babylon.no-module.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375
  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. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  153. */
  154. this.onCompileObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called if an error occurs during shader compilation.
  157. */
  158. this.onErrorObservable = new BABYLON.Observable();
  159. /** @hidden */
  160. this._bonesComputationForcedToCPU = false;
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "onBindObservable", {
  240. /**
  241. * Observable that will be called when effect is bound.
  242. */
  243. get: function () {
  244. if (!this._onBindObservable) {
  245. this._onBindObservable = new BABYLON.Observable();
  246. }
  247. return this._onBindObservable;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. Object.defineProperty(Effect.prototype, "key", {
  253. /**
  254. * Unique key for this effect
  255. */
  256. get: function () {
  257. return this._key;
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. /**
  263. * If the effect has been compiled and prepared.
  264. * @returns if the effect is compiled and prepared.
  265. */
  266. Effect.prototype.isReady = function () {
  267. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  268. return this._engine._isProgramCompiled(this._program);
  269. }
  270. return this._isReady;
  271. };
  272. /**
  273. * The engine the effect was initialized with.
  274. * @returns the engine.
  275. */
  276. Effect.prototype.getEngine = function () {
  277. return this._engine;
  278. };
  279. /**
  280. * The compiled webGL program for the effect
  281. * @returns the webGL program.
  282. */
  283. Effect.prototype.getProgram = function () {
  284. return this._program;
  285. };
  286. /**
  287. * The set of names of attribute variables for the shader.
  288. * @returns An array of attribute names.
  289. */
  290. Effect.prototype.getAttributesNames = function () {
  291. return this._attributesNames;
  292. };
  293. /**
  294. * Returns the attribute at the given index.
  295. * @param index The index of the attribute.
  296. * @returns The location of the attribute.
  297. */
  298. Effect.prototype.getAttributeLocation = function (index) {
  299. return this._attributes[index];
  300. };
  301. /**
  302. * Returns the attribute based on the name of the variable.
  303. * @param name of the attribute to look up.
  304. * @returns the attribute location.
  305. */
  306. Effect.prototype.getAttributeLocationByName = function (name) {
  307. var index = this._attributesNames.indexOf(name);
  308. return this._attributes[index];
  309. };
  310. /**
  311. * The number of attributes.
  312. * @returns the numnber of attributes.
  313. */
  314. Effect.prototype.getAttributesCount = function () {
  315. return this._attributes.length;
  316. };
  317. /**
  318. * Gets the index of a uniform variable.
  319. * @param uniformName of the uniform to look up.
  320. * @returns the index.
  321. */
  322. Effect.prototype.getUniformIndex = function (uniformName) {
  323. return this._uniformsNames.indexOf(uniformName);
  324. };
  325. /**
  326. * Returns the attribute based on the name of the variable.
  327. * @param uniformName of the uniform to look up.
  328. * @returns the location of the uniform.
  329. */
  330. Effect.prototype.getUniform = function (uniformName) {
  331. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  332. };
  333. /**
  334. * Returns an array of sampler variable names
  335. * @returns The array of sampler variable neames.
  336. */
  337. Effect.prototype.getSamplers = function () {
  338. return this._samplers;
  339. };
  340. /**
  341. * The error from the last compilation.
  342. * @returns the error string.
  343. */
  344. Effect.prototype.getCompilationError = function () {
  345. return this._compilationError;
  346. };
  347. /**
  348. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  349. * @param func The callback to be used.
  350. */
  351. Effect.prototype.executeWhenCompiled = function (func) {
  352. var _this = this;
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. if (!this._program || this._program.isParallelCompiled) {
  361. setTimeout(function () {
  362. _this._checkIsReady();
  363. }, 16);
  364. }
  365. };
  366. Effect.prototype._checkIsReady = function () {
  367. var _this = this;
  368. if (this.isReady()) {
  369. return;
  370. }
  371. setTimeout(function () {
  372. _this._checkIsReady();
  373. }, 16);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadVertexShader = function (vertex, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (vertex instanceof HTMLElement) {
  380. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  381. callback(vertexCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (vertex.substr(0, 7) === "base64:") {
  387. var vertexBinary = window.atob(vertex.substr(7));
  388. callback(vertexBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  393. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  394. return;
  395. }
  396. var vertexShaderUrl;
  397. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  398. vertexShaderUrl = vertex;
  399. }
  400. else {
  401. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  402. }
  403. // Vertex shader
  404. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  405. };
  406. /** @hidden */
  407. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  408. if (BABYLON.Tools.IsWindowObjectExist()) {
  409. // DOM element ?
  410. if (fragment instanceof HTMLElement) {
  411. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  412. callback(fragmentCode);
  413. return;
  414. }
  415. }
  416. // Base64 encoded ?
  417. if (fragment.substr(0, 7) === "base64:") {
  418. var fragmentBinary = window.atob(fragment.substr(7));
  419. callback(fragmentBinary);
  420. return;
  421. }
  422. // Is in local store ?
  423. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  424. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  425. return;
  426. }
  427. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  428. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  429. return;
  430. }
  431. var fragmentShaderUrl;
  432. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  433. fragmentShaderUrl = fragment;
  434. }
  435. else {
  436. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  437. }
  438. // Fragment shader
  439. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  440. };
  441. /** @hidden */
  442. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  443. // Rebuild shaders source code
  444. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  445. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  446. vertexCode = prefix + vertexCode;
  447. fragmentCode = prefix + fragmentCode;
  448. // Number lines of shaders source code
  449. var i = 2;
  450. var regex = /\n/gm;
  451. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. i = 2;
  453. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  454. // Dump shaders name and formatted source code
  455. if (this.name.vertexElement) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  458. }
  459. else if (this.name.vertex) {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  462. }
  463. else {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  466. }
  467. };
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. if (isFragment) {
  492. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/texture2D\s*\(/g, "texture(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. * @hidden
  599. */
  600. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  601. var _this = this;
  602. this._isReady = false;
  603. this._vertexSourceCodeOverride = vertexSourceCode;
  604. this._fragmentSourceCodeOverride = fragmentSourceCode;
  605. this.onError = function (effect, error) {
  606. if (onError) {
  607. onError(error);
  608. }
  609. };
  610. this.onCompiled = function () {
  611. var scenes = _this.getEngine().scenes;
  612. for (var i = 0; i < scenes.length; i++) {
  613. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  614. }
  615. if (onCompiled) {
  616. onCompiled(_this._program);
  617. }
  618. };
  619. this._fallbacks = null;
  620. this._prepareEffect();
  621. };
  622. /**
  623. * Gets the uniform locations of the the specified variable names
  624. * @param names THe names of the variables to lookup.
  625. * @returns Array of locations in the same order as variable names.
  626. */
  627. Effect.prototype.getSpecificUniformLocations = function (names) {
  628. var engine = this._engine;
  629. return engine.getUniforms(this._program, names);
  630. };
  631. /**
  632. * Prepares the effect
  633. * @hidden
  634. */
  635. Effect.prototype._prepareEffect = function () {
  636. var _this = this;
  637. var attributesNames = this._attributesNames;
  638. var defines = this.defines;
  639. var fallbacks = this._fallbacks;
  640. this._valueCache = {};
  641. var previousProgram = this._program;
  642. try {
  643. var engine_1 = this._engine;
  644. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  645. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  646. }
  647. else {
  648. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  649. }
  650. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  651. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  652. if (engine_1.supportsUniformBuffers) {
  653. for (var name in _this._uniformBuffersNames) {
  654. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  655. }
  656. }
  657. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  658. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  659. var index;
  660. for (index = 0; index < _this._samplers.length; index++) {
  661. var sampler = _this.getUniform(_this._samplers[index]);
  662. if (sampler == null) {
  663. _this._samplers.splice(index, 1);
  664. index--;
  665. }
  666. }
  667. engine_1.bindSamplers(_this);
  668. _this._compilationError = "";
  669. _this._isReady = true;
  670. if (_this.onCompiled) {
  671. _this.onCompiled(_this);
  672. }
  673. _this.onCompileObservable.notifyObservers(_this);
  674. _this.onCompileObservable.clear();
  675. // Unbind mesh reference in fallbacks
  676. if (_this._fallbacks) {
  677. _this._fallbacks.unBindMesh();
  678. }
  679. if (previousProgram) {
  680. _this.getEngine()._deleteProgram(previousProgram);
  681. }
  682. });
  683. if (this._program.isParallelCompiled) {
  684. this._checkIsReady();
  685. }
  686. }
  687. catch (e) {
  688. this._compilationError = e.message;
  689. // Let's go through fallbacks then
  690. BABYLON.Tools.Error("Unable to compile effect:");
  691. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  692. return " " + uniform;
  693. }));
  694. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  695. return " " + attribute;
  696. }));
  697. BABYLON.Tools.Error("Error: " + this._compilationError);
  698. if (previousProgram) {
  699. this._program = previousProgram;
  700. this._isReady = true;
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. }
  706. if (fallbacks && fallbacks.isMoreFallbacks) {
  707. BABYLON.Tools.Error("Trying next fallback.");
  708. this.defines = fallbacks.reduce(this.defines, this);
  709. this._prepareEffect();
  710. }
  711. else { // Sorry we did everything we can
  712. if (this.onError) {
  713. this.onError(this, this._compilationError);
  714. }
  715. this.onErrorObservable.notifyObservers(this);
  716. this.onErrorObservable.clear();
  717. // Unbind mesh reference in fallbacks
  718. if (this._fallbacks) {
  719. this._fallbacks.unBindMesh();
  720. }
  721. }
  722. }
  723. };
  724. Object.defineProperty(Effect.prototype, "isSupported", {
  725. /**
  726. * Checks if the effect is supported. (Must be called after compilation)
  727. */
  728. get: function () {
  729. return this._compilationError === "";
  730. },
  731. enumerable: true,
  732. configurable: true
  733. });
  734. /**
  735. * Binds a texture to the engine to be used as output of the shader.
  736. * @param channel Name of the output variable.
  737. * @param texture Texture to bind.
  738. * @hidden
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value) {
  899. return this;
  900. }
  901. this._valueCache[uniformName] = value;
  902. this._engine.setInt(this.getUniform(uniformName), value);
  903. return this;
  904. };
  905. /**
  906. * Sets an int array on a uniform variable.
  907. * @param uniformName Name of the variable.
  908. * @param array array to be set.
  909. * @returns this effect.
  910. */
  911. Effect.prototype.setIntArray = function (uniformName, array) {
  912. this._valueCache[uniformName] = null;
  913. this._engine.setIntArray(this.getUniform(uniformName), array);
  914. return this;
  915. };
  916. /**
  917. * 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)
  918. * @param uniformName Name of the variable.
  919. * @param array array to be set.
  920. * @returns this effect.
  921. */
  922. Effect.prototype.setIntArray2 = function (uniformName, array) {
  923. this._valueCache[uniformName] = null;
  924. this._engine.setIntArray2(this.getUniform(uniformName), array);
  925. return this;
  926. };
  927. /**
  928. * 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)
  929. * @param uniformName Name of the variable.
  930. * @param array array to be set.
  931. * @returns this effect.
  932. */
  933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  934. this._valueCache[uniformName] = null;
  935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  936. return this;
  937. };
  938. /**
  939. * 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)
  940. * @param uniformName Name of the variable.
  941. * @param array array to be set.
  942. * @returns this effect.
  943. */
  944. Effect.prototype.setIntArray4 = function (uniformName, array) {
  945. this._valueCache[uniformName] = null;
  946. this._engine.setIntArray4(this.getUniform(uniformName), array);
  947. return this;
  948. };
  949. /**
  950. * Sets an float array on a uniform variable.
  951. * @param uniformName Name of the variable.
  952. * @param array array to be set.
  953. * @returns this effect.
  954. */
  955. Effect.prototype.setFloatArray = function (uniformName, array) {
  956. this._valueCache[uniformName] = null;
  957. this._engine.setFloatArray(this.getUniform(uniformName), array);
  958. return this;
  959. };
  960. /**
  961. * 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)
  962. * @param uniformName Name of the variable.
  963. * @param array array to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  967. this._valueCache[uniformName] = null;
  968. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  969. return this;
  970. };
  971. /**
  972. * 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)
  973. * @param uniformName Name of the variable.
  974. * @param array array to be set.
  975. * @returns this effect.
  976. */
  977. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  978. this._valueCache[uniformName] = null;
  979. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  980. return this;
  981. };
  982. /**
  983. * 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)
  984. * @param uniformName Name of the variable.
  985. * @param array array to be set.
  986. * @returns this effect.
  987. */
  988. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  989. this._valueCache[uniformName] = null;
  990. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  991. return this;
  992. };
  993. /**
  994. * Sets an array on a uniform variable.
  995. * @param uniformName Name of the variable.
  996. * @param array array to be set.
  997. * @returns this effect.
  998. */
  999. Effect.prototype.setArray = function (uniformName, array) {
  1000. this._valueCache[uniformName] = null;
  1001. this._engine.setArray(this.getUniform(uniformName), array);
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param array array to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setArray2 = function (uniformName, array) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setArray2(this.getUniform(uniformName), array);
  1013. return this;
  1014. };
  1015. /**
  1016. * 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)
  1017. * @param uniformName Name of the variable.
  1018. * @param array array to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setArray3 = function (uniformName, array) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setArray3(this.getUniform(uniformName), array);
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param array array to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setArray4 = function (uniformName, array) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setArray4(this.getUniform(uniformName), array);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets matrices on a uniform variable.
  1039. * @param uniformName Name of the variable.
  1040. * @param matrices matrices to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1044. if (!matrices) {
  1045. return this;
  1046. }
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets matrix on a uniform variable.
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1058. if (this._cacheMatrix(uniformName, matrix)) {
  1059. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1060. }
  1061. return this;
  1062. };
  1063. /**
  1064. * 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)
  1065. * @param uniformName Name of the variable.
  1066. * @param matrix matrix to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1076. * @param uniformName Name of the variable.
  1077. * @param matrix matrix to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param value value to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setFloat = function (uniformName, value) {
  1092. var cache = this._valueCache[uniformName];
  1093. if (cache !== undefined && cache === value) {
  1094. return this;
  1095. }
  1096. this._valueCache[uniformName] = value;
  1097. this._engine.setFloat(this.getUniform(uniformName), value);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a boolean on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param bool value to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setBool = function (uniformName, bool) {
  1107. var cache = this._valueCache[uniformName];
  1108. if (cache !== undefined && cache === bool) {
  1109. return this;
  1110. }
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * 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.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /** Class used to store color4 gradient */
  1460. var ColorGradient = /** @class */ (function () {
  1461. function ColorGradient() {
  1462. }
  1463. /**
  1464. * Will get a color picked randomly between color1 and color2.
  1465. * If color2 is undefined then color1 will be used
  1466. * @param result defines the target Color4 to store the result in
  1467. */
  1468. ColorGradient.prototype.getColorToRef = function (result) {
  1469. if (!this.color2) {
  1470. result.copyFrom(this.color1);
  1471. return;
  1472. }
  1473. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1474. };
  1475. return ColorGradient;
  1476. }());
  1477. BABYLON.ColorGradient = ColorGradient;
  1478. /** Class used to store color 3 gradient */
  1479. var Color3Gradient = /** @class */ (function () {
  1480. function Color3Gradient() {
  1481. }
  1482. return Color3Gradient;
  1483. }());
  1484. BABYLON.Color3Gradient = Color3Gradient;
  1485. /** Class used to store factor gradient */
  1486. var FactorGradient = /** @class */ (function () {
  1487. function FactorGradient() {
  1488. }
  1489. /**
  1490. * Will get a number picked randomly between factor1 and factor2.
  1491. * If factor2 is undefined then factor1 will be used
  1492. * @returns the picked number
  1493. */
  1494. FactorGradient.prototype.getFactor = function () {
  1495. if (this.factor2 === undefined) {
  1496. return this.factor1;
  1497. }
  1498. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1499. };
  1500. return FactorGradient;
  1501. }());
  1502. BABYLON.FactorGradient = FactorGradient;
  1503. /**
  1504. * @ignore
  1505. * Application error to support additional information when loading a file
  1506. */
  1507. var LoadFileError = /** @class */ (function (_super) {
  1508. __extends(LoadFileError, _super);
  1509. /**
  1510. * Creates a new LoadFileError
  1511. * @param message defines the message of the error
  1512. * @param request defines the optional XHR request
  1513. */
  1514. function LoadFileError(message,
  1515. /** defines the optional XHR request */
  1516. request) {
  1517. var _this = _super.call(this, message) || this;
  1518. _this.request = request;
  1519. _this.name = "LoadFileError";
  1520. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1521. return _this;
  1522. }
  1523. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1524. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1525. // Polyfill for Object.setPrototypeOf if necessary.
  1526. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1527. return LoadFileError;
  1528. }(Error));
  1529. BABYLON.LoadFileError = LoadFileError;
  1530. /**
  1531. * Class used to define a retry strategy when error happens while loading assets
  1532. */
  1533. var RetryStrategy = /** @class */ (function () {
  1534. function RetryStrategy() {
  1535. }
  1536. /**
  1537. * Function used to defines an exponential back off strategy
  1538. * @param maxRetries defines the maximum number of retries (3 by default)
  1539. * @param baseInterval defines the interval between retries
  1540. * @returns the strategy function to use
  1541. */
  1542. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1543. if (maxRetries === void 0) { maxRetries = 3; }
  1544. if (baseInterval === void 0) { baseInterval = 500; }
  1545. return function (url, request, retryIndex) {
  1546. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1547. return -1;
  1548. }
  1549. return Math.pow(2, retryIndex) * baseInterval;
  1550. };
  1551. };
  1552. return RetryStrategy;
  1553. }());
  1554. BABYLON.RetryStrategy = RetryStrategy;
  1555. // Screenshots
  1556. var screenshotCanvas;
  1557. var cloneValue = function (source, destinationObject) {
  1558. if (!source) {
  1559. return null;
  1560. }
  1561. if (source instanceof BABYLON.Mesh) {
  1562. return null;
  1563. }
  1564. if (source instanceof BABYLON.SubMesh) {
  1565. return source.clone(destinationObject);
  1566. }
  1567. else if (source.clone) {
  1568. return source.clone();
  1569. }
  1570. return null;
  1571. };
  1572. /**
  1573. * Class containing a set of static utilities functions
  1574. */
  1575. var Tools = /** @class */ (function () {
  1576. function Tools() {
  1577. }
  1578. /**
  1579. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1580. * @param u defines the coordinate on X axis
  1581. * @param v defines the coordinate on Y axis
  1582. * @param width defines the width of the source data
  1583. * @param height defines the height of the source data
  1584. * @param pixels defines the source byte array
  1585. * @param color defines the output color
  1586. */
  1587. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1588. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1589. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1590. var position = (wrappedU + wrappedV * width) * 4;
  1591. color.r = pixels[position] / 255;
  1592. color.g = pixels[position + 1] / 255;
  1593. color.b = pixels[position + 2] / 255;
  1594. color.a = pixels[position + 3] / 255;
  1595. };
  1596. /**
  1597. * Interpolates between a and b via alpha
  1598. * @param a The lower value (returned when alpha = 0)
  1599. * @param b The upper value (returned when alpha = 1)
  1600. * @param alpha The interpolation-factor
  1601. * @return The mixed value
  1602. */
  1603. Tools.Mix = function (a, b, alpha) {
  1604. return a * (1 - alpha) + b * alpha;
  1605. };
  1606. /**
  1607. * Tries to instantiate a new object from a given class name
  1608. * @param className defines the class name to instantiate
  1609. * @returns the new object or null if the system was not able to do the instantiation
  1610. */
  1611. Tools.Instantiate = function (className) {
  1612. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1613. return Tools.RegisteredExternalClasses[className];
  1614. }
  1615. var arr = className.split(".");
  1616. var fn = (window || this);
  1617. for (var i = 0, len = arr.length; i < len; i++) {
  1618. fn = fn[arr[i]];
  1619. }
  1620. if (typeof fn !== "function") {
  1621. return null;
  1622. }
  1623. return fn;
  1624. };
  1625. /**
  1626. * Provides a slice function that will work even on IE
  1627. * @param data defines the array to slice
  1628. * @param start defines the start of the data (optional)
  1629. * @param end defines the end of the data (optional)
  1630. * @returns the new sliced array
  1631. */
  1632. Tools.Slice = function (data, start, end) {
  1633. if (data.slice) {
  1634. return data.slice(start, end);
  1635. }
  1636. return Array.prototype.slice.call(data, start, end);
  1637. };
  1638. /**
  1639. * Polyfill for setImmediate
  1640. * @param action defines the action to execute after the current execution block
  1641. */
  1642. Tools.SetImmediate = function (action) {
  1643. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1644. window.setImmediate(action);
  1645. }
  1646. else {
  1647. setTimeout(action, 1);
  1648. }
  1649. };
  1650. /**
  1651. * Function indicating if a number is an exponent of 2
  1652. * @param value defines the value to test
  1653. * @returns true if the value is an exponent of 2
  1654. */
  1655. Tools.IsExponentOfTwo = function (value) {
  1656. var count = 1;
  1657. do {
  1658. count *= 2;
  1659. } while (count < value);
  1660. return count === value;
  1661. };
  1662. /**
  1663. * Returns the nearest 32-bit single precision float representation of a Number
  1664. * @param value A Number. If the parameter is of a different type, it will get converted
  1665. * to a number or to NaN if it cannot be converted
  1666. * @returns number
  1667. */
  1668. Tools.FloatRound = function (value) {
  1669. if (Math.fround) {
  1670. return Math.fround(value);
  1671. }
  1672. return (Tools._tmpFloatArray[0] = value);
  1673. };
  1674. /**
  1675. * Find the next highest power of two.
  1676. * @param x Number to start search from.
  1677. * @return Next highest power of two.
  1678. */
  1679. Tools.CeilingPOT = function (x) {
  1680. x--;
  1681. x |= x >> 1;
  1682. x |= x >> 2;
  1683. x |= x >> 4;
  1684. x |= x >> 8;
  1685. x |= x >> 16;
  1686. x++;
  1687. return x;
  1688. };
  1689. /**
  1690. * Find the next lowest power of two.
  1691. * @param x Number to start search from.
  1692. * @return Next lowest power of two.
  1693. */
  1694. Tools.FloorPOT = function (x) {
  1695. x = x | (x >> 1);
  1696. x = x | (x >> 2);
  1697. x = x | (x >> 4);
  1698. x = x | (x >> 8);
  1699. x = x | (x >> 16);
  1700. return x - (x >> 1);
  1701. };
  1702. /**
  1703. * Find the nearest power of two.
  1704. * @param x Number to start search from.
  1705. * @return Next nearest power of two.
  1706. */
  1707. Tools.NearestPOT = function (x) {
  1708. var c = Tools.CeilingPOT(x);
  1709. var f = Tools.FloorPOT(x);
  1710. return (c - x) > (x - f) ? f : c;
  1711. };
  1712. /**
  1713. * Get the closest exponent of two
  1714. * @param value defines the value to approximate
  1715. * @param max defines the maximum value to return
  1716. * @param mode defines how to define the closest value
  1717. * @returns closest exponent of two of the given value
  1718. */
  1719. Tools.GetExponentOfTwo = function (value, max, mode) {
  1720. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1721. var pot;
  1722. switch (mode) {
  1723. case BABYLON.Engine.SCALEMODE_FLOOR:
  1724. pot = Tools.FloorPOT(value);
  1725. break;
  1726. case BABYLON.Engine.SCALEMODE_NEAREST:
  1727. pot = Tools.NearestPOT(value);
  1728. break;
  1729. case BABYLON.Engine.SCALEMODE_CEILING:
  1730. default:
  1731. pot = Tools.CeilingPOT(value);
  1732. break;
  1733. }
  1734. return Math.min(pot, max);
  1735. };
  1736. /**
  1737. * Extracts the filename from a path
  1738. * @param path defines the path to use
  1739. * @returns the filename
  1740. */
  1741. Tools.GetFilename = function (path) {
  1742. var index = path.lastIndexOf("/");
  1743. if (index < 0) {
  1744. return path;
  1745. }
  1746. return path.substring(index + 1);
  1747. };
  1748. /**
  1749. * Extracts the "folder" part of a path (everything before the filename).
  1750. * @param uri The URI to extract the info from
  1751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1752. * @returns The "folder" part of the path
  1753. */
  1754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1756. var index = uri.lastIndexOf("/");
  1757. if (index < 0) {
  1758. if (returnUnchangedIfNoSlash) {
  1759. return uri;
  1760. }
  1761. return "";
  1762. }
  1763. return uri.substring(0, index + 1);
  1764. };
  1765. /**
  1766. * Extracts text content from a DOM element hierarchy
  1767. * @param element defines the root element
  1768. * @returns a string
  1769. */
  1770. Tools.GetDOMTextContent = function (element) {
  1771. var result = "";
  1772. var child = element.firstChild;
  1773. while (child) {
  1774. if (child.nodeType === 3) {
  1775. result += child.textContent;
  1776. }
  1777. child = child.nextSibling;
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Convert an angle in radians to degrees
  1783. * @param angle defines the angle to convert
  1784. * @returns the angle in degrees
  1785. */
  1786. Tools.ToDegrees = function (angle) {
  1787. return angle * 180 / Math.PI;
  1788. };
  1789. /**
  1790. * Convert an angle in degrees to radians
  1791. * @param angle defines the angle to convert
  1792. * @returns the angle in radians
  1793. */
  1794. Tools.ToRadians = function (angle) {
  1795. return angle * Math.PI / 180;
  1796. };
  1797. /**
  1798. * Encode a buffer to a base64 string
  1799. * @param buffer defines the buffer to encode
  1800. * @returns the encoded string
  1801. */
  1802. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1803. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1804. var output = "";
  1805. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1806. var i = 0;
  1807. var bytes = new Uint8Array(buffer);
  1808. while (i < bytes.length) {
  1809. chr1 = bytes[i++];
  1810. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1811. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1812. enc1 = chr1 >> 2;
  1813. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1814. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1815. enc4 = chr3 & 63;
  1816. if (isNaN(chr2)) {
  1817. enc3 = enc4 = 64;
  1818. }
  1819. else if (isNaN(chr3)) {
  1820. enc4 = 64;
  1821. }
  1822. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1823. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1824. }
  1825. return "data:image/png;base64," + output;
  1826. };
  1827. /**
  1828. * Extracts minimum and maximum values from a list of indexed positions
  1829. * @param positions defines the positions to use
  1830. * @param indices defines the indices to the positions
  1831. * @param indexStart defines the start index
  1832. * @param indexCount defines the end index
  1833. * @param bias defines bias value to add to the result
  1834. * @return minimum and maximum values
  1835. */
  1836. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1837. if (bias === void 0) { bias = null; }
  1838. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1839. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1840. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1841. var offset = indices[index] * 3;
  1842. var x = positions[offset];
  1843. var y = positions[offset + 1];
  1844. var z = positions[offset + 2];
  1845. minimum.minimizeInPlaceFromFloats(x, y, z);
  1846. maximum.maximizeInPlaceFromFloats(x, y, z);
  1847. }
  1848. if (bias) {
  1849. minimum.x -= minimum.x * bias.x + bias.y;
  1850. minimum.y -= minimum.y * bias.x + bias.y;
  1851. minimum.z -= minimum.z * bias.x + bias.y;
  1852. maximum.x += maximum.x * bias.x + bias.y;
  1853. maximum.y += maximum.y * bias.x + bias.y;
  1854. maximum.z += maximum.z * bias.x + bias.y;
  1855. }
  1856. return {
  1857. minimum: minimum,
  1858. maximum: maximum
  1859. };
  1860. };
  1861. /**
  1862. * Extracts minimum and maximum values from a list of positions
  1863. * @param positions defines the positions to use
  1864. * @param start defines the start index in the positions array
  1865. * @param count defines the number of positions to handle
  1866. * @param bias defines bias value to add to the result
  1867. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1868. * @return minimum and maximum values
  1869. */
  1870. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1871. if (bias === void 0) { bias = null; }
  1872. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1873. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1874. if (!stride) {
  1875. stride = 3;
  1876. }
  1877. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1878. var x = positions[offset];
  1879. var y = positions[offset + 1];
  1880. var z = positions[offset + 2];
  1881. minimum.minimizeInPlaceFromFloats(x, y, z);
  1882. maximum.maximizeInPlaceFromFloats(x, y, z);
  1883. }
  1884. if (bias) {
  1885. minimum.x -= minimum.x * bias.x + bias.y;
  1886. minimum.y -= minimum.y * bias.x + bias.y;
  1887. minimum.z -= minimum.z * bias.x + bias.y;
  1888. maximum.x += maximum.x * bias.x + bias.y;
  1889. maximum.y += maximum.y * bias.x + bias.y;
  1890. maximum.z += maximum.z * bias.x + bias.y;
  1891. }
  1892. return {
  1893. minimum: minimum,
  1894. maximum: maximum
  1895. };
  1896. };
  1897. /**
  1898. * Returns an array if obj is not an array
  1899. * @param obj defines the object to evaluate as an array
  1900. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1901. * @returns either obj directly if obj is an array or a new array containing obj
  1902. */
  1903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1904. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1905. return null;
  1906. }
  1907. return Array.isArray(obj) ? obj : [obj];
  1908. };
  1909. /**
  1910. * Returns an array of the given size filled with element built from the given constructor and the paramters
  1911. * @param size the number of element to construct and put in the array
  1912. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  1913. * @returns a new array filled with new objects
  1914. */
  1915. Tools.BuildArray = function (size, itemBuilder) {
  1916. var a = [];
  1917. for (var i = 0; i < size; ++i) {
  1918. a.push(itemBuilder());
  1919. }
  1920. return a;
  1921. };
  1922. /**
  1923. * Gets the pointer prefix to use
  1924. * @returns "pointer" if touch is enabled. Else returns "mouse"
  1925. */
  1926. Tools.GetPointerPrefix = function () {
  1927. var eventPrefix = "pointer";
  1928. // Check if pointer events are supported
  1929. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  1930. eventPrefix = "mouse";
  1931. }
  1932. return eventPrefix;
  1933. };
  1934. /**
  1935. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  1936. * @param func - the function to be called
  1937. * @param requester - the object that will request the next frame. Falls back to window.
  1938. * @returns frame number
  1939. */
  1940. Tools.QueueNewFrame = function (func, requester) {
  1941. if (!Tools.IsWindowObjectExist()) {
  1942. return setTimeout(func, 16);
  1943. }
  1944. if (!requester) {
  1945. requester = window;
  1946. }
  1947. if (requester.requestAnimationFrame) {
  1948. return requester.requestAnimationFrame(func);
  1949. }
  1950. else if (requester.msRequestAnimationFrame) {
  1951. return requester.msRequestAnimationFrame(func);
  1952. }
  1953. else if (requester.webkitRequestAnimationFrame) {
  1954. return requester.webkitRequestAnimationFrame(func);
  1955. }
  1956. else if (requester.mozRequestAnimationFrame) {
  1957. return requester.mozRequestAnimationFrame(func);
  1958. }
  1959. else if (requester.oRequestAnimationFrame) {
  1960. return requester.oRequestAnimationFrame(func);
  1961. }
  1962. else {
  1963. return window.setTimeout(func, 16);
  1964. }
  1965. };
  1966. /**
  1967. * Ask the browser to promote the current element to fullscreen rendering mode
  1968. * @param element defines the DOM element to promote
  1969. */
  1970. Tools.RequestFullscreen = function (element) {
  1971. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  1972. if (!requestFunction) {
  1973. return;
  1974. }
  1975. requestFunction.call(element);
  1976. };
  1977. /**
  1978. * Asks the browser to exit fullscreen mode
  1979. */
  1980. Tools.ExitFullscreen = function () {
  1981. if (document.exitFullscreen) {
  1982. document.exitFullscreen();
  1983. }
  1984. else if (document.mozCancelFullScreen) {
  1985. document.mozCancelFullScreen();
  1986. }
  1987. else if (document.webkitCancelFullScreen) {
  1988. document.webkitCancelFullScreen();
  1989. }
  1990. else if (document.msCancelFullScreen) {
  1991. document.msCancelFullScreen();
  1992. }
  1993. };
  1994. /**
  1995. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  1996. * @param url define the url we are trying
  1997. * @param element define the dom element where to configure the cors policy
  1998. */
  1999. Tools.SetCorsBehavior = function (url, element) {
  2000. if (url && url.indexOf("data:") === 0) {
  2001. return;
  2002. }
  2003. if (Tools.CorsBehavior) {
  2004. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2005. element.crossOrigin = Tools.CorsBehavior;
  2006. }
  2007. else {
  2008. var result = Tools.CorsBehavior(url);
  2009. if (result) {
  2010. element.crossOrigin = result;
  2011. }
  2012. }
  2013. }
  2014. };
  2015. // External files
  2016. /**
  2017. * Removes unwanted characters from an url
  2018. * @param url defines the url to clean
  2019. * @returns the cleaned url
  2020. */
  2021. Tools.CleanUrl = function (url) {
  2022. url = url.replace(/#/mg, "%23");
  2023. return url;
  2024. };
  2025. /**
  2026. * Loads an image as an HTMLImageElement.
  2027. * @param input url string, ArrayBuffer, or Blob to load
  2028. * @param onLoad callback called when the image successfully loads
  2029. * @param onError callback called when the image fails to load
  2030. * @param offlineProvider offline provider for caching
  2031. * @returns the HTMLImageElement of the loaded image
  2032. */
  2033. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2034. var url;
  2035. var usingObjectURL = false;
  2036. if (input instanceof ArrayBuffer) {
  2037. url = URL.createObjectURL(new Blob([input]));
  2038. usingObjectURL = true;
  2039. }
  2040. else if (input instanceof Blob) {
  2041. url = URL.createObjectURL(input);
  2042. usingObjectURL = true;
  2043. }
  2044. else {
  2045. url = Tools.CleanUrl(input);
  2046. url = Tools.PreprocessUrl(input);
  2047. }
  2048. var img = new Image();
  2049. Tools.SetCorsBehavior(url, img);
  2050. var loadHandler = function () {
  2051. if (usingObjectURL && img.src) {
  2052. URL.revokeObjectURL(img.src);
  2053. }
  2054. img.removeEventListener("load", loadHandler);
  2055. img.removeEventListener("error", errorHandler);
  2056. onLoad(img);
  2057. };
  2058. var errorHandler = function (err) {
  2059. if (usingObjectURL && img.src) {
  2060. URL.revokeObjectURL(img.src);
  2061. }
  2062. img.removeEventListener("load", loadHandler);
  2063. img.removeEventListener("error", errorHandler);
  2064. Tools.Error("Error while trying to load image: " + input);
  2065. if (onError) {
  2066. onError("Error while trying to load image: " + input, err);
  2067. }
  2068. };
  2069. img.addEventListener("load", loadHandler);
  2070. img.addEventListener("error", errorHandler);
  2071. var noOfflineSupport = function () {
  2072. img.src = url;
  2073. };
  2074. var loadFromOfflineSupport = function () {
  2075. if (offlineProvider) {
  2076. offlineProvider.loadImage(url, img);
  2077. }
  2078. };
  2079. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2080. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2081. }
  2082. else {
  2083. if (url.indexOf("file:") !== -1) {
  2084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2086. try {
  2087. var blobURL;
  2088. try {
  2089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2090. }
  2091. catch (ex) {
  2092. // Chrome doesn't support oneTimeOnly parameter
  2093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2094. }
  2095. img.src = blobURL;
  2096. usingObjectURL = true;
  2097. }
  2098. catch (e) {
  2099. img.src = "";
  2100. }
  2101. return img;
  2102. }
  2103. }
  2104. noOfflineSupport();
  2105. }
  2106. return img;
  2107. };
  2108. /**
  2109. * Loads a file
  2110. * @param url url string, ArrayBuffer, or Blob to load
  2111. * @param onSuccess callback called when the file successfully loads
  2112. * @param onProgress callback called while file is loading (if the server supports this mode)
  2113. * @param offlineProvider defines the offline provider for caching
  2114. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2115. * @param onError callback called when the file fails to load
  2116. * @returns a file request object
  2117. */
  2118. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2119. url = Tools.CleanUrl(url);
  2120. url = Tools.PreprocessUrl(url);
  2121. // If file and file input are set
  2122. if (url.indexOf("file:") !== -1) {
  2123. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2124. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2125. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2126. }
  2127. }
  2128. var loadUrl = Tools.BaseUrl + url;
  2129. var aborted = false;
  2130. var fileRequest = {
  2131. onCompleteObservable: new BABYLON.Observable(),
  2132. abort: function () { return aborted = true; },
  2133. };
  2134. var requestFile = function () {
  2135. var request = new XMLHttpRequest();
  2136. var retryHandle = null;
  2137. fileRequest.abort = function () {
  2138. aborted = true;
  2139. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2140. request.abort();
  2141. }
  2142. if (retryHandle !== null) {
  2143. clearTimeout(retryHandle);
  2144. retryHandle = null;
  2145. }
  2146. };
  2147. var retryLoop = function (retryIndex) {
  2148. request.open('GET', loadUrl, true);
  2149. if (useArrayBuffer) {
  2150. request.responseType = "arraybuffer";
  2151. }
  2152. if (onProgress) {
  2153. request.addEventListener("progress", onProgress);
  2154. }
  2155. var onLoadEnd = function () {
  2156. request.removeEventListener("loadend", onLoadEnd);
  2157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2158. fileRequest.onCompleteObservable.clear();
  2159. };
  2160. request.addEventListener("loadend", onLoadEnd);
  2161. var onReadyStateChange = function () {
  2162. if (aborted) {
  2163. return;
  2164. }
  2165. // In case of undefined state in some browsers.
  2166. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2167. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2168. request.removeEventListener("readystatechange", onReadyStateChange);
  2169. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2170. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2171. return;
  2172. }
  2173. var retryStrategy = Tools.DefaultRetryStrategy;
  2174. if (retryStrategy) {
  2175. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2176. if (waitTime !== -1) {
  2177. // Prevent the request from completing for retry.
  2178. request.removeEventListener("loadend", onLoadEnd);
  2179. request = new XMLHttpRequest();
  2180. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2181. return;
  2182. }
  2183. }
  2184. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2185. if (onError) {
  2186. onError(request, e);
  2187. }
  2188. else {
  2189. throw e;
  2190. }
  2191. }
  2192. };
  2193. request.addEventListener("readystatechange", onReadyStateChange);
  2194. request.send();
  2195. };
  2196. retryLoop(0);
  2197. };
  2198. // Caching all files
  2199. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2200. var noOfflineSupport_1 = function (request) {
  2201. if (request && request.status > 400) {
  2202. if (onError) {
  2203. onError(request);
  2204. }
  2205. }
  2206. else {
  2207. if (!aborted) {
  2208. requestFile();
  2209. }
  2210. }
  2211. };
  2212. var loadFromOfflineSupport = function () {
  2213. // TODO: database needs to support aborting and should return a IFileRequest
  2214. if (aborted) {
  2215. return;
  2216. }
  2217. if (offlineProvider) {
  2218. offlineProvider.loadFile(url, function (data) {
  2219. if (!aborted) {
  2220. onSuccess(data);
  2221. }
  2222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2223. }, onProgress ? function (event) {
  2224. if (!aborted) {
  2225. onProgress(event);
  2226. }
  2227. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2228. }
  2229. };
  2230. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2231. }
  2232. else {
  2233. requestFile();
  2234. }
  2235. return fileRequest;
  2236. };
  2237. /**
  2238. * Load a script (identified by an url). When the url returns, the
  2239. * content of this file is added into a new script element, attached to the DOM (body element)
  2240. * @param scriptUrl defines the url of the script to laod
  2241. * @param onSuccess defines the callback called when the script is loaded
  2242. * @param onError defines the callback to call if an error occurs
  2243. */
  2244. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2245. if (!Tools.IsWindowObjectExist()) {
  2246. return;
  2247. }
  2248. var head = document.getElementsByTagName('head')[0];
  2249. var script = document.createElement('script');
  2250. script.type = 'text/javascript';
  2251. script.src = scriptUrl;
  2252. script.onload = function () {
  2253. if (onSuccess) {
  2254. onSuccess();
  2255. }
  2256. };
  2257. script.onerror = function (e) {
  2258. if (onError) {
  2259. onError("Unable to load script '" + scriptUrl + "'", e);
  2260. }
  2261. };
  2262. head.appendChild(script);
  2263. };
  2264. /**
  2265. * Loads a file from a blob
  2266. * @param fileToLoad defines the blob to use
  2267. * @param callback defines the callback to call when data is loaded
  2268. * @param progressCallback defines the callback to call during loading process
  2269. * @returns a file request object
  2270. */
  2271. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2272. var reader = new FileReader();
  2273. var request = {
  2274. onCompleteObservable: new BABYLON.Observable(),
  2275. abort: function () { return reader.abort(); },
  2276. };
  2277. reader.onloadend = function (e) {
  2278. request.onCompleteObservable.notifyObservers(request);
  2279. };
  2280. reader.onload = function (e) {
  2281. //target doesn't have result from ts 1.3
  2282. callback(e.target['result']);
  2283. };
  2284. reader.onprogress = progressCallback;
  2285. reader.readAsDataURL(fileToLoad);
  2286. return request;
  2287. };
  2288. /**
  2289. * Loads a file
  2290. * @param fileToLoad defines the file to load
  2291. * @param callback defines the callback to call when data is loaded
  2292. * @param progressCallBack defines the callback to call during loading process
  2293. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2294. * @returns a file request object
  2295. */
  2296. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2297. var reader = new FileReader();
  2298. var request = {
  2299. onCompleteObservable: new BABYLON.Observable(),
  2300. abort: function () { return reader.abort(); },
  2301. };
  2302. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2303. reader.onerror = function (e) {
  2304. Tools.Log("Error while reading file: " + fileToLoad.name);
  2305. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2306. };
  2307. reader.onload = function (e) {
  2308. //target doesn't have result from ts 1.3
  2309. callback(e.target['result']);
  2310. };
  2311. if (progressCallBack) {
  2312. reader.onprogress = progressCallBack;
  2313. }
  2314. if (!useArrayBuffer) {
  2315. // Asynchronous read
  2316. reader.readAsText(fileToLoad);
  2317. }
  2318. else {
  2319. reader.readAsArrayBuffer(fileToLoad);
  2320. }
  2321. return request;
  2322. };
  2323. /**
  2324. * Creates a data url from a given string content
  2325. * @param content defines the content to convert
  2326. * @returns the new data url link
  2327. */
  2328. Tools.FileAsURL = function (content) {
  2329. var fileBlob = new Blob([content]);
  2330. var url = window.URL || window.webkitURL;
  2331. var link = url.createObjectURL(fileBlob);
  2332. return link;
  2333. };
  2334. /**
  2335. * Format the given number to a specific decimal format
  2336. * @param value defines the number to format
  2337. * @param decimals defines the number of decimals to use
  2338. * @returns the formatted string
  2339. */
  2340. Tools.Format = function (value, decimals) {
  2341. if (decimals === void 0) { decimals = 2; }
  2342. return value.toFixed(decimals);
  2343. };
  2344. /**
  2345. * Checks if a given vector is inside a specific range
  2346. * @param v defines the vector to test
  2347. * @param min defines the minimum range
  2348. * @param max defines the maximum range
  2349. */
  2350. Tools.CheckExtends = function (v, min, max) {
  2351. min.minimizeInPlace(v);
  2352. max.maximizeInPlace(v);
  2353. };
  2354. /**
  2355. * Tries to copy an object by duplicating every property
  2356. * @param source defines the source object
  2357. * @param destination defines the target object
  2358. * @param doNotCopyList defines a list of properties to avoid
  2359. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2360. */
  2361. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2362. for (var prop in source) {
  2363. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2364. continue;
  2365. }
  2366. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2367. continue;
  2368. }
  2369. var sourceValue = source[prop];
  2370. var typeOfSourceValue = typeof sourceValue;
  2371. if (typeOfSourceValue === "function") {
  2372. continue;
  2373. }
  2374. try {
  2375. if (typeOfSourceValue === "object") {
  2376. if (sourceValue instanceof Array) {
  2377. destination[prop] = [];
  2378. if (sourceValue.length > 0) {
  2379. if (typeof sourceValue[0] == "object") {
  2380. for (var index = 0; index < sourceValue.length; index++) {
  2381. var clonedValue = cloneValue(sourceValue[index], destination);
  2382. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2383. destination[prop].push(clonedValue);
  2384. }
  2385. }
  2386. }
  2387. else {
  2388. destination[prop] = sourceValue.slice(0);
  2389. }
  2390. }
  2391. }
  2392. else {
  2393. destination[prop] = cloneValue(sourceValue, destination);
  2394. }
  2395. }
  2396. else {
  2397. destination[prop] = sourceValue;
  2398. }
  2399. }
  2400. catch (e) {
  2401. // Just ignore error (it could be because of a read-only property)
  2402. }
  2403. }
  2404. };
  2405. /**
  2406. * Gets a boolean indicating if the given object has no own property
  2407. * @param obj defines the object to test
  2408. * @returns true if object has no own property
  2409. */
  2410. Tools.IsEmpty = function (obj) {
  2411. for (var i in obj) {
  2412. if (obj.hasOwnProperty(i)) {
  2413. return false;
  2414. }
  2415. }
  2416. return true;
  2417. };
  2418. /**
  2419. * Function used to register events at window level
  2420. * @param events defines the events to register
  2421. */
  2422. Tools.RegisterTopRootEvents = function (events) {
  2423. for (var index = 0; index < events.length; index++) {
  2424. var event = events[index];
  2425. window.addEventListener(event.name, event.handler, false);
  2426. try {
  2427. if (window.parent) {
  2428. window.parent.addEventListener(event.name, event.handler, false);
  2429. }
  2430. }
  2431. catch (e) {
  2432. // Silently fails...
  2433. }
  2434. }
  2435. };
  2436. /**
  2437. * Function used to unregister events from window level
  2438. * @param events defines the events to unregister
  2439. */
  2440. Tools.UnregisterTopRootEvents = function (events) {
  2441. for (var index = 0; index < events.length; index++) {
  2442. var event = events[index];
  2443. window.removeEventListener(event.name, event.handler);
  2444. try {
  2445. if (window.parent) {
  2446. window.parent.removeEventListener(event.name, event.handler);
  2447. }
  2448. }
  2449. catch (e) {
  2450. // Silently fails...
  2451. }
  2452. }
  2453. };
  2454. /**
  2455. * Dumps the current bound framebuffer
  2456. * @param width defines the rendering width
  2457. * @param height defines the rendering height
  2458. * @param engine defines the hosting engine
  2459. * @param successCallback defines the callback triggered once the data are available
  2460. * @param mimeType defines the mime type of the result
  2461. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2462. */
  2463. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2464. if (mimeType === void 0) { mimeType = "image/png"; }
  2465. // Read the contents of the framebuffer
  2466. var numberOfChannelsByLine = width * 4;
  2467. var halfHeight = height / 2;
  2468. //Reading datas from WebGL
  2469. var data = engine.readPixels(0, 0, width, height);
  2470. //To flip image on Y axis.
  2471. for (var i = 0; i < halfHeight; i++) {
  2472. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2473. var currentCell = j + i * numberOfChannelsByLine;
  2474. var targetLine = height - i - 1;
  2475. var targetCell = j + targetLine * numberOfChannelsByLine;
  2476. var temp = data[currentCell];
  2477. data[currentCell] = data[targetCell];
  2478. data[targetCell] = temp;
  2479. }
  2480. }
  2481. // Create a 2D canvas to store the result
  2482. if (!screenshotCanvas) {
  2483. screenshotCanvas = document.createElement('canvas');
  2484. }
  2485. screenshotCanvas.width = width;
  2486. screenshotCanvas.height = height;
  2487. var context = screenshotCanvas.getContext('2d');
  2488. if (context) {
  2489. // Copy the pixels to a 2D canvas
  2490. var imageData = context.createImageData(width, height);
  2491. var castData = (imageData.data);
  2492. castData.set(data);
  2493. context.putImageData(imageData, 0, 0);
  2494. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2495. }
  2496. };
  2497. /**
  2498. * Converts the canvas data to blob.
  2499. * This acts as a polyfill for browsers not supporting the to blob function.
  2500. * @param canvas Defines the canvas to extract the data from
  2501. * @param successCallback Defines the callback triggered once the data are available
  2502. * @param mimeType Defines the mime type of the result
  2503. */
  2504. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2505. if (mimeType === void 0) { mimeType = "image/png"; }
  2506. // We need HTMLCanvasElement.toBlob for HD screenshots
  2507. if (!canvas.toBlob) {
  2508. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2509. canvas.toBlob = function (callback, type, quality) {
  2510. var _this = this;
  2511. setTimeout(function () {
  2512. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2513. for (var i = 0; i < len; i++) {
  2514. arr[i] = binStr.charCodeAt(i);
  2515. }
  2516. callback(new Blob([arr]));
  2517. });
  2518. };
  2519. }
  2520. canvas.toBlob(function (blob) {
  2521. successCallback(blob);
  2522. }, mimeType);
  2523. };
  2524. /**
  2525. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2526. * @param successCallback defines the callback triggered once the data are available
  2527. * @param mimeType defines the mime type of the result
  2528. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2529. */
  2530. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2531. if (mimeType === void 0) { mimeType = "image/png"; }
  2532. if (successCallback) {
  2533. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2534. successCallback(base64Image);
  2535. }
  2536. else {
  2537. this.ToBlob(screenshotCanvas, function (blob) {
  2538. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2539. if (("download" in document.createElement("a"))) {
  2540. if (!fileName) {
  2541. var date = new Date();
  2542. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2543. fileName = "screenshot_" + stringDate + ".png";
  2544. }
  2545. Tools.Download(blob, fileName);
  2546. }
  2547. else {
  2548. var url = URL.createObjectURL(blob);
  2549. var newWindow = window.open("");
  2550. if (!newWindow) {
  2551. return;
  2552. }
  2553. var img = newWindow.document.createElement("img");
  2554. img.onload = function () {
  2555. // no longer need to read the blob so it's revoked
  2556. URL.revokeObjectURL(url);
  2557. };
  2558. img.src = url;
  2559. newWindow.document.body.appendChild(img);
  2560. }
  2561. }, mimeType);
  2562. }
  2563. };
  2564. /**
  2565. * Downloads a blob in the browser
  2566. * @param blob defines the blob to download
  2567. * @param fileName defines the name of the downloaded file
  2568. */
  2569. Tools.Download = function (blob, fileName) {
  2570. if (navigator && navigator.msSaveBlob) {
  2571. navigator.msSaveBlob(blob, fileName);
  2572. return;
  2573. }
  2574. var url = window.URL.createObjectURL(blob);
  2575. var a = document.createElement("a");
  2576. document.body.appendChild(a);
  2577. a.style.display = "none";
  2578. a.href = url;
  2579. a.download = fileName;
  2580. a.addEventListener("click", function () {
  2581. if (a.parentElement) {
  2582. a.parentElement.removeChild(a);
  2583. }
  2584. });
  2585. a.click();
  2586. window.URL.revokeObjectURL(url);
  2587. };
  2588. /**
  2589. * Captures a screenshot of the current rendering
  2590. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2591. * @param engine defines the rendering engine
  2592. * @param camera defines the source camera
  2593. * @param size This parameter can be set to a single number or to an object with the
  2594. * following (optional) properties: precision, width, height. If a single number is passed,
  2595. * it will be used for both width and height. If an object is passed, the screenshot size
  2596. * will be derived from the parameters. The precision property is a multiplier allowing
  2597. * rendering at a higher or lower resolution
  2598. * @param successCallback defines the callback receives a single parameter which contains the
  2599. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2600. * src parameter of an <img> to display it
  2601. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2602. * Check your browser for supported MIME types
  2603. */
  2604. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2605. if (mimeType === void 0) { mimeType = "image/png"; }
  2606. var width;
  2607. var height;
  2608. // If a precision value is specified
  2609. if (size.precision) {
  2610. width = Math.round(engine.getRenderWidth() * size.precision);
  2611. height = Math.round(width / engine.getAspectRatio(camera));
  2612. }
  2613. else if (size.width && size.height) {
  2614. width = size.width;
  2615. height = size.height;
  2616. }
  2617. //If passing only width, computing height to keep display canvas ratio.
  2618. else if (size.width && !size.height) {
  2619. width = size.width;
  2620. height = Math.round(width / engine.getAspectRatio(camera));
  2621. }
  2622. //If passing only height, computing width to keep display canvas ratio.
  2623. else if (size.height && !size.width) {
  2624. height = size.height;
  2625. width = Math.round(height * engine.getAspectRatio(camera));
  2626. }
  2627. //Assuming here that "size" parameter is a number
  2628. else if (!isNaN(size)) {
  2629. height = size;
  2630. width = size;
  2631. }
  2632. else {
  2633. Tools.Error("Invalid 'size' parameter !");
  2634. return;
  2635. }
  2636. if (!screenshotCanvas) {
  2637. screenshotCanvas = document.createElement('canvas');
  2638. }
  2639. screenshotCanvas.width = width;
  2640. screenshotCanvas.height = height;
  2641. var renderContext = screenshotCanvas.getContext("2d");
  2642. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2643. var newWidth = width;
  2644. var newHeight = newWidth / ratio;
  2645. if (newHeight > height) {
  2646. newHeight = height;
  2647. newWidth = newHeight * ratio;
  2648. }
  2649. var offsetX = Math.max(0, width - newWidth) / 2;
  2650. var offsetY = Math.max(0, height - newHeight) / 2;
  2651. var renderingCanvas = engine.getRenderingCanvas();
  2652. if (renderContext && renderingCanvas) {
  2653. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2654. }
  2655. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2656. };
  2657. /**
  2658. * Generates an image screenshot from the specified camera.
  2659. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2660. * @param engine The engine to use for rendering
  2661. * @param camera The camera to use for rendering
  2662. * @param size This parameter can be set to a single number or to an object with the
  2663. * following (optional) properties: precision, width, height. If a single number is passed,
  2664. * it will be used for both width and height. If an object is passed, the screenshot size
  2665. * will be derived from the parameters. The precision property is a multiplier allowing
  2666. * rendering at a higher or lower resolution
  2667. * @param successCallback The callback receives a single parameter which contains the
  2668. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2669. * src parameter of an <img> to display it
  2670. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2671. * Check your browser for supported MIME types
  2672. * @param samples Texture samples (default: 1)
  2673. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2674. * @param fileName A name for for the downloaded file.
  2675. */
  2676. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2677. if (mimeType === void 0) { mimeType = "image/png"; }
  2678. if (samples === void 0) { samples = 1; }
  2679. if (antialiasing === void 0) { antialiasing = false; }
  2680. var width;
  2681. var height;
  2682. //If a precision value is specified
  2683. if (size.precision) {
  2684. width = Math.round(engine.getRenderWidth() * size.precision);
  2685. height = Math.round(width / engine.getAspectRatio(camera));
  2686. size = { width: width, height: height };
  2687. }
  2688. else if (size.width && size.height) {
  2689. width = size.width;
  2690. height = size.height;
  2691. }
  2692. //If passing only width, computing height to keep display canvas ratio.
  2693. else if (size.width && !size.height) {
  2694. width = size.width;
  2695. height = Math.round(width / engine.getAspectRatio(camera));
  2696. size = { width: width, height: height };
  2697. }
  2698. //If passing only height, computing width to keep display canvas ratio.
  2699. else if (size.height && !size.width) {
  2700. height = size.height;
  2701. width = Math.round(height * engine.getAspectRatio(camera));
  2702. size = { width: width, height: height };
  2703. }
  2704. //Assuming here that "size" parameter is a number
  2705. else if (!isNaN(size)) {
  2706. height = size;
  2707. width = size;
  2708. }
  2709. else {
  2710. Tools.Error("Invalid 'size' parameter !");
  2711. return;
  2712. }
  2713. var scene = camera.getScene();
  2714. var previousCamera = null;
  2715. if (scene.activeCamera !== camera) {
  2716. previousCamera = scene.activeCamera;
  2717. scene.activeCamera = camera;
  2718. }
  2719. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2720. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2721. texture.renderList = null;
  2722. texture.samples = samples;
  2723. if (antialiasing) {
  2724. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2725. }
  2726. texture.onAfterRenderObservable.add(function () {
  2727. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2728. });
  2729. scene.incrementRenderId();
  2730. scene.resetCachedMaterial();
  2731. texture.render(true);
  2732. texture.dispose();
  2733. if (previousCamera) {
  2734. scene.activeCamera = previousCamera;
  2735. }
  2736. camera.getProjectionMatrix(true); // Force cache refresh;
  2737. };
  2738. /**
  2739. * Validates if xhr data is correct
  2740. * @param xhr defines the request to validate
  2741. * @param dataType defines the expected data type
  2742. * @returns true if data is correct
  2743. */
  2744. Tools.ValidateXHRData = function (xhr, dataType) {
  2745. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2746. if (dataType === void 0) { dataType = 7; }
  2747. try {
  2748. if (dataType & 1) {
  2749. if (xhr.responseText && xhr.responseText.length > 0) {
  2750. return true;
  2751. }
  2752. else if (dataType === 1) {
  2753. return false;
  2754. }
  2755. }
  2756. if (dataType & 2) {
  2757. // Check header width and height since there is no "TGA" magic number
  2758. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2759. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2760. return true;
  2761. }
  2762. else if (dataType === 2) {
  2763. return false;
  2764. }
  2765. }
  2766. if (dataType & 4) {
  2767. // Check for the "DDS" magic number
  2768. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2769. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2770. return true;
  2771. }
  2772. else {
  2773. return false;
  2774. }
  2775. }
  2776. }
  2777. catch (e) {
  2778. // Global protection
  2779. }
  2780. return false;
  2781. };
  2782. /**
  2783. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2784. * Be aware Math.random() could cause collisions, but:
  2785. * "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"
  2786. * @returns a pseudo random id
  2787. */
  2788. Tools.RandomId = function () {
  2789. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2790. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2791. return v.toString(16);
  2792. });
  2793. };
  2794. /**
  2795. * Test if the given uri is a base64 string
  2796. * @param uri The uri to test
  2797. * @return True if the uri is a base64 string or false otherwise
  2798. */
  2799. Tools.IsBase64 = function (uri) {
  2800. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2801. };
  2802. /**
  2803. * Decode the given base64 uri.
  2804. * @param uri The uri to decode
  2805. * @return The decoded base64 data.
  2806. */
  2807. Tools.DecodeBase64 = function (uri) {
  2808. var decodedString = atob(uri.split(",")[1]);
  2809. var bufferLength = decodedString.length;
  2810. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2811. for (var i = 0; i < bufferLength; i++) {
  2812. bufferView[i] = decodedString.charCodeAt(i);
  2813. }
  2814. return bufferView.buffer;
  2815. };
  2816. Tools._AddLogEntry = function (entry) {
  2817. Tools._LogCache = entry + Tools._LogCache;
  2818. if (Tools.OnNewCacheEntry) {
  2819. Tools.OnNewCacheEntry(entry);
  2820. }
  2821. };
  2822. Tools._FormatMessage = function (message) {
  2823. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2824. var date = new Date();
  2825. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2826. };
  2827. Tools._LogDisabled = function (message) {
  2828. // nothing to do
  2829. };
  2830. Tools._LogEnabled = function (message) {
  2831. var formattedMessage = Tools._FormatMessage(message);
  2832. console.log("BJS - " + formattedMessage);
  2833. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2834. Tools._AddLogEntry(entry);
  2835. };
  2836. Tools._WarnDisabled = function (message) {
  2837. // nothing to do
  2838. };
  2839. Tools._WarnEnabled = function (message) {
  2840. var formattedMessage = Tools._FormatMessage(message);
  2841. console.warn("BJS - " + formattedMessage);
  2842. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2843. Tools._AddLogEntry(entry);
  2844. };
  2845. Tools._ErrorDisabled = function (message) {
  2846. // nothing to do
  2847. };
  2848. Tools._ErrorEnabled = function (message) {
  2849. Tools.errorsCount++;
  2850. var formattedMessage = Tools._FormatMessage(message);
  2851. console.error("BJS - " + formattedMessage);
  2852. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2853. Tools._AddLogEntry(entry);
  2854. };
  2855. Object.defineProperty(Tools, "LogCache", {
  2856. /**
  2857. * Gets current log cache (list of logs)
  2858. */
  2859. get: function () {
  2860. return Tools._LogCache;
  2861. },
  2862. enumerable: true,
  2863. configurable: true
  2864. });
  2865. /**
  2866. * Clears the log cache
  2867. */
  2868. Tools.ClearLogCache = function () {
  2869. Tools._LogCache = "";
  2870. Tools.errorsCount = 0;
  2871. };
  2872. Object.defineProperty(Tools, "LogLevels", {
  2873. /**
  2874. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2875. */
  2876. set: function (level) {
  2877. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2878. Tools.Log = Tools._LogEnabled;
  2879. }
  2880. else {
  2881. Tools.Log = Tools._LogDisabled;
  2882. }
  2883. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2884. Tools.Warn = Tools._WarnEnabled;
  2885. }
  2886. else {
  2887. Tools.Warn = Tools._WarnDisabled;
  2888. }
  2889. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2890. Tools.Error = Tools._ErrorEnabled;
  2891. }
  2892. else {
  2893. Tools.Error = Tools._ErrorDisabled;
  2894. }
  2895. },
  2896. enumerable: true,
  2897. configurable: true
  2898. });
  2899. /**
  2900. * Checks if the loaded document was accessed via `file:`-Protocol.
  2901. * @returns boolean
  2902. */
  2903. Tools.IsFileURL = function () {
  2904. return location.protocol === "file:";
  2905. };
  2906. /**
  2907. * Checks if the window object exists
  2908. * @returns true if the window object exists
  2909. */
  2910. Tools.IsWindowObjectExist = function () {
  2911. return (typeof window) !== "undefined";
  2912. };
  2913. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2914. /**
  2915. * Sets the current performance log level
  2916. */
  2917. set: function (level) {
  2918. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2919. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2920. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2921. return;
  2922. }
  2923. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2924. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2925. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2926. return;
  2927. }
  2928. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2929. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2930. },
  2931. enumerable: true,
  2932. configurable: true
  2933. });
  2934. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2935. };
  2936. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2937. };
  2938. Tools._StartUserMark = function (counterName, condition) {
  2939. if (condition === void 0) { condition = true; }
  2940. if (!Tools._performance) {
  2941. if (!Tools.IsWindowObjectExist()) {
  2942. return;
  2943. }
  2944. Tools._performance = window.performance;
  2945. }
  2946. if (!condition || !Tools._performance.mark) {
  2947. return;
  2948. }
  2949. Tools._performance.mark(counterName + "-Begin");
  2950. };
  2951. Tools._EndUserMark = function (counterName, condition) {
  2952. if (condition === void 0) { condition = true; }
  2953. if (!condition || !Tools._performance.mark) {
  2954. return;
  2955. }
  2956. Tools._performance.mark(counterName + "-End");
  2957. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2958. };
  2959. Tools._StartPerformanceConsole = function (counterName, condition) {
  2960. if (condition === void 0) { condition = true; }
  2961. if (!condition) {
  2962. return;
  2963. }
  2964. Tools._StartUserMark(counterName, condition);
  2965. if (console.time) {
  2966. console.time(counterName);
  2967. }
  2968. };
  2969. Tools._EndPerformanceConsole = function (counterName, condition) {
  2970. if (condition === void 0) { condition = true; }
  2971. if (!condition) {
  2972. return;
  2973. }
  2974. Tools._EndUserMark(counterName, condition);
  2975. if (console.time) {
  2976. console.timeEnd(counterName);
  2977. }
  2978. };
  2979. Object.defineProperty(Tools, "Now", {
  2980. /**
  2981. * Gets either window.performance.now() if supported or Date.now() else
  2982. */
  2983. get: function () {
  2984. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  2985. return window.performance.now();
  2986. }
  2987. return Date.now();
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. /**
  2993. * This method will return the name of the class used to create the instance of the given object.
  2994. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  2995. * @param object the object to get the class name from
  2996. * @param isType defines if the object is actually a type
  2997. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  2998. */
  2999. Tools.GetClassName = function (object, isType) {
  3000. if (isType === void 0) { isType = false; }
  3001. var name = null;
  3002. if (!isType && object.getClassName) {
  3003. name = object.getClassName();
  3004. }
  3005. else {
  3006. if (object instanceof Object) {
  3007. var classObj = isType ? object : Object.getPrototypeOf(object);
  3008. name = classObj.constructor["__bjsclassName__"];
  3009. }
  3010. if (!name) {
  3011. name = typeof object;
  3012. }
  3013. }
  3014. return name;
  3015. };
  3016. /**
  3017. * Gets the first element of an array satisfying a given predicate
  3018. * @param array defines the array to browse
  3019. * @param predicate defines the predicate to use
  3020. * @returns null if not found or the element
  3021. */
  3022. Tools.First = function (array, predicate) {
  3023. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3024. var el = array_1[_i];
  3025. if (predicate(el)) {
  3026. return el;
  3027. }
  3028. }
  3029. return null;
  3030. };
  3031. /**
  3032. * This method will return the name of the full name of the class, including its owning module (if any).
  3033. * 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).
  3034. * @param object the object to get the class name from
  3035. * @param isType defines if the object is actually a type
  3036. * @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.
  3037. * @ignorenaming
  3038. */
  3039. Tools.getFullClassName = function (object, isType) {
  3040. if (isType === void 0) { isType = false; }
  3041. var className = null;
  3042. var moduleName = null;
  3043. if (!isType && object.getClassName) {
  3044. className = object.getClassName();
  3045. }
  3046. else {
  3047. if (object instanceof Object) {
  3048. var classObj = isType ? object : Object.getPrototypeOf(object);
  3049. className = classObj.constructor["__bjsclassName__"];
  3050. moduleName = classObj.constructor["__bjsmoduleName__"];
  3051. }
  3052. if (!className) {
  3053. className = typeof object;
  3054. }
  3055. }
  3056. if (!className) {
  3057. return null;
  3058. }
  3059. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3060. };
  3061. /**
  3062. * Returns a promise that resolves after the given amount of time.
  3063. * @param delay Number of milliseconds to delay
  3064. * @returns Promise that resolves after the given amount of time
  3065. */
  3066. Tools.DelayAsync = function (delay) {
  3067. return new Promise(function (resolve) {
  3068. setTimeout(function () {
  3069. resolve();
  3070. }, delay);
  3071. });
  3072. };
  3073. /**
  3074. * Gets the current gradient from an array of IValueGradient
  3075. * @param ratio defines the current ratio to get
  3076. * @param gradients defines the array of IValueGradient
  3077. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3078. */
  3079. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3080. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3081. var currentGradient = gradients[gradientIndex];
  3082. var nextGradient = gradients[gradientIndex + 1];
  3083. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3084. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3085. updateFunc(currentGradient, nextGradient, scale);
  3086. return;
  3087. }
  3088. }
  3089. // Use last index if over
  3090. var lastIndex = gradients.length - 1;
  3091. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3092. };
  3093. /**
  3094. * Gets or sets the base URL to use to load assets
  3095. */
  3096. Tools.BaseUrl = "";
  3097. /**
  3098. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3099. */
  3100. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3101. /**
  3102. * Default behaviour for cors in the application.
  3103. * It can be a string if the expected behavior is identical in the entire app.
  3104. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3105. */
  3106. Tools.CorsBehavior = "anonymous";
  3107. /**
  3108. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3109. * @ignorenaming
  3110. */
  3111. Tools.UseFallbackTexture = true;
  3112. /**
  3113. * Use this object to register external classes like custom textures or material
  3114. * to allow the laoders to instantiate them
  3115. */
  3116. Tools.RegisteredExternalClasses = {};
  3117. /**
  3118. * Texture content used if a texture cannot loaded
  3119. * @ignorenaming
  3120. */
  3121. 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";
  3122. Tools._tmpFloatArray = new Float32Array(1);
  3123. /**
  3124. * Gets or sets a function used to pre-process url before using them to load assets
  3125. */
  3126. Tools.PreprocessUrl = function (url) {
  3127. return url;
  3128. };
  3129. // Logs
  3130. /**
  3131. * No log
  3132. */
  3133. Tools.NoneLogLevel = 0;
  3134. /**
  3135. * Only message logs
  3136. */
  3137. Tools.MessageLogLevel = 1;
  3138. /**
  3139. * Only warning logs
  3140. */
  3141. Tools.WarningLogLevel = 2;
  3142. /**
  3143. * Only error logs
  3144. */
  3145. Tools.ErrorLogLevel = 4;
  3146. /**
  3147. * All logs
  3148. */
  3149. Tools.AllLogLevel = 7;
  3150. Tools._LogCache = "";
  3151. /**
  3152. * Gets a value indicating the number of loading errors
  3153. * @ignorenaming
  3154. */
  3155. Tools.errorsCount = 0;
  3156. /**
  3157. * Log a message to the console
  3158. */
  3159. Tools.Log = Tools._LogEnabled;
  3160. /**
  3161. * Write a warning message to the console
  3162. */
  3163. Tools.Warn = Tools._WarnEnabled;
  3164. /**
  3165. * Write an error message to the console
  3166. */
  3167. Tools.Error = Tools._ErrorEnabled;
  3168. // Performances
  3169. /**
  3170. * No performance log
  3171. */
  3172. Tools.PerformanceNoneLogLevel = 0;
  3173. /**
  3174. * Use user marks to log performance
  3175. */
  3176. Tools.PerformanceUserMarkLogLevel = 1;
  3177. /**
  3178. * Log performance to the console
  3179. */
  3180. Tools.PerformanceConsoleLogLevel = 2;
  3181. /**
  3182. * Starts a performance counter
  3183. */
  3184. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3185. /**
  3186. * Ends a specific performance coutner
  3187. */
  3188. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3189. return Tools;
  3190. }());
  3191. BABYLON.Tools = Tools;
  3192. /**
  3193. * This class is used to track a performance counter which is number based.
  3194. * The user has access to many properties which give statistics of different nature.
  3195. *
  3196. * The implementer can track two kinds of Performance Counter: time and count.
  3197. * 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.
  3198. * 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.
  3199. */
  3200. var PerfCounter = /** @class */ (function () {
  3201. /**
  3202. * Creates a new counter
  3203. */
  3204. function PerfCounter() {
  3205. this._startMonitoringTime = 0;
  3206. this._min = 0;
  3207. this._max = 0;
  3208. this._average = 0;
  3209. this._lastSecAverage = 0;
  3210. this._current = 0;
  3211. this._totalValueCount = 0;
  3212. this._totalAccumulated = 0;
  3213. this._lastSecAccumulated = 0;
  3214. this._lastSecTime = 0;
  3215. this._lastSecValueCount = 0;
  3216. }
  3217. Object.defineProperty(PerfCounter.prototype, "min", {
  3218. /**
  3219. * Returns the smallest value ever
  3220. */
  3221. get: function () {
  3222. return this._min;
  3223. },
  3224. enumerable: true,
  3225. configurable: true
  3226. });
  3227. Object.defineProperty(PerfCounter.prototype, "max", {
  3228. /**
  3229. * Returns the biggest value ever
  3230. */
  3231. get: function () {
  3232. return this._max;
  3233. },
  3234. enumerable: true,
  3235. configurable: true
  3236. });
  3237. Object.defineProperty(PerfCounter.prototype, "average", {
  3238. /**
  3239. * Returns the average value since the performance counter is running
  3240. */
  3241. get: function () {
  3242. return this._average;
  3243. },
  3244. enumerable: true,
  3245. configurable: true
  3246. });
  3247. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3248. /**
  3249. * Returns the average value of the last second the counter was monitored
  3250. */
  3251. get: function () {
  3252. return this._lastSecAverage;
  3253. },
  3254. enumerable: true,
  3255. configurable: true
  3256. });
  3257. Object.defineProperty(PerfCounter.prototype, "current", {
  3258. /**
  3259. * Returns the current value
  3260. */
  3261. get: function () {
  3262. return this._current;
  3263. },
  3264. enumerable: true,
  3265. configurable: true
  3266. });
  3267. Object.defineProperty(PerfCounter.prototype, "total", {
  3268. /**
  3269. * Gets the accumulated total
  3270. */
  3271. get: function () {
  3272. return this._totalAccumulated;
  3273. },
  3274. enumerable: true,
  3275. configurable: true
  3276. });
  3277. Object.defineProperty(PerfCounter.prototype, "count", {
  3278. /**
  3279. * Gets the total value count
  3280. */
  3281. get: function () {
  3282. return this._totalValueCount;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. /**
  3288. * Call this method to start monitoring a new frame.
  3289. * 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.
  3290. */
  3291. PerfCounter.prototype.fetchNewFrame = function () {
  3292. this._totalValueCount++;
  3293. this._current = 0;
  3294. this._lastSecValueCount++;
  3295. };
  3296. /**
  3297. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3298. * @param newCount the count value to add to the monitored count
  3299. * @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.
  3300. */
  3301. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3302. if (!PerfCounter.Enabled) {
  3303. return;
  3304. }
  3305. this._current += newCount;
  3306. if (fetchResult) {
  3307. this._fetchResult();
  3308. }
  3309. };
  3310. /**
  3311. * Start monitoring this performance counter
  3312. */
  3313. PerfCounter.prototype.beginMonitoring = function () {
  3314. if (!PerfCounter.Enabled) {
  3315. return;
  3316. }
  3317. this._startMonitoringTime = Tools.Now;
  3318. };
  3319. /**
  3320. * Compute the time lapsed since the previous beginMonitoring() call.
  3321. * @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
  3322. */
  3323. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3324. if (newFrame === void 0) { newFrame = true; }
  3325. if (!PerfCounter.Enabled) {
  3326. return;
  3327. }
  3328. if (newFrame) {
  3329. this.fetchNewFrame();
  3330. }
  3331. var currentTime = Tools.Now;
  3332. this._current = currentTime - this._startMonitoringTime;
  3333. if (newFrame) {
  3334. this._fetchResult();
  3335. }
  3336. };
  3337. PerfCounter.prototype._fetchResult = function () {
  3338. this._totalAccumulated += this._current;
  3339. this._lastSecAccumulated += this._current;
  3340. // Min/Max update
  3341. this._min = Math.min(this._min, this._current);
  3342. this._max = Math.max(this._max, this._current);
  3343. this._average = this._totalAccumulated / this._totalValueCount;
  3344. // Reset last sec?
  3345. var now = Tools.Now;
  3346. if ((now - this._lastSecTime) > 1000) {
  3347. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3348. this._lastSecTime = now;
  3349. this._lastSecAccumulated = 0;
  3350. this._lastSecValueCount = 0;
  3351. }
  3352. };
  3353. /**
  3354. * Gets or sets a global boolean to turn on and off all the counters
  3355. */
  3356. PerfCounter.Enabled = true;
  3357. return PerfCounter;
  3358. }());
  3359. BABYLON.PerfCounter = PerfCounter;
  3360. /**
  3361. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3362. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3363. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3364. * @param name The name of the class, case should be preserved
  3365. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3366. */
  3367. function className(name, module) {
  3368. return function (target) {
  3369. target["__bjsclassName__"] = name;
  3370. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3371. };
  3372. }
  3373. BABYLON.className = className;
  3374. /**
  3375. * An implementation of a loop for asynchronous functions.
  3376. */
  3377. var AsyncLoop = /** @class */ (function () {
  3378. /**
  3379. * Constructor.
  3380. * @param iterations the number of iterations.
  3381. * @param func the function to run each iteration
  3382. * @param successCallback the callback that will be called upon succesful execution
  3383. * @param offset starting offset.
  3384. */
  3385. function AsyncLoop(
  3386. /**
  3387. * Defines the number of iterations for the loop
  3388. */
  3389. iterations, func, successCallback, offset) {
  3390. if (offset === void 0) { offset = 0; }
  3391. this.iterations = iterations;
  3392. this.index = offset - 1;
  3393. this._done = false;
  3394. this._fn = func;
  3395. this._successCallback = successCallback;
  3396. }
  3397. /**
  3398. * Execute the next iteration. Must be called after the last iteration was finished.
  3399. */
  3400. AsyncLoop.prototype.executeNext = function () {
  3401. if (!this._done) {
  3402. if (this.index + 1 < this.iterations) {
  3403. ++this.index;
  3404. this._fn(this);
  3405. }
  3406. else {
  3407. this.breakLoop();
  3408. }
  3409. }
  3410. };
  3411. /**
  3412. * Break the loop and run the success callback.
  3413. */
  3414. AsyncLoop.prototype.breakLoop = function () {
  3415. this._done = true;
  3416. this._successCallback();
  3417. };
  3418. /**
  3419. * Create and run an async loop.
  3420. * @param iterations the number of iterations.
  3421. * @param fn the function to run each iteration
  3422. * @param successCallback the callback that will be called upon succesful execution
  3423. * @param offset starting offset.
  3424. * @returns the created async loop object
  3425. */
  3426. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3427. if (offset === void 0) { offset = 0; }
  3428. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3429. loop.executeNext();
  3430. return loop;
  3431. };
  3432. /**
  3433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3434. * @param iterations total number of iterations
  3435. * @param syncedIterations number of synchronous iterations in each async iteration.
  3436. * @param fn the function to call each iteration.
  3437. * @param callback a success call back that will be called when iterating stops.
  3438. * @param breakFunction a break condition (optional)
  3439. * @param timeout timeout settings for the setTimeout function. default - 0.
  3440. * @returns the created async loop object
  3441. */
  3442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3443. if (timeout === void 0) { timeout = 0; }
  3444. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3445. if (breakFunction && breakFunction()) {
  3446. loop.breakLoop();
  3447. }
  3448. else {
  3449. setTimeout(function () {
  3450. for (var i = 0; i < syncedIterations; ++i) {
  3451. var iteration = (loop.index * syncedIterations) + i;
  3452. if (iteration >= iterations) {
  3453. break;
  3454. }
  3455. fn(iteration);
  3456. if (breakFunction && breakFunction()) {
  3457. loop.breakLoop();
  3458. break;
  3459. }
  3460. }
  3461. loop.executeNext();
  3462. }, timeout);
  3463. }
  3464. }, callback);
  3465. };
  3466. return AsyncLoop;
  3467. }());
  3468. BABYLON.AsyncLoop = AsyncLoop;
  3469. })(BABYLON || (BABYLON = {}));
  3470. //# sourceMappingURL=babylon.tools.js.map
  3471. var BABYLON;
  3472. (function (BABYLON) {
  3473. /**
  3474. * Constant used to convert a value to gamma space
  3475. * @ignorenaming
  3476. */
  3477. BABYLON.ToGammaSpace = 1 / 2.2;
  3478. /**
  3479. * Constant used to convert a value to linear space
  3480. * @ignorenaming
  3481. */
  3482. BABYLON.ToLinearSpace = 2.2;
  3483. /**
  3484. * Constant used to define the minimal number value in Babylon.js
  3485. * @ignorenaming
  3486. */
  3487. BABYLON.Epsilon = 0.001;
  3488. /**
  3489. * Class used to hold a RBG color
  3490. */
  3491. var Color3 = /** @class */ (function () {
  3492. /**
  3493. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3494. * @param r defines the red component (between 0 and 1, default is 0)
  3495. * @param g defines the green component (between 0 and 1, default is 0)
  3496. * @param b defines the blue component (between 0 and 1, default is 0)
  3497. */
  3498. function Color3(
  3499. /**
  3500. * Defines the red component (between 0 and 1, default is 0)
  3501. */
  3502. r,
  3503. /**
  3504. * Defines the green component (between 0 and 1, default is 0)
  3505. */
  3506. g,
  3507. /**
  3508. * Defines the blue component (between 0 and 1, default is 0)
  3509. */
  3510. b) {
  3511. if (r === void 0) { r = 0; }
  3512. if (g === void 0) { g = 0; }
  3513. if (b === void 0) { b = 0; }
  3514. this.r = r;
  3515. this.g = g;
  3516. this.b = b;
  3517. }
  3518. /**
  3519. * Creates a string with the Color3 current values
  3520. * @returns the string representation of the Color3 object
  3521. */
  3522. Color3.prototype.toString = function () {
  3523. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3524. };
  3525. /**
  3526. * Returns the string "Color3"
  3527. * @returns "Color3"
  3528. */
  3529. Color3.prototype.getClassName = function () {
  3530. return "Color3";
  3531. };
  3532. /**
  3533. * Compute the Color3 hash code
  3534. * @returns an unique number that can be used to hash Color3 objects
  3535. */
  3536. Color3.prototype.getHashCode = function () {
  3537. var hash = this.r || 0;
  3538. hash = (hash * 397) ^ (this.g || 0);
  3539. hash = (hash * 397) ^ (this.b || 0);
  3540. return hash;
  3541. };
  3542. // Operators
  3543. /**
  3544. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3545. * @param array defines the array where to store the r,g,b components
  3546. * @param index defines an optional index in the target array to define where to start storing values
  3547. * @returns the current Color3 object
  3548. */
  3549. Color3.prototype.toArray = function (array, index) {
  3550. if (index === undefined) {
  3551. index = 0;
  3552. }
  3553. array[index] = this.r;
  3554. array[index + 1] = this.g;
  3555. array[index + 2] = this.b;
  3556. return this;
  3557. };
  3558. /**
  3559. * Returns a new Color4 object from the current Color3 and the given alpha
  3560. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3561. * @returns a new Color4 object
  3562. */
  3563. Color3.prototype.toColor4 = function (alpha) {
  3564. if (alpha === void 0) { alpha = 1; }
  3565. return new Color4(this.r, this.g, this.b, alpha);
  3566. };
  3567. /**
  3568. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3569. * @returns the new array
  3570. */
  3571. Color3.prototype.asArray = function () {
  3572. var result = new Array();
  3573. this.toArray(result, 0);
  3574. return result;
  3575. };
  3576. /**
  3577. * Returns the luminance value
  3578. * @returns a float value
  3579. */
  3580. Color3.prototype.toLuminance = function () {
  3581. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3582. };
  3583. /**
  3584. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3585. * @param otherColor defines the second operand
  3586. * @returns the new Color3 object
  3587. */
  3588. Color3.prototype.multiply = function (otherColor) {
  3589. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3590. };
  3591. /**
  3592. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3593. * @param otherColor defines the second operand
  3594. * @param result defines the Color3 object where to store the result
  3595. * @returns the current Color3
  3596. */
  3597. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3598. result.r = this.r * otherColor.r;
  3599. result.g = this.g * otherColor.g;
  3600. result.b = this.b * otherColor.b;
  3601. return this;
  3602. };
  3603. /**
  3604. * Determines equality between Color3 objects
  3605. * @param otherColor defines the second operand
  3606. * @returns true if the rgb values are equal to the given ones
  3607. */
  3608. Color3.prototype.equals = function (otherColor) {
  3609. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3610. };
  3611. /**
  3612. * Determines equality between the current Color3 object and a set of r,b,g values
  3613. * @param r defines the red component to check
  3614. * @param g defines the green component to check
  3615. * @param b defines the blue component to check
  3616. * @returns true if the rgb values are equal to the given ones
  3617. */
  3618. Color3.prototype.equalsFloats = function (r, g, b) {
  3619. return this.r === r && this.g === g && this.b === b;
  3620. };
  3621. /**
  3622. * Multiplies in place each rgb value by scale
  3623. * @param scale defines the scaling factor
  3624. * @returns the updated Color3
  3625. */
  3626. Color3.prototype.scale = function (scale) {
  3627. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3628. };
  3629. /**
  3630. * Multiplies the rgb values by scale and stores the result into "result"
  3631. * @param scale defines the scaling factor
  3632. * @param result defines the Color3 object where to store the result
  3633. * @returns the unmodified current Color3
  3634. */
  3635. Color3.prototype.scaleToRef = function (scale, result) {
  3636. result.r = this.r * scale;
  3637. result.g = this.g * scale;
  3638. result.b = this.b * scale;
  3639. return this;
  3640. };
  3641. /**
  3642. * Scale the current Color3 values by a factor and add the result to a given Color3
  3643. * @param scale defines the scale factor
  3644. * @param result defines color to store the result into
  3645. * @returns the unmodified current Color3
  3646. */
  3647. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3648. result.r += this.r * scale;
  3649. result.g += this.g * scale;
  3650. result.b += this.b * scale;
  3651. return this;
  3652. };
  3653. /**
  3654. * Clamps the rgb values by the min and max values and stores the result into "result"
  3655. * @param min defines minimum clamping value (default is 0)
  3656. * @param max defines maximum clamping value (default is 1)
  3657. * @param result defines color to store the result into
  3658. * @returns the original Color3
  3659. */
  3660. Color3.prototype.clampToRef = function (min, max, result) {
  3661. if (min === void 0) { min = 0; }
  3662. if (max === void 0) { max = 1; }
  3663. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3664. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3665. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3666. return this;
  3667. };
  3668. /**
  3669. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3670. * @param otherColor defines the second operand
  3671. * @returns the new Color3
  3672. */
  3673. Color3.prototype.add = function (otherColor) {
  3674. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3675. };
  3676. /**
  3677. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3678. * @param otherColor defines the second operand
  3679. * @param result defines Color3 object to store the result into
  3680. * @returns the unmodified current Color3
  3681. */
  3682. Color3.prototype.addToRef = function (otherColor, result) {
  3683. result.r = this.r + otherColor.r;
  3684. result.g = this.g + otherColor.g;
  3685. result.b = this.b + otherColor.b;
  3686. return this;
  3687. };
  3688. /**
  3689. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3690. * @param otherColor defines the second operand
  3691. * @returns the new Color3
  3692. */
  3693. Color3.prototype.subtract = function (otherColor) {
  3694. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3695. };
  3696. /**
  3697. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3698. * @param otherColor defines the second operand
  3699. * @param result defines Color3 object to store the result into
  3700. * @returns the unmodified current Color3
  3701. */
  3702. Color3.prototype.subtractToRef = function (otherColor, result) {
  3703. result.r = this.r - otherColor.r;
  3704. result.g = this.g - otherColor.g;
  3705. result.b = this.b - otherColor.b;
  3706. return this;
  3707. };
  3708. /**
  3709. * Copy the current object
  3710. * @returns a new Color3 copied the current one
  3711. */
  3712. Color3.prototype.clone = function () {
  3713. return new Color3(this.r, this.g, this.b);
  3714. };
  3715. /**
  3716. * Copies the rgb values from the source in the current Color3
  3717. * @param source defines the source Color3 object
  3718. * @returns the updated Color3 object
  3719. */
  3720. Color3.prototype.copyFrom = function (source) {
  3721. this.r = source.r;
  3722. this.g = source.g;
  3723. this.b = source.b;
  3724. return this;
  3725. };
  3726. /**
  3727. * Updates the Color3 rgb values from the given floats
  3728. * @param r defines the red component to read from
  3729. * @param g defines the green component to read from
  3730. * @param b defines the blue component to read from
  3731. * @returns the current Color3 object
  3732. */
  3733. Color3.prototype.copyFromFloats = function (r, g, b) {
  3734. this.r = r;
  3735. this.g = g;
  3736. this.b = b;
  3737. return this;
  3738. };
  3739. /**
  3740. * Updates the Color3 rgb values from the given floats
  3741. * @param r defines the red component to read from
  3742. * @param g defines the green component to read from
  3743. * @param b defines the blue component to read from
  3744. * @returns the current Color3 object
  3745. */
  3746. Color3.prototype.set = function (r, g, b) {
  3747. return this.copyFromFloats(r, g, b);
  3748. };
  3749. /**
  3750. * Compute the Color3 hexadecimal code as a string
  3751. * @returns a string containing the hexadecimal representation of the Color3 object
  3752. */
  3753. Color3.prototype.toHexString = function () {
  3754. var intR = (this.r * 255) | 0;
  3755. var intG = (this.g * 255) | 0;
  3756. var intB = (this.b * 255) | 0;
  3757. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3758. };
  3759. /**
  3760. * Computes a new Color3 converted from the current one to linear space
  3761. * @returns a new Color3 object
  3762. */
  3763. Color3.prototype.toLinearSpace = function () {
  3764. var convertedColor = new Color3();
  3765. this.toLinearSpaceToRef(convertedColor);
  3766. return convertedColor;
  3767. };
  3768. /**
  3769. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3770. * @param convertedColor defines the Color3 object where to store the linear space version
  3771. * @returns the unmodified Color3
  3772. */
  3773. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3774. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3775. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3776. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3777. return this;
  3778. };
  3779. /**
  3780. * Computes a new Color3 converted from the current one to gamma space
  3781. * @returns a new Color3 object
  3782. */
  3783. Color3.prototype.toGammaSpace = function () {
  3784. var convertedColor = new Color3();
  3785. this.toGammaSpaceToRef(convertedColor);
  3786. return convertedColor;
  3787. };
  3788. /**
  3789. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3790. * @param convertedColor defines the Color3 object where to store the gamma space version
  3791. * @returns the unmodified Color3
  3792. */
  3793. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3794. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3795. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3796. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3797. return this;
  3798. };
  3799. // Statics
  3800. /**
  3801. * Creates a new Color3 from the string containing valid hexadecimal values
  3802. * @param hex defines a string containing valid hexadecimal values
  3803. * @returns a new Color3 object
  3804. */
  3805. Color3.FromHexString = function (hex) {
  3806. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3807. return new Color3(0, 0, 0);
  3808. }
  3809. var r = parseInt(hex.substring(1, 3), 16);
  3810. var g = parseInt(hex.substring(3, 5), 16);
  3811. var b = parseInt(hex.substring(5, 7), 16);
  3812. return Color3.FromInts(r, g, b);
  3813. };
  3814. /**
  3815. * Creates a new Vector3 from the starting index of the given array
  3816. * @param array defines the source array
  3817. * @param offset defines an offset in the source array
  3818. * @returns a new Color3 object
  3819. */
  3820. Color3.FromArray = function (array, offset) {
  3821. if (offset === void 0) { offset = 0; }
  3822. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3823. };
  3824. /**
  3825. * Creates a new Color3 from integer values (< 256)
  3826. * @param r defines the red component to read from (value between 0 and 255)
  3827. * @param g defines the green component to read from (value between 0 and 255)
  3828. * @param b defines the blue component to read from (value between 0 and 255)
  3829. * @returns a new Color3 object
  3830. */
  3831. Color3.FromInts = function (r, g, b) {
  3832. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3833. };
  3834. /**
  3835. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3836. * @param start defines the start Color3 value
  3837. * @param end defines the end Color3 value
  3838. * @param amount defines the gradient value between start and end
  3839. * @returns a new Color3 object
  3840. */
  3841. Color3.Lerp = function (start, end, amount) {
  3842. var result = new Color3(0.0, 0.0, 0.0);
  3843. Color3.LerpToRef(start, end, amount, result);
  3844. return result;
  3845. };
  3846. /**
  3847. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3848. * @param left defines the start value
  3849. * @param right defines the end value
  3850. * @param amount defines the gradient factor
  3851. * @param result defines the Color3 object where to store the result
  3852. */
  3853. Color3.LerpToRef = function (left, right, amount, result) {
  3854. result.r = left.r + ((right.r - left.r) * amount);
  3855. result.g = left.g + ((right.g - left.g) * amount);
  3856. result.b = left.b + ((right.b - left.b) * amount);
  3857. };
  3858. /**
  3859. * Returns a Color3 value containing a red color
  3860. * @returns a new Color3 object
  3861. */
  3862. Color3.Red = function () { return new Color3(1, 0, 0); };
  3863. /**
  3864. * Returns a Color3 value containing a green color
  3865. * @returns a new Color3 object
  3866. */
  3867. Color3.Green = function () { return new Color3(0, 1, 0); };
  3868. /**
  3869. * Returns a Color3 value containing a blue color
  3870. * @returns a new Color3 object
  3871. */
  3872. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3873. /**
  3874. * Returns a Color3 value containing a black color
  3875. * @returns a new Color3 object
  3876. */
  3877. Color3.Black = function () { return new Color3(0, 0, 0); };
  3878. /**
  3879. * Returns a Color3 value containing a white color
  3880. * @returns a new Color3 object
  3881. */
  3882. Color3.White = function () { return new Color3(1, 1, 1); };
  3883. /**
  3884. * Returns a Color3 value containing a purple color
  3885. * @returns a new Color3 object
  3886. */
  3887. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3888. /**
  3889. * Returns a Color3 value containing a magenta color
  3890. * @returns a new Color3 object
  3891. */
  3892. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  3893. /**
  3894. * Returns a Color3 value containing a yellow color
  3895. * @returns a new Color3 object
  3896. */
  3897. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  3898. /**
  3899. * Returns a Color3 value containing a gray color
  3900. * @returns a new Color3 object
  3901. */
  3902. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  3903. /**
  3904. * Returns a Color3 value containing a teal color
  3905. * @returns a new Color3 object
  3906. */
  3907. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  3908. /**
  3909. * Returns a Color3 value containing a random color
  3910. * @returns a new Color3 object
  3911. */
  3912. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  3913. return Color3;
  3914. }());
  3915. BABYLON.Color3 = Color3;
  3916. /**
  3917. * Class used to hold a RBGA color
  3918. */
  3919. var Color4 = /** @class */ (function () {
  3920. /**
  3921. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  3922. * @param r defines the red component (between 0 and 1, default is 0)
  3923. * @param g defines the green component (between 0 and 1, default is 0)
  3924. * @param b defines the blue component (between 0 and 1, default is 0)
  3925. * @param a defines the alpha component (between 0 and 1, default is 1)
  3926. */
  3927. function Color4(
  3928. /**
  3929. * Defines the red component (between 0 and 1, default is 0)
  3930. */
  3931. r,
  3932. /**
  3933. * Defines the green component (between 0 and 1, default is 0)
  3934. */
  3935. g,
  3936. /**
  3937. * Defines the blue component (between 0 and 1, default is 0)
  3938. */
  3939. b,
  3940. /**
  3941. * Defines the alpha component (between 0 and 1, default is 1)
  3942. */
  3943. a) {
  3944. if (r === void 0) { r = 0; }
  3945. if (g === void 0) { g = 0; }
  3946. if (b === void 0) { b = 0; }
  3947. if (a === void 0) { a = 1; }
  3948. this.r = r;
  3949. this.g = g;
  3950. this.b = b;
  3951. this.a = a;
  3952. }
  3953. // Operators
  3954. /**
  3955. * Adds in place the given Color4 values to the current Color4 object
  3956. * @param right defines the second operand
  3957. * @returns the current updated Color4 object
  3958. */
  3959. Color4.prototype.addInPlace = function (right) {
  3960. this.r += right.r;
  3961. this.g += right.g;
  3962. this.b += right.b;
  3963. this.a += right.a;
  3964. return this;
  3965. };
  3966. /**
  3967. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  3968. * @returns the new array
  3969. */
  3970. Color4.prototype.asArray = function () {
  3971. var result = new Array();
  3972. this.toArray(result, 0);
  3973. return result;
  3974. };
  3975. /**
  3976. * Stores from the starting index in the given array the Color4 successive values
  3977. * @param array defines the array where to store the r,g,b components
  3978. * @param index defines an optional index in the target array to define where to start storing values
  3979. * @returns the current Color4 object
  3980. */
  3981. Color4.prototype.toArray = function (array, index) {
  3982. if (index === void 0) { index = 0; }
  3983. array[index] = this.r;
  3984. array[index + 1] = this.g;
  3985. array[index + 2] = this.b;
  3986. array[index + 3] = this.a;
  3987. return this;
  3988. };
  3989. /**
  3990. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  3991. * @param right defines the second operand
  3992. * @returns a new Color4 object
  3993. */
  3994. Color4.prototype.add = function (right) {
  3995. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  3996. };
  3997. /**
  3998. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  3999. * @param right defines the second operand
  4000. * @returns a new Color4 object
  4001. */
  4002. Color4.prototype.subtract = function (right) {
  4003. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4004. };
  4005. /**
  4006. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4007. * @param right defines the second operand
  4008. * @param result defines the Color4 object where to store the result
  4009. * @returns the current Color4 object
  4010. */
  4011. Color4.prototype.subtractToRef = function (right, result) {
  4012. result.r = this.r - right.r;
  4013. result.g = this.g - right.g;
  4014. result.b = this.b - right.b;
  4015. result.a = this.a - right.a;
  4016. return this;
  4017. };
  4018. /**
  4019. * Creates a new Color4 with the current Color4 values multiplied by scale
  4020. * @param scale defines the scaling factor to apply
  4021. * @returns a new Color4 object
  4022. */
  4023. Color4.prototype.scale = function (scale) {
  4024. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4025. };
  4026. /**
  4027. * Multiplies the current Color4 values by scale and stores the result in "result"
  4028. * @param scale defines the scaling factor to apply
  4029. * @param result defines the Color4 object where to store the result
  4030. * @returns the current unmodified Color4
  4031. */
  4032. Color4.prototype.scaleToRef = function (scale, result) {
  4033. result.r = this.r * scale;
  4034. result.g = this.g * scale;
  4035. result.b = this.b * scale;
  4036. result.a = this.a * scale;
  4037. return this;
  4038. };
  4039. /**
  4040. * Scale the current Color4 values by a factor and add the result to a given Color4
  4041. * @param scale defines the scale factor
  4042. * @param result defines the Color4 object where to store the result
  4043. * @returns the unmodified current Color4
  4044. */
  4045. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4046. result.r += this.r * scale;
  4047. result.g += this.g * scale;
  4048. result.b += this.b * scale;
  4049. result.a += this.a * scale;
  4050. return this;
  4051. };
  4052. /**
  4053. * Clamps the rgb values by the min and max values and stores the result into "result"
  4054. * @param min defines minimum clamping value (default is 0)
  4055. * @param max defines maximum clamping value (default is 1)
  4056. * @param result defines color to store the result into.
  4057. * @returns the cuurent Color4
  4058. */
  4059. Color4.prototype.clampToRef = function (min, max, result) {
  4060. if (min === void 0) { min = 0; }
  4061. if (max === void 0) { max = 1; }
  4062. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4063. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4064. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4065. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4066. return this;
  4067. };
  4068. /**
  4069. * Multipy an Color4 value by another and return a new Color4 object
  4070. * @param color defines the Color4 value to multiply by
  4071. * @returns a new Color4 object
  4072. */
  4073. Color4.prototype.multiply = function (color) {
  4074. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4075. };
  4076. /**
  4077. * Multipy a Color4 value by another and push the result in a reference value
  4078. * @param color defines the Color4 value to multiply by
  4079. * @param result defines the Color4 to fill the result in
  4080. * @returns the result Color4
  4081. */
  4082. Color4.prototype.multiplyToRef = function (color, result) {
  4083. result.r = this.r * color.r;
  4084. result.g = this.g * color.g;
  4085. result.b = this.b * color.b;
  4086. result.a = this.a * color.a;
  4087. return result;
  4088. };
  4089. /**
  4090. * Creates a string with the Color4 current values
  4091. * @returns the string representation of the Color4 object
  4092. */
  4093. Color4.prototype.toString = function () {
  4094. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4095. };
  4096. /**
  4097. * Returns the string "Color4"
  4098. * @returns "Color4"
  4099. */
  4100. Color4.prototype.getClassName = function () {
  4101. return "Color4";
  4102. };
  4103. /**
  4104. * Compute the Color4 hash code
  4105. * @returns an unique number that can be used to hash Color4 objects
  4106. */
  4107. Color4.prototype.getHashCode = function () {
  4108. var hash = this.r || 0;
  4109. hash = (hash * 397) ^ (this.g || 0);
  4110. hash = (hash * 397) ^ (this.b || 0);
  4111. hash = (hash * 397) ^ (this.a || 0);
  4112. return hash;
  4113. };
  4114. /**
  4115. * Creates a new Color4 copied from the current one
  4116. * @returns a new Color4 object
  4117. */
  4118. Color4.prototype.clone = function () {
  4119. return new Color4(this.r, this.g, this.b, this.a);
  4120. };
  4121. /**
  4122. * Copies the given Color4 values into the current one
  4123. * @param source defines the source Color4 object
  4124. * @returns the current updated Color4 object
  4125. */
  4126. Color4.prototype.copyFrom = function (source) {
  4127. this.r = source.r;
  4128. this.g = source.g;
  4129. this.b = source.b;
  4130. this.a = source.a;
  4131. return this;
  4132. };
  4133. /**
  4134. * Copies the given float values into the current one
  4135. * @param r defines the red component to read from
  4136. * @param g defines the green component to read from
  4137. * @param b defines the blue component to read from
  4138. * @param a defines the alpha component to read from
  4139. * @returns the current updated Color4 object
  4140. */
  4141. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4142. this.r = r;
  4143. this.g = g;
  4144. this.b = b;
  4145. this.a = a;
  4146. return this;
  4147. };
  4148. /**
  4149. * Copies the given float values into the current one
  4150. * @param r defines the red component to read from
  4151. * @param g defines the green component to read from
  4152. * @param b defines the blue component to read from
  4153. * @param a defines the alpha component to read from
  4154. * @returns the current updated Color4 object
  4155. */
  4156. Color4.prototype.set = function (r, g, b, a) {
  4157. return this.copyFromFloats(r, g, b, a);
  4158. };
  4159. /**
  4160. * Compute the Color4 hexadecimal code as a string
  4161. * @returns a string containing the hexadecimal representation of the Color4 object
  4162. */
  4163. Color4.prototype.toHexString = function () {
  4164. var intR = (this.r * 255) | 0;
  4165. var intG = (this.g * 255) | 0;
  4166. var intB = (this.b * 255) | 0;
  4167. var intA = (this.a * 255) | 0;
  4168. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4169. };
  4170. /**
  4171. * Computes a new Color4 converted from the current one to linear space
  4172. * @returns a new Color4 object
  4173. */
  4174. Color4.prototype.toLinearSpace = function () {
  4175. var convertedColor = new Color4();
  4176. this.toLinearSpaceToRef(convertedColor);
  4177. return convertedColor;
  4178. };
  4179. /**
  4180. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4181. * @param convertedColor defines the Color4 object where to store the linear space version
  4182. * @returns the unmodified Color4
  4183. */
  4184. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4185. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4186. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4187. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4188. convertedColor.a = this.a;
  4189. return this;
  4190. };
  4191. /**
  4192. * Computes a new Color4 converted from the current one to gamma space
  4193. * @returns a new Color4 object
  4194. */
  4195. Color4.prototype.toGammaSpace = function () {
  4196. var convertedColor = new Color4();
  4197. this.toGammaSpaceToRef(convertedColor);
  4198. return convertedColor;
  4199. };
  4200. /**
  4201. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4202. * @param convertedColor defines the Color4 object where to store the gamma space version
  4203. * @returns the unmodified Color4
  4204. */
  4205. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4206. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4207. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4208. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4209. convertedColor.a = this.a;
  4210. return this;
  4211. };
  4212. // Statics
  4213. /**
  4214. * Creates a new Color4 from the string containing valid hexadecimal values
  4215. * @param hex defines a string containing valid hexadecimal values
  4216. * @returns a new Color4 object
  4217. */
  4218. Color4.FromHexString = function (hex) {
  4219. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4220. return new Color4(0.0, 0.0, 0.0, 0.0);
  4221. }
  4222. var r = parseInt(hex.substring(1, 3), 16);
  4223. var g = parseInt(hex.substring(3, 5), 16);
  4224. var b = parseInt(hex.substring(5, 7), 16);
  4225. var a = parseInt(hex.substring(7, 9), 16);
  4226. return Color4.FromInts(r, g, b, a);
  4227. };
  4228. /**
  4229. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4230. * @param left defines the start value
  4231. * @param right defines the end value
  4232. * @param amount defines the gradient factor
  4233. * @returns a new Color4 object
  4234. */
  4235. Color4.Lerp = function (left, right, amount) {
  4236. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4237. Color4.LerpToRef(left, right, amount, result);
  4238. return result;
  4239. };
  4240. /**
  4241. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4242. * @param left defines the start value
  4243. * @param right defines the end value
  4244. * @param amount defines the gradient factor
  4245. * @param result defines the Color4 object where to store data
  4246. */
  4247. Color4.LerpToRef = function (left, right, amount, result) {
  4248. result.r = left.r + (right.r - left.r) * amount;
  4249. result.g = left.g + (right.g - left.g) * amount;
  4250. result.b = left.b + (right.b - left.b) * amount;
  4251. result.a = left.a + (right.a - left.a) * amount;
  4252. };
  4253. /**
  4254. * Creates a new Color4 from a Color3 and an alpha value
  4255. * @param color3 defines the source Color3 to read from
  4256. * @param alpha defines the alpha component (1.0 by default)
  4257. * @returns a new Color4 object
  4258. */
  4259. Color4.FromColor3 = function (color3, alpha) {
  4260. if (alpha === void 0) { alpha = 1.0; }
  4261. return new Color4(color3.r, color3.g, color3.b, alpha);
  4262. };
  4263. /**
  4264. * Creates a new Color4 from the starting index element of the given array
  4265. * @param array defines the source array to read from
  4266. * @param offset defines the offset in the source array
  4267. * @returns a new Color4 object
  4268. */
  4269. Color4.FromArray = function (array, offset) {
  4270. if (offset === void 0) { offset = 0; }
  4271. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4272. };
  4273. /**
  4274. * Creates a new Color3 from integer values (< 256)
  4275. * @param r defines the red component to read from (value between 0 and 255)
  4276. * @param g defines the green component to read from (value between 0 and 255)
  4277. * @param b defines the blue component to read from (value between 0 and 255)
  4278. * @param a defines the alpha component to read from (value between 0 and 255)
  4279. * @returns a new Color3 object
  4280. */
  4281. Color4.FromInts = function (r, g, b, a) {
  4282. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4283. };
  4284. /**
  4285. * Check the content of a given array and convert it to an array containing RGBA data
  4286. * If the original array was already containing count * 4 values then it is returned directly
  4287. * @param colors defines the array to check
  4288. * @param count defines the number of RGBA data to expect
  4289. * @returns an array containing count * 4 values (RGBA)
  4290. */
  4291. Color4.CheckColors4 = function (colors, count) {
  4292. // Check if color3 was used
  4293. if (colors.length === count * 3) {
  4294. var colors4 = [];
  4295. for (var index = 0; index < colors.length; index += 3) {
  4296. var newIndex = (index / 3) * 4;
  4297. colors4[newIndex] = colors[index];
  4298. colors4[newIndex + 1] = colors[index + 1];
  4299. colors4[newIndex + 2] = colors[index + 2];
  4300. colors4[newIndex + 3] = 1.0;
  4301. }
  4302. return colors4;
  4303. }
  4304. return colors;
  4305. };
  4306. return Color4;
  4307. }());
  4308. BABYLON.Color4 = Color4;
  4309. /**
  4310. * Class representing a vector containing 2 coordinates
  4311. */
  4312. var Vector2 = /** @class */ (function () {
  4313. /**
  4314. * Creates a new Vector2 from the given x and y coordinates
  4315. * @param x defines the first coordinate
  4316. * @param y defines the second coordinate
  4317. */
  4318. function Vector2(
  4319. /** defines the first coordinate */
  4320. x,
  4321. /** defines the second coordinate */
  4322. y) {
  4323. if (x === void 0) { x = 0; }
  4324. if (y === void 0) { y = 0; }
  4325. this.x = x;
  4326. this.y = y;
  4327. }
  4328. /**
  4329. * Gets a string with the Vector2 coordinates
  4330. * @returns a string with the Vector2 coordinates
  4331. */
  4332. Vector2.prototype.toString = function () {
  4333. return "{X: " + this.x + " Y:" + this.y + "}";
  4334. };
  4335. /**
  4336. * Gets class name
  4337. * @returns the string "Vector2"
  4338. */
  4339. Vector2.prototype.getClassName = function () {
  4340. return "Vector2";
  4341. };
  4342. /**
  4343. * Gets current vector hash code
  4344. * @returns the Vector2 hash code as a number
  4345. */
  4346. Vector2.prototype.getHashCode = function () {
  4347. var hash = this.x || 0;
  4348. hash = (hash * 397) ^ (this.y || 0);
  4349. return hash;
  4350. };
  4351. // Operators
  4352. /**
  4353. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4354. * @param array defines the source array
  4355. * @param index defines the offset in source array
  4356. * @returns the current Vector2
  4357. */
  4358. Vector2.prototype.toArray = function (array, index) {
  4359. if (index === void 0) { index = 0; }
  4360. array[index] = this.x;
  4361. array[index + 1] = this.y;
  4362. return this;
  4363. };
  4364. /**
  4365. * Copy the current vector to an array
  4366. * @returns a new array with 2 elements: the Vector2 coordinates.
  4367. */
  4368. Vector2.prototype.asArray = function () {
  4369. var result = new Array();
  4370. this.toArray(result, 0);
  4371. return result;
  4372. };
  4373. /**
  4374. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4375. * @param source defines the source Vector2
  4376. * @returns the current updated Vector2
  4377. */
  4378. Vector2.prototype.copyFrom = function (source) {
  4379. this.x = source.x;
  4380. this.y = source.y;
  4381. return this;
  4382. };
  4383. /**
  4384. * Sets the Vector2 coordinates with the given floats
  4385. * @param x defines the first coordinate
  4386. * @param y defines the second coordinate
  4387. * @returns the current updated Vector2
  4388. */
  4389. Vector2.prototype.copyFromFloats = function (x, y) {
  4390. this.x = x;
  4391. this.y = y;
  4392. return this;
  4393. };
  4394. /**
  4395. * Sets the Vector2 coordinates with the given floats
  4396. * @param x defines the first coordinate
  4397. * @param y defines the second coordinate
  4398. * @returns the current updated Vector2
  4399. */
  4400. Vector2.prototype.set = function (x, y) {
  4401. return this.copyFromFloats(x, y);
  4402. };
  4403. /**
  4404. * Add another vector with the current one
  4405. * @param otherVector defines the other vector
  4406. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4407. */
  4408. Vector2.prototype.add = function (otherVector) {
  4409. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4410. };
  4411. /**
  4412. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4413. * @param otherVector defines the other vector
  4414. * @param result defines the target vector
  4415. * @returns the unmodified current Vector2
  4416. */
  4417. Vector2.prototype.addToRef = function (otherVector, result) {
  4418. result.x = this.x + otherVector.x;
  4419. result.y = this.y + otherVector.y;
  4420. return this;
  4421. };
  4422. /**
  4423. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4424. * @param otherVector defines the other vector
  4425. * @returns the current updated Vector2
  4426. */
  4427. Vector2.prototype.addInPlace = function (otherVector) {
  4428. this.x += otherVector.x;
  4429. this.y += otherVector.y;
  4430. return this;
  4431. };
  4432. /**
  4433. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4434. * @param otherVector defines the other vector
  4435. * @returns a new Vector2
  4436. */
  4437. Vector2.prototype.addVector3 = function (otherVector) {
  4438. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4439. };
  4440. /**
  4441. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4442. * @param otherVector defines the other vector
  4443. * @returns a new Vector2
  4444. */
  4445. Vector2.prototype.subtract = function (otherVector) {
  4446. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4447. };
  4448. /**
  4449. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4450. * @param otherVector defines the other vector
  4451. * @param result defines the target vector
  4452. * @returns the unmodified current Vector2
  4453. */
  4454. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4455. result.x = this.x - otherVector.x;
  4456. result.y = this.y - otherVector.y;
  4457. return this;
  4458. };
  4459. /**
  4460. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4461. * @param otherVector defines the other vector
  4462. * @returns the current updated Vector2
  4463. */
  4464. Vector2.prototype.subtractInPlace = function (otherVector) {
  4465. this.x -= otherVector.x;
  4466. this.y -= otherVector.y;
  4467. return this;
  4468. };
  4469. /**
  4470. * Multiplies in place the current Vector2 coordinates by the given ones
  4471. * @param otherVector defines the other vector
  4472. * @returns the current updated Vector2
  4473. */
  4474. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4475. this.x *= otherVector.x;
  4476. this.y *= otherVector.y;
  4477. return this;
  4478. };
  4479. /**
  4480. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4481. * @param otherVector defines the other vector
  4482. * @returns a new Vector2
  4483. */
  4484. Vector2.prototype.multiply = function (otherVector) {
  4485. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4486. };
  4487. /**
  4488. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4489. * @param otherVector defines the other vector
  4490. * @param result defines the target vector
  4491. * @returns the unmodified current Vector2
  4492. */
  4493. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4494. result.x = this.x * otherVector.x;
  4495. result.y = this.y * otherVector.y;
  4496. return this;
  4497. };
  4498. /**
  4499. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4500. * @param x defines the first coordinate
  4501. * @param y defines the second coordinate
  4502. * @returns a new Vector2
  4503. */
  4504. Vector2.prototype.multiplyByFloats = function (x, y) {
  4505. return new Vector2(this.x * x, this.y * y);
  4506. };
  4507. /**
  4508. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4509. * @param otherVector defines the other vector
  4510. * @returns a new Vector2
  4511. */
  4512. Vector2.prototype.divide = function (otherVector) {
  4513. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4514. };
  4515. /**
  4516. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4517. * @param otherVector defines the other vector
  4518. * @param result defines the target vector
  4519. * @returns the unmodified current Vector2
  4520. */
  4521. Vector2.prototype.divideToRef = function (otherVector, result) {
  4522. result.x = this.x / otherVector.x;
  4523. result.y = this.y / otherVector.y;
  4524. return this;
  4525. };
  4526. /**
  4527. * Divides the current Vector2 coordinates by the given ones
  4528. * @param otherVector defines the other vector
  4529. * @returns the current updated Vector2
  4530. */
  4531. Vector2.prototype.divideInPlace = function (otherVector) {
  4532. return this.divideToRef(otherVector, this);
  4533. };
  4534. /**
  4535. * Gets a new Vector2 with current Vector2 negated coordinates
  4536. * @returns a new Vector2
  4537. */
  4538. Vector2.prototype.negate = function () {
  4539. return new Vector2(-this.x, -this.y);
  4540. };
  4541. /**
  4542. * Multiply the Vector2 coordinates by scale
  4543. * @param scale defines the scaling factor
  4544. * @returns the current updated Vector2
  4545. */
  4546. Vector2.prototype.scaleInPlace = function (scale) {
  4547. this.x *= scale;
  4548. this.y *= scale;
  4549. return this;
  4550. };
  4551. /**
  4552. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4553. * @param scale defines the scaling factor
  4554. * @returns a new Vector2
  4555. */
  4556. Vector2.prototype.scale = function (scale) {
  4557. var result = new Vector2(0, 0);
  4558. this.scaleToRef(scale, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Scale the current Vector2 values by a factor to a given Vector2
  4563. * @param scale defines the scale factor
  4564. * @param result defines the Vector2 object where to store the result
  4565. * @returns the unmodified current Vector2
  4566. */
  4567. Vector2.prototype.scaleToRef = function (scale, result) {
  4568. result.x = this.x * scale;
  4569. result.y = this.y * scale;
  4570. return this;
  4571. };
  4572. /**
  4573. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4574. * @param scale defines the scale factor
  4575. * @param result defines the Vector2 object where to store the result
  4576. * @returns the unmodified current Vector2
  4577. */
  4578. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4579. result.x += this.x * scale;
  4580. result.y += this.y * scale;
  4581. return this;
  4582. };
  4583. /**
  4584. * Gets a boolean if two vectors are equals
  4585. * @param otherVector defines the other vector
  4586. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4587. */
  4588. Vector2.prototype.equals = function (otherVector) {
  4589. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4590. };
  4591. /**
  4592. * Gets a boolean if two vectors are equals (using an epsilon value)
  4593. * @param otherVector defines the other vector
  4594. * @param epsilon defines the minimal distance to consider equality
  4595. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4596. */
  4597. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4598. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4599. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4600. };
  4601. /**
  4602. * Gets a new Vector2 from current Vector2 floored values
  4603. * @returns a new Vector2
  4604. */
  4605. Vector2.prototype.floor = function () {
  4606. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4607. };
  4608. /**
  4609. * Gets a new Vector2 from current Vector2 floored values
  4610. * @returns a new Vector2
  4611. */
  4612. Vector2.prototype.fract = function () {
  4613. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4614. };
  4615. // Properties
  4616. /**
  4617. * Gets the length of the vector
  4618. * @returns the vector length (float)
  4619. */
  4620. Vector2.prototype.length = function () {
  4621. return Math.sqrt(this.x * this.x + this.y * this.y);
  4622. };
  4623. /**
  4624. * Gets the vector squared length
  4625. * @returns the vector squared length (float)
  4626. */
  4627. Vector2.prototype.lengthSquared = function () {
  4628. return (this.x * this.x + this.y * this.y);
  4629. };
  4630. // Methods
  4631. /**
  4632. * Normalize the vector
  4633. * @returns the current updated Vector2
  4634. */
  4635. Vector2.prototype.normalize = function () {
  4636. var len = this.length();
  4637. if (len === 0) {
  4638. return this;
  4639. }
  4640. var num = 1.0 / len;
  4641. this.x *= num;
  4642. this.y *= num;
  4643. return this;
  4644. };
  4645. /**
  4646. * Gets a new Vector2 copied from the Vector2
  4647. * @returns a new Vector2
  4648. */
  4649. Vector2.prototype.clone = function () {
  4650. return new Vector2(this.x, this.y);
  4651. };
  4652. // Statics
  4653. /**
  4654. * Gets a new Vector2(0, 0)
  4655. * @returns a new Vector2
  4656. */
  4657. Vector2.Zero = function () {
  4658. return new Vector2(0, 0);
  4659. };
  4660. /**
  4661. * Gets a new Vector2(1, 1)
  4662. * @returns a new Vector2
  4663. */
  4664. Vector2.One = function () {
  4665. return new Vector2(1, 1);
  4666. };
  4667. /**
  4668. * Gets a new Vector2 set from the given index element of the given array
  4669. * @param array defines the data source
  4670. * @param offset defines the offset in the data source
  4671. * @returns a new Vector2
  4672. */
  4673. Vector2.FromArray = function (array, offset) {
  4674. if (offset === void 0) { offset = 0; }
  4675. return new Vector2(array[offset], array[offset + 1]);
  4676. };
  4677. /**
  4678. * Sets "result" from the given index element of the given array
  4679. * @param array defines the data source
  4680. * @param offset defines the offset in the data source
  4681. * @param result defines the target vector
  4682. */
  4683. Vector2.FromArrayToRef = function (array, offset, result) {
  4684. result.x = array[offset];
  4685. result.y = array[offset + 1];
  4686. };
  4687. /**
  4688. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4689. * @param value1 defines 1st point of control
  4690. * @param value2 defines 2nd point of control
  4691. * @param value3 defines 3rd point of control
  4692. * @param value4 defines 4th point of control
  4693. * @param amount defines the interpolation factor
  4694. * @returns a new Vector2
  4695. */
  4696. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4697. var squared = amount * amount;
  4698. var cubed = amount * squared;
  4699. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4700. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4701. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4702. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4703. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4704. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4705. return new Vector2(x, y);
  4706. };
  4707. /**
  4708. * 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".
  4709. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4710. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4711. * @param value defines the value to clamp
  4712. * @param min defines the lower limit
  4713. * @param max defines the upper limit
  4714. * @returns a new Vector2
  4715. */
  4716. Vector2.Clamp = function (value, min, max) {
  4717. var x = value.x;
  4718. x = (x > max.x) ? max.x : x;
  4719. x = (x < min.x) ? min.x : x;
  4720. var y = value.y;
  4721. y = (y > max.y) ? max.y : y;
  4722. y = (y < min.y) ? min.y : y;
  4723. return new Vector2(x, y);
  4724. };
  4725. /**
  4726. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4727. * @param value1 defines the 1st control point
  4728. * @param tangent1 defines the outgoing tangent
  4729. * @param value2 defines the 2nd control point
  4730. * @param tangent2 defines the incoming tangent
  4731. * @param amount defines the interpolation factor
  4732. * @returns a new Vector2
  4733. */
  4734. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4735. var squared = amount * amount;
  4736. var cubed = amount * squared;
  4737. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4738. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4739. var part3 = (cubed - (2.0 * squared)) + amount;
  4740. var part4 = cubed - squared;
  4741. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4742. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4743. return new Vector2(x, y);
  4744. };
  4745. /**
  4746. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4747. * @param start defines the start vector
  4748. * @param end defines the end vector
  4749. * @param amount defines the interpolation factor
  4750. * @returns a new Vector2
  4751. */
  4752. Vector2.Lerp = function (start, end, amount) {
  4753. var x = start.x + ((end.x - start.x) * amount);
  4754. var y = start.y + ((end.y - start.y) * amount);
  4755. return new Vector2(x, y);
  4756. };
  4757. /**
  4758. * Gets the dot product of the vector "left" and the vector "right"
  4759. * @param left defines first vector
  4760. * @param right defines second vector
  4761. * @returns the dot product (float)
  4762. */
  4763. Vector2.Dot = function (left, right) {
  4764. return left.x * right.x + left.y * right.y;
  4765. };
  4766. /**
  4767. * Returns a new Vector2 equal to the normalized given vector
  4768. * @param vector defines the vector to normalize
  4769. * @returns a new Vector2
  4770. */
  4771. Vector2.Normalize = function (vector) {
  4772. var newVector = vector.clone();
  4773. newVector.normalize();
  4774. return newVector;
  4775. };
  4776. /**
  4777. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4778. * @param left defines 1st vector
  4779. * @param right defines 2nd vector
  4780. * @returns a new Vector2
  4781. */
  4782. Vector2.Minimize = function (left, right) {
  4783. var x = (left.x < right.x) ? left.x : right.x;
  4784. var y = (left.y < right.y) ? left.y : right.y;
  4785. return new Vector2(x, y);
  4786. };
  4787. /**
  4788. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4789. * @param left defines 1st vector
  4790. * @param right defines 2nd vector
  4791. * @returns a new Vector2
  4792. */
  4793. Vector2.Maximize = function (left, right) {
  4794. var x = (left.x > right.x) ? left.x : right.x;
  4795. var y = (left.y > right.y) ? left.y : right.y;
  4796. return new Vector2(x, y);
  4797. };
  4798. /**
  4799. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4800. * @param vector defines the vector to transform
  4801. * @param transformation defines the matrix to apply
  4802. * @returns a new Vector2
  4803. */
  4804. Vector2.Transform = function (vector, transformation) {
  4805. var r = Vector2.Zero();
  4806. Vector2.TransformToRef(vector, transformation, r);
  4807. return r;
  4808. };
  4809. /**
  4810. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4811. * @param vector defines the vector to transform
  4812. * @param transformation defines the matrix to apply
  4813. * @param result defines the target vector
  4814. */
  4815. Vector2.TransformToRef = function (vector, transformation, result) {
  4816. var m = transformation.m;
  4817. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4818. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4819. result.x = x;
  4820. result.y = y;
  4821. };
  4822. /**
  4823. * Determines if a given vector is included in a triangle
  4824. * @param p defines the vector to test
  4825. * @param p0 defines 1st triangle point
  4826. * @param p1 defines 2nd triangle point
  4827. * @param p2 defines 3rd triangle point
  4828. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4829. */
  4830. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4831. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4832. var sign = a < 0 ? -1 : 1;
  4833. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4834. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4835. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4836. };
  4837. /**
  4838. * Gets the distance between the vectors "value1" and "value2"
  4839. * @param value1 defines first vector
  4840. * @param value2 defines second vector
  4841. * @returns the distance between vectors
  4842. */
  4843. Vector2.Distance = function (value1, value2) {
  4844. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4845. };
  4846. /**
  4847. * Returns the squared distance between the vectors "value1" and "value2"
  4848. * @param value1 defines first vector
  4849. * @param value2 defines second vector
  4850. * @returns the squared distance between vectors
  4851. */
  4852. Vector2.DistanceSquared = function (value1, value2) {
  4853. var x = value1.x - value2.x;
  4854. var y = value1.y - value2.y;
  4855. return (x * x) + (y * y);
  4856. };
  4857. /**
  4858. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4859. * @param value1 defines first vector
  4860. * @param value2 defines second vector
  4861. * @returns a new Vector2
  4862. */
  4863. Vector2.Center = function (value1, value2) {
  4864. var center = value1.add(value2);
  4865. center.scaleInPlace(0.5);
  4866. return center;
  4867. };
  4868. /**
  4869. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4870. * @param p defines the middle point
  4871. * @param segA defines one point of the segment
  4872. * @param segB defines the other point of the segment
  4873. * @returns the shortest distance
  4874. */
  4875. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4876. var l2 = Vector2.DistanceSquared(segA, segB);
  4877. if (l2 === 0.0) {
  4878. return Vector2.Distance(p, segA);
  4879. }
  4880. var v = segB.subtract(segA);
  4881. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4882. var proj = segA.add(v.multiplyByFloats(t, t));
  4883. return Vector2.Distance(p, proj);
  4884. };
  4885. return Vector2;
  4886. }());
  4887. BABYLON.Vector2 = Vector2;
  4888. /**
  4889. * Classed used to store (x,y,z) vector representation
  4890. * A Vector3 is the main object used in 3D geometry
  4891. * It can represent etiher the coordinates of a point the space, either a direction
  4892. * Reminder: Babylon.js uses a left handed forward facing system
  4893. */
  4894. var Vector3 = /** @class */ (function () {
  4895. /**
  4896. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  4897. * @param x defines the first coordinates (on X axis)
  4898. * @param y defines the second coordinates (on Y axis)
  4899. * @param z defines the third coordinates (on Z axis)
  4900. */
  4901. function Vector3(
  4902. /**
  4903. * Defines the first coordinates (on X axis)
  4904. */
  4905. x,
  4906. /**
  4907. * Defines the second coordinates (on Y axis)
  4908. */
  4909. y,
  4910. /**
  4911. * Defines the third coordinates (on Z axis)
  4912. */
  4913. z) {
  4914. if (x === void 0) { x = 0; }
  4915. if (y === void 0) { y = 0; }
  4916. if (z === void 0) { z = 0; }
  4917. this.x = x;
  4918. this.y = y;
  4919. this.z = z;
  4920. }
  4921. /**
  4922. * Creates a string representation of the Vector3
  4923. * @returns a string with the Vector3 coordinates.
  4924. */
  4925. Vector3.prototype.toString = function () {
  4926. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  4927. };
  4928. /**
  4929. * Gets the class name
  4930. * @returns the string "Vector3"
  4931. */
  4932. Vector3.prototype.getClassName = function () {
  4933. return "Vector3";
  4934. };
  4935. /**
  4936. * Creates the Vector3 hash code
  4937. * @returns a number which tends to be unique between Vector3 instances
  4938. */
  4939. Vector3.prototype.getHashCode = function () {
  4940. var hash = this.x || 0;
  4941. hash = (hash * 397) ^ (this.y || 0);
  4942. hash = (hash * 397) ^ (this.z || 0);
  4943. return hash;
  4944. };
  4945. // Operators
  4946. /**
  4947. * Creates an array containing three elements : the coordinates of the Vector3
  4948. * @returns a new array of numbers
  4949. */
  4950. Vector3.prototype.asArray = function () {
  4951. var result = [];
  4952. this.toArray(result, 0);
  4953. return result;
  4954. };
  4955. /**
  4956. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  4957. * @param array defines the destination array
  4958. * @param index defines the offset in the destination array
  4959. * @returns the current Vector3
  4960. */
  4961. Vector3.prototype.toArray = function (array, index) {
  4962. if (index === void 0) { index = 0; }
  4963. array[index] = this.x;
  4964. array[index + 1] = this.y;
  4965. array[index + 2] = this.z;
  4966. return this;
  4967. };
  4968. /**
  4969. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  4970. * @returns a new Quaternion object, computed from the Vector3 coordinates
  4971. */
  4972. Vector3.prototype.toQuaternion = function () {
  4973. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  4974. };
  4975. /**
  4976. * Adds the given vector to the current Vector3
  4977. * @param otherVector defines the second operand
  4978. * @returns the current updated Vector3
  4979. */
  4980. Vector3.prototype.addInPlace = function (otherVector) {
  4981. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  4982. };
  4983. /**
  4984. * Adds the given coordinates to the current Vector3
  4985. * @param x defines the x coordinate of the operand
  4986. * @param y defines the y coordinate of the operand
  4987. * @param z defines the z coordinate of the operand
  4988. * @returns the current updated Vector3
  4989. */
  4990. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  4991. this.x += x;
  4992. this.y += y;
  4993. this.z += z;
  4994. return this;
  4995. };
  4996. /**
  4997. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  4998. * @param otherVector defines the second operand
  4999. * @returns the resulting Vector3
  5000. */
  5001. Vector3.prototype.add = function (otherVector) {
  5002. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5003. };
  5004. /**
  5005. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5006. * @param otherVector defines the second operand
  5007. * @param result defines the Vector3 object where to store the result
  5008. * @returns the current Vector3
  5009. */
  5010. Vector3.prototype.addToRef = function (otherVector, result) {
  5011. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5012. };
  5013. /**
  5014. * Subtract the given vector from the current Vector3
  5015. * @param otherVector defines the second operand
  5016. * @returns the current updated Vector3
  5017. */
  5018. Vector3.prototype.subtractInPlace = function (otherVector) {
  5019. this.x -= otherVector.x;
  5020. this.y -= otherVector.y;
  5021. this.z -= otherVector.z;
  5022. return this;
  5023. };
  5024. /**
  5025. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5026. * @param otherVector defines the second operand
  5027. * @returns the resulting Vector3
  5028. */
  5029. Vector3.prototype.subtract = function (otherVector) {
  5030. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5031. };
  5032. /**
  5033. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5034. * @param otherVector defines the second operand
  5035. * @param result defines the Vector3 object where to store the result
  5036. * @returns the current Vector3
  5037. */
  5038. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5039. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5040. };
  5041. /**
  5042. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5043. * @param x defines the x coordinate of the operand
  5044. * @param y defines the y coordinate of the operand
  5045. * @param z defines the z coordinate of the operand
  5046. * @returns the resulting Vector3
  5047. */
  5048. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5049. return new Vector3(this.x - x, this.y - y, this.z - z);
  5050. };
  5051. /**
  5052. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5053. * @param x defines the x coordinate of the operand
  5054. * @param y defines the y coordinate of the operand
  5055. * @param z defines the z coordinate of the operand
  5056. * @param result defines the Vector3 object where to store the result
  5057. * @returns the current Vector3
  5058. */
  5059. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5060. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5061. };
  5062. /**
  5063. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5064. * @returns a new Vector3
  5065. */
  5066. Vector3.prototype.negate = function () {
  5067. return new Vector3(-this.x, -this.y, -this.z);
  5068. };
  5069. /**
  5070. * Multiplies the Vector3 coordinates by the float "scale"
  5071. * @param scale defines the multiplier factor
  5072. * @returns the current updated Vector3
  5073. */
  5074. Vector3.prototype.scaleInPlace = function (scale) {
  5075. this.x *= scale;
  5076. this.y *= scale;
  5077. this.z *= scale;
  5078. return this;
  5079. };
  5080. /**
  5081. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5082. * @param scale defines the multiplier factor
  5083. * @returns a new Vector3
  5084. */
  5085. Vector3.prototype.scale = function (scale) {
  5086. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5087. };
  5088. /**
  5089. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5090. * @param scale defines the multiplier factor
  5091. * @param result defines the Vector3 object where to store the result
  5092. * @returns the current Vector3
  5093. */
  5094. Vector3.prototype.scaleToRef = function (scale, result) {
  5095. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5096. };
  5097. /**
  5098. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5099. * @param scale defines the scale factor
  5100. * @param result defines the Vector3 object where to store the result
  5101. * @returns the unmodified current Vector3
  5102. */
  5103. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5104. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5105. };
  5106. /**
  5107. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5108. * @param otherVector defines the second operand
  5109. * @returns true if both vectors are equals
  5110. */
  5111. Vector3.prototype.equals = function (otherVector) {
  5112. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5113. };
  5114. /**
  5115. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5116. * @param otherVector defines the second operand
  5117. * @param epsilon defines the minimal distance to define values as equals
  5118. * @returns true if both vectors are distant less than epsilon
  5119. */
  5120. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5121. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5122. 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);
  5123. };
  5124. /**
  5125. * Returns true if the current Vector3 coordinates equals the given floats
  5126. * @param x defines the x coordinate of the operand
  5127. * @param y defines the y coordinate of the operand
  5128. * @param z defines the z coordinate of the operand
  5129. * @returns true if both vectors are equals
  5130. */
  5131. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5132. return this.x === x && this.y === y && this.z === z;
  5133. };
  5134. /**
  5135. * Multiplies the current Vector3 coordinates by the given ones
  5136. * @param otherVector defines the second operand
  5137. * @returns the current updated Vector3
  5138. */
  5139. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5140. this.x *= otherVector.x;
  5141. this.y *= otherVector.y;
  5142. this.z *= otherVector.z;
  5143. return this;
  5144. };
  5145. /**
  5146. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5147. * @param otherVector defines the second operand
  5148. * @returns the new Vector3
  5149. */
  5150. Vector3.prototype.multiply = function (otherVector) {
  5151. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5152. };
  5153. /**
  5154. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5155. * @param otherVector defines the second operand
  5156. * @param result defines the Vector3 object where to store the result
  5157. * @returns the current Vector3
  5158. */
  5159. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5160. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5161. };
  5162. /**
  5163. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5164. * @param x defines the x coordinate of the operand
  5165. * @param y defines the y coordinate of the operand
  5166. * @param z defines the z coordinate of the operand
  5167. * @returns the new Vector3
  5168. */
  5169. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5170. return new Vector3(this.x * x, this.y * y, this.z * z);
  5171. };
  5172. /**
  5173. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5174. * @param otherVector defines the second operand
  5175. * @returns the new Vector3
  5176. */
  5177. Vector3.prototype.divide = function (otherVector) {
  5178. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5179. };
  5180. /**
  5181. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5182. * @param otherVector defines the second operand
  5183. * @param result defines the Vector3 object where to store the result
  5184. * @returns the current Vector3
  5185. */
  5186. Vector3.prototype.divideToRef = function (otherVector, result) {
  5187. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5188. };
  5189. /**
  5190. * Divides the current Vector3 coordinates by the given ones.
  5191. * @param otherVector defines the second operand
  5192. * @returns the current updated Vector3
  5193. */
  5194. Vector3.prototype.divideInPlace = function (otherVector) {
  5195. return this.divideToRef(otherVector, this);
  5196. };
  5197. /**
  5198. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5199. * @param other defines the second operand
  5200. * @returns the current updated Vector3
  5201. */
  5202. Vector3.prototype.minimizeInPlace = function (other) {
  5203. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5204. };
  5205. /**
  5206. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5207. * @param other defines the second operand
  5208. * @returns the current updated Vector3
  5209. */
  5210. Vector3.prototype.maximizeInPlace = function (other) {
  5211. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5212. };
  5213. /**
  5214. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5215. * @param x defines the x coordinate of the operand
  5216. * @param y defines the y coordinate of the operand
  5217. * @param z defines the z coordinate of the operand
  5218. * @returns the current updated Vector3
  5219. */
  5220. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5221. if (x < this.x) {
  5222. this.x = x;
  5223. }
  5224. if (y < this.y) {
  5225. this.y = y;
  5226. }
  5227. if (z < this.z) {
  5228. this.z = z;
  5229. }
  5230. return this;
  5231. };
  5232. /**
  5233. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5234. * @param x defines the x coordinate of the operand
  5235. * @param y defines the y coordinate of the operand
  5236. * @param z defines the z coordinate of the operand
  5237. * @returns the current updated Vector3
  5238. */
  5239. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5240. if (x > this.x) {
  5241. this.x = x;
  5242. }
  5243. if (y > this.y) {
  5244. this.y = y;
  5245. }
  5246. if (z > this.z) {
  5247. this.z = z;
  5248. }
  5249. return this;
  5250. };
  5251. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5252. /**
  5253. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5254. */
  5255. get: function () {
  5256. var absX = Math.abs(this.x);
  5257. var absY = Math.abs(this.y);
  5258. if (absX !== absY) {
  5259. return true;
  5260. }
  5261. var absZ = Math.abs(this.z);
  5262. if (absX !== absZ) {
  5263. return true;
  5264. }
  5265. if (absY !== absZ) {
  5266. return true;
  5267. }
  5268. return false;
  5269. },
  5270. enumerable: true,
  5271. configurable: true
  5272. });
  5273. /**
  5274. * Gets a new Vector3 from current Vector3 floored values
  5275. * @returns a new Vector3
  5276. */
  5277. Vector3.prototype.floor = function () {
  5278. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5279. };
  5280. /**
  5281. * Gets a new Vector3 from current Vector3 floored values
  5282. * @returns a new Vector3
  5283. */
  5284. Vector3.prototype.fract = function () {
  5285. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5286. };
  5287. // Properties
  5288. /**
  5289. * Gets the length of the Vector3
  5290. * @returns the length of the Vecto3
  5291. */
  5292. Vector3.prototype.length = function () {
  5293. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5294. };
  5295. /**
  5296. * Gets the squared length of the Vector3
  5297. * @returns squared length of the Vector3
  5298. */
  5299. Vector3.prototype.lengthSquared = function () {
  5300. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5301. };
  5302. /**
  5303. * Normalize the current Vector3.
  5304. * Please note that this is an in place operation.
  5305. * @returns the current updated Vector3
  5306. */
  5307. Vector3.prototype.normalize = function () {
  5308. return this.normalizeFromLength(this.length());
  5309. };
  5310. /**
  5311. * Normalize the current Vector3 with the given input length.
  5312. * Please note that this is an in place operation.
  5313. * @param len the length of the vector
  5314. * @returns the current updated Vector3
  5315. */
  5316. Vector3.prototype.normalizeFromLength = function (len) {
  5317. if (len === 0 || len === 1.0) {
  5318. return this;
  5319. }
  5320. return this.scaleInPlace(1.0 / len);
  5321. };
  5322. /**
  5323. * Normalize the current Vector3 to a new vector
  5324. * @returns the new Vector3
  5325. */
  5326. Vector3.prototype.normalizeToNew = function () {
  5327. var normalized = new Vector3(0, 0, 0);
  5328. this.normalizeToRef(normalized);
  5329. return normalized;
  5330. };
  5331. /**
  5332. * Normalize the current Vector3 to the reference
  5333. * @param reference define the Vector3 to update
  5334. * @returns the updated Vector3
  5335. */
  5336. Vector3.prototype.normalizeToRef = function (reference) {
  5337. var len = this.length();
  5338. if (len === 0 || len === 1.0) {
  5339. return reference.copyFromFloats(this.x, this.y, this.z);
  5340. }
  5341. return this.scaleToRef(1.0 / len, reference);
  5342. };
  5343. /**
  5344. * Creates a new Vector3 copied from the current Vector3
  5345. * @returns the new Vector3
  5346. */
  5347. Vector3.prototype.clone = function () {
  5348. return new Vector3(this.x, this.y, this.z);
  5349. };
  5350. /**
  5351. * Copies the given vector coordinates to the current Vector3 ones
  5352. * @param source defines the source Vector3
  5353. * @returns the current updated Vector3
  5354. */
  5355. Vector3.prototype.copyFrom = function (source) {
  5356. return this.copyFromFloats(source.x, source.y, source.z);
  5357. };
  5358. /**
  5359. * Copies the given floats to the current Vector3 coordinates
  5360. * @param x defines the x coordinate of the operand
  5361. * @param y defines the y coordinate of the operand
  5362. * @param z defines the z coordinate of the operand
  5363. * @returns the current updated Vector3
  5364. */
  5365. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5366. this.x = x;
  5367. this.y = y;
  5368. this.z = z;
  5369. return this;
  5370. };
  5371. /**
  5372. * Copies the given floats to the current Vector3 coordinates
  5373. * @param x defines the x coordinate of the operand
  5374. * @param y defines the y coordinate of the operand
  5375. * @param z defines the z coordinate of the operand
  5376. * @returns the current updated Vector3
  5377. */
  5378. Vector3.prototype.set = function (x, y, z) {
  5379. return this.copyFromFloats(x, y, z);
  5380. };
  5381. /**
  5382. * Copies the given float to the current Vector3 coordinates
  5383. * @param v defines the x, y and z coordinates of the operand
  5384. * @returns the current updated Vector3
  5385. */
  5386. Vector3.prototype.setAll = function (v) {
  5387. this.x = this.y = this.z = v;
  5388. return this;
  5389. };
  5390. // Statics
  5391. /**
  5392. * Get the clip factor between two vectors
  5393. * @param vector0 defines the first operand
  5394. * @param vector1 defines the second operand
  5395. * @param axis defines the axis to use
  5396. * @param size defines the size along the axis
  5397. * @returns the clip factor
  5398. */
  5399. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5400. var d0 = Vector3.Dot(vector0, axis) - size;
  5401. var d1 = Vector3.Dot(vector1, axis) - size;
  5402. var s = d0 / (d0 - d1);
  5403. return s;
  5404. };
  5405. /**
  5406. * Get angle between two vectors
  5407. * @param vector0 angle between vector0 and vector1
  5408. * @param vector1 angle between vector0 and vector1
  5409. * @param normal direction of the normal
  5410. * @return the angle between vector0 and vector1
  5411. */
  5412. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5413. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5414. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5415. var dot = Vector3.Dot(v0, v1);
  5416. var n = MathTmp.Vector3[3];
  5417. Vector3.CrossToRef(v0, v1, n);
  5418. if (Vector3.Dot(n, normal) > 0) {
  5419. return Math.acos(dot);
  5420. }
  5421. return -Math.acos(dot);
  5422. };
  5423. /**
  5424. * Returns a new Vector3 set from the index "offset" of the given array
  5425. * @param array defines the source array
  5426. * @param offset defines the offset in the source array
  5427. * @returns the new Vector3
  5428. */
  5429. Vector3.FromArray = function (array, offset) {
  5430. if (!offset) {
  5431. offset = 0;
  5432. }
  5433. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5434. };
  5435. /**
  5436. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5437. * This function is deprecated. Use FromArray instead
  5438. * @param array defines the source array
  5439. * @param offset defines the offset in the source array
  5440. * @returns the new Vector3
  5441. */
  5442. Vector3.FromFloatArray = function (array, offset) {
  5443. return Vector3.FromArray(array, offset);
  5444. };
  5445. /**
  5446. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5447. * @param array defines the source array
  5448. * @param offset defines the offset in the source array
  5449. * @param result defines the Vector3 where to store the result
  5450. */
  5451. Vector3.FromArrayToRef = function (array, offset, result) {
  5452. result.x = array[offset];
  5453. result.y = array[offset + 1];
  5454. result.z = array[offset + 2];
  5455. };
  5456. /**
  5457. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5458. * This function is deprecated. Use FromArrayToRef instead.
  5459. * @param array defines the source array
  5460. * @param offset defines the offset in the source array
  5461. * @param result defines the Vector3 where to store the result
  5462. */
  5463. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5464. return Vector3.FromArrayToRef(array, offset, result);
  5465. };
  5466. /**
  5467. * Sets the given vector "result" with the given floats.
  5468. * @param x defines the x coordinate of the source
  5469. * @param y defines the y coordinate of the source
  5470. * @param z defines the z coordinate of the source
  5471. * @param result defines the Vector3 where to store the result
  5472. */
  5473. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5474. result.copyFromFloats(x, y, z);
  5475. };
  5476. /**
  5477. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5478. * @returns a new empty Vector3
  5479. */
  5480. Vector3.Zero = function () {
  5481. return new Vector3(0.0, 0.0, 0.0);
  5482. };
  5483. /**
  5484. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5485. * @returns a new unit Vector3
  5486. */
  5487. Vector3.One = function () {
  5488. return new Vector3(1.0, 1.0, 1.0);
  5489. };
  5490. /**
  5491. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5492. * @returns a new up Vector3
  5493. */
  5494. Vector3.Up = function () {
  5495. return new Vector3(0.0, 1.0, 0.0);
  5496. };
  5497. /**
  5498. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5499. * @returns a new down Vector3
  5500. */
  5501. Vector3.Down = function () {
  5502. return new Vector3(0.0, -1.0, 0.0);
  5503. };
  5504. /**
  5505. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5506. * @returns a new forward Vector3
  5507. */
  5508. Vector3.Forward = function () {
  5509. return new Vector3(0.0, 0.0, 1.0);
  5510. };
  5511. /**
  5512. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5513. * @returns a new forward Vector3
  5514. */
  5515. Vector3.Backward = function () {
  5516. return new Vector3(0.0, 0.0, -1.0);
  5517. };
  5518. /**
  5519. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5520. * @returns a new right Vector3
  5521. */
  5522. Vector3.Right = function () {
  5523. return new Vector3(1.0, 0.0, 0.0);
  5524. };
  5525. /**
  5526. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5527. * @returns a new left Vector3
  5528. */
  5529. Vector3.Left = function () {
  5530. return new Vector3(-1.0, 0.0, 0.0);
  5531. };
  5532. /**
  5533. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5534. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5535. * @param vector defines the Vector3 to transform
  5536. * @param transformation defines the transformation matrix
  5537. * @returns the transformed Vector3
  5538. */
  5539. Vector3.TransformCoordinates = function (vector, transformation) {
  5540. var result = Vector3.Zero();
  5541. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5542. return result;
  5543. };
  5544. /**
  5545. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5546. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5547. * @param vector defines the Vector3 to transform
  5548. * @param transformation defines the transformation matrix
  5549. * @param result defines the Vector3 where to store the result
  5550. */
  5551. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5552. return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5553. };
  5554. /**
  5555. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5556. * This method computes tranformed coordinates only, not transformed direction vectors
  5557. * @param x define the x coordinate of the source vector
  5558. * @param y define the y coordinate of the source vector
  5559. * @param z define the z coordinate of the source vector
  5560. * @param transformation defines the transformation matrix
  5561. * @param result defines the Vector3 where to store the result
  5562. */
  5563. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5564. var m = transformation.m;
  5565. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5566. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5567. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5568. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5569. result.x = rx * rw;
  5570. result.y = ry * rw;
  5571. result.z = rz * rw;
  5572. };
  5573. /**
  5574. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5575. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5576. * @param vector defines the Vector3 to transform
  5577. * @param transformation defines the transformation matrix
  5578. * @returns the new Vector3
  5579. */
  5580. Vector3.TransformNormal = function (vector, transformation) {
  5581. var result = Vector3.Zero();
  5582. Vector3.TransformNormalToRef(vector, transformation, result);
  5583. return result;
  5584. };
  5585. /**
  5586. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5587. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5588. * @param vector defines the Vector3 to transform
  5589. * @param transformation defines the transformation matrix
  5590. * @param result defines the Vector3 where to store the result
  5591. */
  5592. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5593. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5594. };
  5595. /**
  5596. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5597. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5598. * @param x define the x coordinate of the source vector
  5599. * @param y define the y coordinate of the source vector
  5600. * @param z define the z coordinate of the source vector
  5601. * @param transformation defines the transformation matrix
  5602. * @param result defines the Vector3 where to store the result
  5603. */
  5604. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5605. var m = transformation.m;
  5606. result.x = x * m[0] + y * m[4] + z * m[8];
  5607. result.y = x * m[1] + y * m[5] + z * m[9];
  5608. result.z = x * m[2] + y * m[6] + z * m[10];
  5609. };
  5610. /**
  5611. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5612. * @param value1 defines the first control point
  5613. * @param value2 defines the second control point
  5614. * @param value3 defines the third control point
  5615. * @param value4 defines the fourth control point
  5616. * @param amount defines the amount on the spline to use
  5617. * @returns the new Vector3
  5618. */
  5619. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5620. var squared = amount * amount;
  5621. var cubed = amount * squared;
  5622. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5623. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5624. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5625. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5626. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5627. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5628. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5629. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5630. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5631. return new Vector3(x, y, z);
  5632. };
  5633. /**
  5634. * 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"
  5635. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5636. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5637. * @param value defines the current value
  5638. * @param min defines the lower range value
  5639. * @param max defines the upper range value
  5640. * @returns the new Vector3
  5641. */
  5642. Vector3.Clamp = function (value, min, max) {
  5643. var x = value.x;
  5644. x = (x > max.x) ? max.x : x;
  5645. x = (x < min.x) ? min.x : x;
  5646. var y = value.y;
  5647. y = (y > max.y) ? max.y : y;
  5648. y = (y < min.y) ? min.y : y;
  5649. var z = value.z;
  5650. z = (z > max.z) ? max.z : z;
  5651. z = (z < min.z) ? min.z : z;
  5652. return new Vector3(x, y, z);
  5653. };
  5654. /**
  5655. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5656. * @param value1 defines the first control point
  5657. * @param tangent1 defines the first tangent vector
  5658. * @param value2 defines the second control point
  5659. * @param tangent2 defines the second tangent vector
  5660. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5661. * @returns the new Vector3
  5662. */
  5663. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5664. var squared = amount * amount;
  5665. var cubed = amount * squared;
  5666. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5667. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5668. var part3 = (cubed - (2.0 * squared)) + amount;
  5669. var part4 = cubed - squared;
  5670. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5671. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5672. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5673. return new Vector3(x, y, z);
  5674. };
  5675. /**
  5676. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5677. * @param start defines the start value
  5678. * @param end defines the end value
  5679. * @param amount max defines amount between both (between 0 and 1)
  5680. * @returns the new Vector3
  5681. */
  5682. Vector3.Lerp = function (start, end, amount) {
  5683. var result = new Vector3(0, 0, 0);
  5684. Vector3.LerpToRef(start, end, amount, result);
  5685. return result;
  5686. };
  5687. /**
  5688. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5689. * @param start defines the start value
  5690. * @param end defines the end value
  5691. * @param amount max defines amount between both (between 0 and 1)
  5692. * @param result defines the Vector3 where to store the result
  5693. */
  5694. Vector3.LerpToRef = function (start, end, amount, result) {
  5695. result.x = start.x + ((end.x - start.x) * amount);
  5696. result.y = start.y + ((end.y - start.y) * amount);
  5697. result.z = start.z + ((end.z - start.z) * amount);
  5698. };
  5699. /**
  5700. * Returns the dot product (float) between the vectors "left" and "right"
  5701. * @param left defines the left operand
  5702. * @param right defines the right operand
  5703. * @returns the dot product
  5704. */
  5705. Vector3.Dot = function (left, right) {
  5706. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5707. };
  5708. /**
  5709. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5710. * The cross product is then orthogonal to both "left" and "right"
  5711. * @param left defines the left operand
  5712. * @param right defines the right operand
  5713. * @returns the cross product
  5714. */
  5715. Vector3.Cross = function (left, right) {
  5716. var result = Vector3.Zero();
  5717. Vector3.CrossToRef(left, right, result);
  5718. return result;
  5719. };
  5720. /**
  5721. * Sets the given vector "result" with the cross product of "left" and "right"
  5722. * The cross product is then orthogonal to both "left" and "right"
  5723. * @param left defines the left operand
  5724. * @param right defines the right operand
  5725. * @param result defines the Vector3 where to store the result
  5726. */
  5727. Vector3.CrossToRef = function (left, right, result) {
  5728. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  5729. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  5730. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  5731. result.copyFrom(MathTmp.Vector3[0]);
  5732. };
  5733. /**
  5734. * Returns a new Vector3 as the normalization of the given vector
  5735. * @param vector defines the Vector3 to normalize
  5736. * @returns the new Vector3
  5737. */
  5738. Vector3.Normalize = function (vector) {
  5739. var result = Vector3.Zero();
  5740. Vector3.NormalizeToRef(vector, result);
  5741. return result;
  5742. };
  5743. /**
  5744. * Sets the given vector "result" with the normalization of the given first vector
  5745. * @param vector defines the Vector3 to normalize
  5746. * @param result defines the Vector3 where to store the result
  5747. */
  5748. Vector3.NormalizeToRef = function (vector, result) {
  5749. vector.normalizeToRef(result);
  5750. };
  5751. /**
  5752. * Project a Vector3 onto screen space
  5753. * @param vector defines the Vector3 to project
  5754. * @param world defines the world matrix to use
  5755. * @param transform defines the transform (view x projection) matrix to use
  5756. * @param viewport defines the screen viewport to use
  5757. * @returns the new Vector3
  5758. */
  5759. Vector3.Project = function (vector, world, transform, viewport) {
  5760. var cw = viewport.width;
  5761. var ch = viewport.height;
  5762. var cx = viewport.x;
  5763. var cy = viewport.y;
  5764. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  5765. 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);
  5766. var matrix = MathTmp.Matrix[0];
  5767. world.multiplyToRef(transform, matrix);
  5768. matrix.multiplyToRef(viewportMatrix, matrix);
  5769. return Vector3.TransformCoordinates(vector, matrix);
  5770. };
  5771. /**
  5772. * Unproject from screen space to object space
  5773. * @param source defines the screen space Vector3 to use
  5774. * @param viewportWidth defines the current width of the viewport
  5775. * @param viewportHeight defines the current height of the viewport
  5776. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5777. * @param transform defines the transform (view x projection) matrix to use
  5778. * @returns the new Vector3
  5779. */
  5780. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5781. var matrix = MathTmp.Matrix[0];
  5782. world.multiplyToRef(transform, matrix);
  5783. matrix.invert();
  5784. source.x = source.x / viewportWidth * 2 - 1;
  5785. source.y = -(source.y / viewportHeight * 2 - 1);
  5786. var vector = Vector3.TransformCoordinates(source, matrix);
  5787. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  5788. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5789. vector = vector.scale(1.0 / num);
  5790. }
  5791. return vector;
  5792. };
  5793. /**
  5794. * Unproject from screen space to object space
  5795. * @param source defines the screen space Vector3 to use
  5796. * @param viewportWidth defines the current width of the viewport
  5797. * @param viewportHeight defines the current height of the viewport
  5798. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5799. * @param view defines the view matrix to use
  5800. * @param projection defines the projection matrix to use
  5801. * @returns the new Vector3
  5802. */
  5803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5804. var result = Vector3.Zero();
  5805. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Unproject from screen space to object space
  5810. * @param source defines the screen space Vector3 to use
  5811. * @param viewportWidth defines the current width of the viewport
  5812. * @param viewportHeight defines the current height of the viewport
  5813. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5814. * @param view defines the view matrix to use
  5815. * @param projection defines the projection matrix to use
  5816. * @param result defines the Vector3 where to store the result
  5817. */
  5818. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5819. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5820. };
  5821. /**
  5822. * Unproject from screen space to object space
  5823. * @param sourceX defines the screen space x coordinate to use
  5824. * @param sourceY defines the screen space y coordinate to use
  5825. * @param sourceZ defines the screen space z coordinate to use
  5826. * @param viewportWidth defines the current width of the viewport
  5827. * @param viewportHeight defines the current height of the viewport
  5828. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5829. * @param view defines the view matrix to use
  5830. * @param projection defines the projection matrix to use
  5831. * @param result defines the Vector3 where to store the result
  5832. */
  5833. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5834. var matrix = MathTmp.Matrix[0];
  5835. world.multiplyToRef(view, matrix);
  5836. matrix.multiplyToRef(projection, matrix);
  5837. matrix.invert();
  5838. var screenSource = MathTmp.Vector3[0];
  5839. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5840. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5841. screenSource.z = 2 * sourceZ - 1.0;
  5842. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  5843. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  5844. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5845. result.scaleInPlace(1.0 / num);
  5846. }
  5847. };
  5848. /**
  5849. * Gets the minimal coordinate values between two Vector3
  5850. * @param left defines the first operand
  5851. * @param right defines the second operand
  5852. * @returns the new Vector3
  5853. */
  5854. Vector3.Minimize = function (left, right) {
  5855. var min = left.clone();
  5856. min.minimizeInPlace(right);
  5857. return min;
  5858. };
  5859. /**
  5860. * Gets the maximal coordinate values between two Vector3
  5861. * @param left defines the first operand
  5862. * @param right defines the second operand
  5863. * @returns the new Vector3
  5864. */
  5865. Vector3.Maximize = function (left, right) {
  5866. var max = left.clone();
  5867. max.maximizeInPlace(right);
  5868. return max;
  5869. };
  5870. /**
  5871. * Returns the distance between the vectors "value1" and "value2"
  5872. * @param value1 defines the first operand
  5873. * @param value2 defines the second operand
  5874. * @returns the distance
  5875. */
  5876. Vector3.Distance = function (value1, value2) {
  5877. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  5878. };
  5879. /**
  5880. * Returns the squared distance between the vectors "value1" and "value2"
  5881. * @param value1 defines the first operand
  5882. * @param value2 defines the second operand
  5883. * @returns the squared distance
  5884. */
  5885. Vector3.DistanceSquared = function (value1, value2) {
  5886. var x = value1.x - value2.x;
  5887. var y = value1.y - value2.y;
  5888. var z = value1.z - value2.z;
  5889. return (x * x) + (y * y) + (z * z);
  5890. };
  5891. /**
  5892. * Returns a new Vector3 located at the center between "value1" and "value2"
  5893. * @param value1 defines the first operand
  5894. * @param value2 defines the second operand
  5895. * @returns the new Vector3
  5896. */
  5897. Vector3.Center = function (value1, value2) {
  5898. var center = value1.add(value2);
  5899. center.scaleInPlace(0.5);
  5900. return center;
  5901. };
  5902. /**
  5903. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  5904. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  5905. * to something in order to rotate it from its local system to the given target system
  5906. * Note: axis1, axis2 and axis3 are normalized during this operation
  5907. * @param axis1 defines the first axis
  5908. * @param axis2 defines the second axis
  5909. * @param axis3 defines the third axis
  5910. * @returns a new Vector3
  5911. */
  5912. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  5913. var rotation = Vector3.Zero();
  5914. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  5915. return rotation;
  5916. };
  5917. /**
  5918. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  5919. * @param axis1 defines the first axis
  5920. * @param axis2 defines the second axis
  5921. * @param axis3 defines the third axis
  5922. * @param ref defines the Vector3 where to store the result
  5923. */
  5924. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5925. var quat = MathTmp.Quaternion[0];
  5926. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5927. quat.toEulerAnglesToRef(ref);
  5928. };
  5929. return Vector3;
  5930. }());
  5931. BABYLON.Vector3 = Vector3;
  5932. /**
  5933. * Vector4 class created for EulerAngle class conversion to Quaternion
  5934. */
  5935. var Vector4 = /** @class */ (function () {
  5936. /**
  5937. * Creates a Vector4 object from the given floats.
  5938. * @param x x value of the vector
  5939. * @param y y value of the vector
  5940. * @param z z value of the vector
  5941. * @param w w value of the vector
  5942. */
  5943. function Vector4(
  5944. /** x value of the vector */
  5945. x,
  5946. /** y value of the vector */
  5947. y,
  5948. /** z value of the vector */
  5949. z,
  5950. /** w value of the vector */
  5951. w) {
  5952. this.x = x;
  5953. this.y = y;
  5954. this.z = z;
  5955. this.w = w;
  5956. }
  5957. /**
  5958. * Returns the string with the Vector4 coordinates.
  5959. * @returns a string containing all the vector values
  5960. */
  5961. Vector4.prototype.toString = function () {
  5962. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  5963. };
  5964. /**
  5965. * Returns the string "Vector4".
  5966. * @returns "Vector4"
  5967. */
  5968. Vector4.prototype.getClassName = function () {
  5969. return "Vector4";
  5970. };
  5971. /**
  5972. * Returns the Vector4 hash code.
  5973. * @returns a unique hash code
  5974. */
  5975. Vector4.prototype.getHashCode = function () {
  5976. var hash = this.x || 0;
  5977. hash = (hash * 397) ^ (this.y || 0);
  5978. hash = (hash * 397) ^ (this.z || 0);
  5979. hash = (hash * 397) ^ (this.w || 0);
  5980. return hash;
  5981. };
  5982. // Operators
  5983. /**
  5984. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  5985. * @returns the resulting array
  5986. */
  5987. Vector4.prototype.asArray = function () {
  5988. var result = new Array();
  5989. this.toArray(result, 0);
  5990. return result;
  5991. };
  5992. /**
  5993. * Populates the given array from the given index with the Vector4 coordinates.
  5994. * @param array array to populate
  5995. * @param index index of the array to start at (default: 0)
  5996. * @returns the Vector4.
  5997. */
  5998. Vector4.prototype.toArray = function (array, index) {
  5999. if (index === undefined) {
  6000. index = 0;
  6001. }
  6002. array[index] = this.x;
  6003. array[index + 1] = this.y;
  6004. array[index + 2] = this.z;
  6005. array[index + 3] = this.w;
  6006. return this;
  6007. };
  6008. /**
  6009. * Adds the given vector to the current Vector4.
  6010. * @param otherVector the vector to add
  6011. * @returns the updated Vector4.
  6012. */
  6013. Vector4.prototype.addInPlace = function (otherVector) {
  6014. this.x += otherVector.x;
  6015. this.y += otherVector.y;
  6016. this.z += otherVector.z;
  6017. this.w += otherVector.w;
  6018. return this;
  6019. };
  6020. /**
  6021. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6022. * @param otherVector the vector to add
  6023. * @returns the resulting vector
  6024. */
  6025. Vector4.prototype.add = function (otherVector) {
  6026. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6027. };
  6028. /**
  6029. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6030. * @param otherVector the vector to add
  6031. * @param result the vector to store the result
  6032. * @returns the current Vector4.
  6033. */
  6034. Vector4.prototype.addToRef = function (otherVector, result) {
  6035. result.x = this.x + otherVector.x;
  6036. result.y = this.y + otherVector.y;
  6037. result.z = this.z + otherVector.z;
  6038. result.w = this.w + otherVector.w;
  6039. return this;
  6040. };
  6041. /**
  6042. * Subtract in place the given vector from the current Vector4.
  6043. * @param otherVector the vector to subtract
  6044. * @returns the updated Vector4.
  6045. */
  6046. Vector4.prototype.subtractInPlace = function (otherVector) {
  6047. this.x -= otherVector.x;
  6048. this.y -= otherVector.y;
  6049. this.z -= otherVector.z;
  6050. this.w -= otherVector.w;
  6051. return this;
  6052. };
  6053. /**
  6054. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6055. * @param otherVector the vector to add
  6056. * @returns the new vector with the result
  6057. */
  6058. Vector4.prototype.subtract = function (otherVector) {
  6059. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6060. };
  6061. /**
  6062. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6063. * @param otherVector the vector to subtract
  6064. * @param result the vector to store the result
  6065. * @returns the current Vector4.
  6066. */
  6067. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6068. result.x = this.x - otherVector.x;
  6069. result.y = this.y - otherVector.y;
  6070. result.z = this.z - otherVector.z;
  6071. result.w = this.w - otherVector.w;
  6072. return this;
  6073. };
  6074. /**
  6075. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6076. */
  6077. /**
  6078. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6079. * @param x value to subtract
  6080. * @param y value to subtract
  6081. * @param z value to subtract
  6082. * @param w value to subtract
  6083. * @returns new vector containing the result
  6084. */
  6085. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6086. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6087. };
  6088. /**
  6089. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6090. * @param x value to subtract
  6091. * @param y value to subtract
  6092. * @param z value to subtract
  6093. * @param w value to subtract
  6094. * @param result the vector to store the result in
  6095. * @returns the current Vector4.
  6096. */
  6097. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6098. result.x = this.x - x;
  6099. result.y = this.y - y;
  6100. result.z = this.z - z;
  6101. result.w = this.w - w;
  6102. return this;
  6103. };
  6104. /**
  6105. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6106. * @returns a new vector with the negated values
  6107. */
  6108. Vector4.prototype.negate = function () {
  6109. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6110. };
  6111. /**
  6112. * Multiplies the current Vector4 coordinates by scale (float).
  6113. * @param scale the number to scale with
  6114. * @returns the updated Vector4.
  6115. */
  6116. Vector4.prototype.scaleInPlace = function (scale) {
  6117. this.x *= scale;
  6118. this.y *= scale;
  6119. this.z *= scale;
  6120. this.w *= scale;
  6121. return this;
  6122. };
  6123. /**
  6124. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6125. * @param scale the number to scale with
  6126. * @returns a new vector with the result
  6127. */
  6128. Vector4.prototype.scale = function (scale) {
  6129. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6130. };
  6131. /**
  6132. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6133. * @param scale the number to scale with
  6134. * @param result a vector to store the result in
  6135. * @returns the current Vector4.
  6136. */
  6137. Vector4.prototype.scaleToRef = function (scale, result) {
  6138. result.x = this.x * scale;
  6139. result.y = this.y * scale;
  6140. result.z = this.z * scale;
  6141. result.w = this.w * scale;
  6142. return this;
  6143. };
  6144. /**
  6145. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6146. * @param scale defines the scale factor
  6147. * @param result defines the Vector4 object where to store the result
  6148. * @returns the unmodified current Vector4
  6149. */
  6150. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6151. result.x += this.x * scale;
  6152. result.y += this.y * scale;
  6153. result.z += this.z * scale;
  6154. result.w += this.w * scale;
  6155. return this;
  6156. };
  6157. /**
  6158. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6159. * @param otherVector the vector to compare against
  6160. * @returns true if they are equal
  6161. */
  6162. Vector4.prototype.equals = function (otherVector) {
  6163. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6164. };
  6165. /**
  6166. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6167. * @param otherVector vector to compare against
  6168. * @param epsilon (Default: very small number)
  6169. * @returns true if they are equal
  6170. */
  6171. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6172. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6173. return otherVector
  6174. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6175. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6176. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6177. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6178. };
  6179. /**
  6180. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6181. * @param x x value to compare against
  6182. * @param y y value to compare against
  6183. * @param z z value to compare against
  6184. * @param w w value to compare against
  6185. * @returns true if equal
  6186. */
  6187. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6188. return this.x === x && this.y === y && this.z === z && this.w === w;
  6189. };
  6190. /**
  6191. * Multiplies in place the current Vector4 by the given one.
  6192. * @param otherVector vector to multiple with
  6193. * @returns the updated Vector4.
  6194. */
  6195. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6196. this.x *= otherVector.x;
  6197. this.y *= otherVector.y;
  6198. this.z *= otherVector.z;
  6199. this.w *= otherVector.w;
  6200. return this;
  6201. };
  6202. /**
  6203. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6204. * @param otherVector vector to multiple with
  6205. * @returns resulting new vector
  6206. */
  6207. Vector4.prototype.multiply = function (otherVector) {
  6208. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6209. };
  6210. /**
  6211. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6212. * @param otherVector vector to multiple with
  6213. * @param result vector to store the result
  6214. * @returns the current Vector4.
  6215. */
  6216. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6217. result.x = this.x * otherVector.x;
  6218. result.y = this.y * otherVector.y;
  6219. result.z = this.z * otherVector.z;
  6220. result.w = this.w * otherVector.w;
  6221. return this;
  6222. };
  6223. /**
  6224. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6225. * @param x x value multiply with
  6226. * @param y y value multiply with
  6227. * @param z z value multiply with
  6228. * @param w w value multiply with
  6229. * @returns resulting new vector
  6230. */
  6231. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6232. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6233. };
  6234. /**
  6235. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6236. * @param otherVector vector to devide with
  6237. * @returns resulting new vector
  6238. */
  6239. Vector4.prototype.divide = function (otherVector) {
  6240. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6241. };
  6242. /**
  6243. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6244. * @param otherVector vector to devide with
  6245. * @param result vector to store the result
  6246. * @returns the current Vector4.
  6247. */
  6248. Vector4.prototype.divideToRef = function (otherVector, result) {
  6249. result.x = this.x / otherVector.x;
  6250. result.y = this.y / otherVector.y;
  6251. result.z = this.z / otherVector.z;
  6252. result.w = this.w / otherVector.w;
  6253. return this;
  6254. };
  6255. /**
  6256. * Divides the current Vector3 coordinates by the given ones.
  6257. * @param otherVector vector to devide with
  6258. * @returns the updated Vector3.
  6259. */
  6260. Vector4.prototype.divideInPlace = function (otherVector) {
  6261. return this.divideToRef(otherVector, this);
  6262. };
  6263. /**
  6264. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6265. * @param other defines the second operand
  6266. * @returns the current updated Vector4
  6267. */
  6268. Vector4.prototype.minimizeInPlace = function (other) {
  6269. if (other.x < this.x) {
  6270. this.x = other.x;
  6271. }
  6272. if (other.y < this.y) {
  6273. this.y = other.y;
  6274. }
  6275. if (other.z < this.z) {
  6276. this.z = other.z;
  6277. }
  6278. if (other.w < this.w) {
  6279. this.w = other.w;
  6280. }
  6281. return this;
  6282. };
  6283. /**
  6284. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6285. * @param other defines the second operand
  6286. * @returns the current updated Vector4
  6287. */
  6288. Vector4.prototype.maximizeInPlace = function (other) {
  6289. if (other.x > this.x) {
  6290. this.x = other.x;
  6291. }
  6292. if (other.y > this.y) {
  6293. this.y = other.y;
  6294. }
  6295. if (other.z > this.z) {
  6296. this.z = other.z;
  6297. }
  6298. if (other.w > this.w) {
  6299. this.w = other.w;
  6300. }
  6301. return this;
  6302. };
  6303. /**
  6304. * Gets a new Vector4 from current Vector4 floored values
  6305. * @returns a new Vector4
  6306. */
  6307. Vector4.prototype.floor = function () {
  6308. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6309. };
  6310. /**
  6311. * Gets a new Vector4 from current Vector3 floored values
  6312. * @returns a new Vector4
  6313. */
  6314. Vector4.prototype.fract = function () {
  6315. 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));
  6316. };
  6317. // Properties
  6318. /**
  6319. * Returns the Vector4 length (float).
  6320. * @returns the length
  6321. */
  6322. Vector4.prototype.length = function () {
  6323. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6324. };
  6325. /**
  6326. * Returns the Vector4 squared length (float).
  6327. * @returns the length squared
  6328. */
  6329. Vector4.prototype.lengthSquared = function () {
  6330. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6331. };
  6332. // Methods
  6333. /**
  6334. * Normalizes in place the Vector4.
  6335. * @returns the updated Vector4.
  6336. */
  6337. Vector4.prototype.normalize = function () {
  6338. var len = this.length();
  6339. if (len === 0) {
  6340. return this;
  6341. }
  6342. return this.scaleInPlace(1.0 / len);
  6343. };
  6344. /**
  6345. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6346. * @returns this converted to a new vector3
  6347. */
  6348. Vector4.prototype.toVector3 = function () {
  6349. return new Vector3(this.x, this.y, this.z);
  6350. };
  6351. /**
  6352. * Returns a new Vector4 copied from the current one.
  6353. * @returns the new cloned vector
  6354. */
  6355. Vector4.prototype.clone = function () {
  6356. return new Vector4(this.x, this.y, this.z, this.w);
  6357. };
  6358. /**
  6359. * Updates the current Vector4 with the given one coordinates.
  6360. * @param source the source vector to copy from
  6361. * @returns the updated Vector4.
  6362. */
  6363. Vector4.prototype.copyFrom = function (source) {
  6364. this.x = source.x;
  6365. this.y = source.y;
  6366. this.z = source.z;
  6367. this.w = source.w;
  6368. return this;
  6369. };
  6370. /**
  6371. * Updates the current Vector4 coordinates with the given floats.
  6372. * @param x float to copy from
  6373. * @param y float to copy from
  6374. * @param z float to copy from
  6375. * @param w float to copy from
  6376. * @returns the updated Vector4.
  6377. */
  6378. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6379. this.x = x;
  6380. this.y = y;
  6381. this.z = z;
  6382. this.w = w;
  6383. return this;
  6384. };
  6385. /**
  6386. * Updates the current Vector4 coordinates with the given floats.
  6387. * @param x float to set from
  6388. * @param y float to set from
  6389. * @param z float to set from
  6390. * @param w float to set from
  6391. * @returns the updated Vector4.
  6392. */
  6393. Vector4.prototype.set = function (x, y, z, w) {
  6394. return this.copyFromFloats(x, y, z, w);
  6395. };
  6396. /**
  6397. * Copies the given float to the current Vector3 coordinates
  6398. * @param v defines the x, y, z and w coordinates of the operand
  6399. * @returns the current updated Vector3
  6400. */
  6401. Vector4.prototype.setAll = function (v) {
  6402. this.x = this.y = this.z = this.w = v;
  6403. return this;
  6404. };
  6405. // Statics
  6406. /**
  6407. * Returns a new Vector4 set from the starting index of the given array.
  6408. * @param array the array to pull values from
  6409. * @param offset the offset into the array to start at
  6410. * @returns the new vector
  6411. */
  6412. Vector4.FromArray = function (array, offset) {
  6413. if (!offset) {
  6414. offset = 0;
  6415. }
  6416. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6417. };
  6418. /**
  6419. * Updates the given vector "result" from the starting index of the given array.
  6420. * @param array the array to pull values from
  6421. * @param offset the offset into the array to start at
  6422. * @param result the vector to store the result in
  6423. */
  6424. Vector4.FromArrayToRef = function (array, offset, result) {
  6425. result.x = array[offset];
  6426. result.y = array[offset + 1];
  6427. result.z = array[offset + 2];
  6428. result.w = array[offset + 3];
  6429. };
  6430. /**
  6431. * Updates the given vector "result" from the starting index of the given Float32Array.
  6432. * @param array the array to pull values from
  6433. * @param offset the offset into the array to start at
  6434. * @param result the vector to store the result in
  6435. */
  6436. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6437. Vector4.FromArrayToRef(array, offset, result);
  6438. };
  6439. /**
  6440. * Updates the given vector "result" coordinates from the given floats.
  6441. * @param x float to set from
  6442. * @param y float to set from
  6443. * @param z float to set from
  6444. * @param w float to set from
  6445. * @param result the vector to the floats in
  6446. */
  6447. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6448. result.x = x;
  6449. result.y = y;
  6450. result.z = z;
  6451. result.w = w;
  6452. };
  6453. /**
  6454. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6455. * @returns the new vector
  6456. */
  6457. Vector4.Zero = function () {
  6458. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6459. };
  6460. /**
  6461. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6462. * @returns the new vector
  6463. */
  6464. Vector4.One = function () {
  6465. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6466. };
  6467. /**
  6468. * Returns a new normalized Vector4 from the given one.
  6469. * @param vector the vector to normalize
  6470. * @returns the vector
  6471. */
  6472. Vector4.Normalize = function (vector) {
  6473. var result = Vector4.Zero();
  6474. Vector4.NormalizeToRef(vector, result);
  6475. return result;
  6476. };
  6477. /**
  6478. * Updates the given vector "result" from the normalization of the given one.
  6479. * @param vector the vector to normalize
  6480. * @param result the vector to store the result in
  6481. */
  6482. Vector4.NormalizeToRef = function (vector, result) {
  6483. result.copyFrom(vector);
  6484. result.normalize();
  6485. };
  6486. /**
  6487. * Returns a vector with the minimum values from the left and right vectors
  6488. * @param left left vector to minimize
  6489. * @param right right vector to minimize
  6490. * @returns a new vector with the minimum of the left and right vector values
  6491. */
  6492. Vector4.Minimize = function (left, right) {
  6493. var min = left.clone();
  6494. min.minimizeInPlace(right);
  6495. return min;
  6496. };
  6497. /**
  6498. * Returns a vector with the maximum values from the left and right vectors
  6499. * @param left left vector to maximize
  6500. * @param right right vector to maximize
  6501. * @returns a new vector with the maximum of the left and right vector values
  6502. */
  6503. Vector4.Maximize = function (left, right) {
  6504. var max = left.clone();
  6505. max.maximizeInPlace(right);
  6506. return max;
  6507. };
  6508. /**
  6509. * Returns the distance (float) between the vectors "value1" and "value2".
  6510. * @param value1 value to calulate the distance between
  6511. * @param value2 value to calulate the distance between
  6512. * @return the distance between the two vectors
  6513. */
  6514. Vector4.Distance = function (value1, value2) {
  6515. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6516. };
  6517. /**
  6518. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6519. * @param value1 value to calulate the distance between
  6520. * @param value2 value to calulate the distance between
  6521. * @return the distance between the two vectors squared
  6522. */
  6523. Vector4.DistanceSquared = function (value1, value2) {
  6524. var x = value1.x - value2.x;
  6525. var y = value1.y - value2.y;
  6526. var z = value1.z - value2.z;
  6527. var w = value1.w - value2.w;
  6528. return (x * x) + (y * y) + (z * z) + (w * w);
  6529. };
  6530. /**
  6531. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6532. * @param value1 value to calulate the center between
  6533. * @param value2 value to calulate the center between
  6534. * @return the center between the two vectors
  6535. */
  6536. Vector4.Center = function (value1, value2) {
  6537. var center = value1.add(value2);
  6538. center.scaleInPlace(0.5);
  6539. return center;
  6540. };
  6541. /**
  6542. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6543. * This methods computes transformed normalized direction vectors only.
  6544. * @param vector the vector to transform
  6545. * @param transformation the transformation matrix to apply
  6546. * @returns the new vector
  6547. */
  6548. Vector4.TransformNormal = function (vector, transformation) {
  6549. var result = Vector4.Zero();
  6550. Vector4.TransformNormalToRef(vector, transformation, result);
  6551. return result;
  6552. };
  6553. /**
  6554. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6555. * This methods computes transformed normalized direction vectors only.
  6556. * @param vector the vector to transform
  6557. * @param transformation the transformation matrix to apply
  6558. * @param result the vector to store the result in
  6559. */
  6560. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6561. var m = transformation.m;
  6562. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6563. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6564. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6565. result.x = x;
  6566. result.y = y;
  6567. result.z = z;
  6568. result.w = vector.w;
  6569. };
  6570. /**
  6571. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6572. * This methods computes transformed normalized direction vectors only.
  6573. * @param x value to transform
  6574. * @param y value to transform
  6575. * @param z value to transform
  6576. * @param w value to transform
  6577. * @param transformation the transformation matrix to apply
  6578. * @param result the vector to store the results in
  6579. */
  6580. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6581. var m = transformation.m;
  6582. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6583. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6584. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6585. result.w = w;
  6586. };
  6587. return Vector4;
  6588. }());
  6589. BABYLON.Vector4 = Vector4;
  6590. /**
  6591. * Size containing widht and height
  6592. */
  6593. var Size = /** @class */ (function () {
  6594. /**
  6595. * Creates a Size object from the given width and height (floats).
  6596. * @param width width of the new size
  6597. * @param height height of the new size
  6598. */
  6599. function Size(width, height) {
  6600. this.width = width;
  6601. this.height = height;
  6602. }
  6603. /**
  6604. * Returns a string with the Size width and height
  6605. * @returns a string with the Size width and height
  6606. */
  6607. Size.prototype.toString = function () {
  6608. return "{W: " + this.width + ", H: " + this.height + "}";
  6609. };
  6610. /**
  6611. * "Size"
  6612. * @returns the string "Size"
  6613. */
  6614. Size.prototype.getClassName = function () {
  6615. return "Size";
  6616. };
  6617. /**
  6618. * Returns the Size hash code.
  6619. * @returns a hash code for a unique width and height
  6620. */
  6621. Size.prototype.getHashCode = function () {
  6622. var hash = this.width || 0;
  6623. hash = (hash * 397) ^ (this.height || 0);
  6624. return hash;
  6625. };
  6626. /**
  6627. * Updates the current size from the given one.
  6628. * @param src the given size
  6629. */
  6630. Size.prototype.copyFrom = function (src) {
  6631. this.width = src.width;
  6632. this.height = src.height;
  6633. };
  6634. /**
  6635. * Updates in place the current Size from the given floats.
  6636. * @param width width of the new size
  6637. * @param height height of the new size
  6638. * @returns the updated Size.
  6639. */
  6640. Size.prototype.copyFromFloats = function (width, height) {
  6641. this.width = width;
  6642. this.height = height;
  6643. return this;
  6644. };
  6645. /**
  6646. * Updates in place the current Size from the given floats.
  6647. * @param width width to set
  6648. * @param height height to set
  6649. * @returns the updated Size.
  6650. */
  6651. Size.prototype.set = function (width, height) {
  6652. return this.copyFromFloats(width, height);
  6653. };
  6654. /**
  6655. * Multiplies the width and height by numbers
  6656. * @param w factor to multiple the width by
  6657. * @param h factor to multiple the height by
  6658. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6659. */
  6660. Size.prototype.multiplyByFloats = function (w, h) {
  6661. return new Size(this.width * w, this.height * h);
  6662. };
  6663. /**
  6664. * Clones the size
  6665. * @returns a new Size copied from the given one.
  6666. */
  6667. Size.prototype.clone = function () {
  6668. return new Size(this.width, this.height);
  6669. };
  6670. /**
  6671. * True if the current Size and the given one width and height are strictly equal.
  6672. * @param other the other size to compare against
  6673. * @returns True if the current Size and the given one width and height are strictly equal.
  6674. */
  6675. Size.prototype.equals = function (other) {
  6676. if (!other) {
  6677. return false;
  6678. }
  6679. return (this.width === other.width) && (this.height === other.height);
  6680. };
  6681. Object.defineProperty(Size.prototype, "surface", {
  6682. /**
  6683. * The surface of the Size : width * height (float).
  6684. */
  6685. get: function () {
  6686. return this.width * this.height;
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. /**
  6692. * Create a new size of zero
  6693. * @returns a new Size set to (0.0, 0.0)
  6694. */
  6695. Size.Zero = function () {
  6696. return new Size(0.0, 0.0);
  6697. };
  6698. /**
  6699. * Sums the width and height of two sizes
  6700. * @param otherSize size to add to this size
  6701. * @returns a new Size set as the addition result of the current Size and the given one.
  6702. */
  6703. Size.prototype.add = function (otherSize) {
  6704. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6705. return r;
  6706. };
  6707. /**
  6708. * Subtracts the width and height of two
  6709. * @param otherSize size to subtract to this size
  6710. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6711. */
  6712. Size.prototype.subtract = function (otherSize) {
  6713. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6714. return r;
  6715. };
  6716. /**
  6717. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6718. * @param start starting size to lerp between
  6719. * @param end end size to lerp between
  6720. * @param amount amount to lerp between the start and end values
  6721. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6722. */
  6723. Size.Lerp = function (start, end, amount) {
  6724. var w = start.width + ((end.width - start.width) * amount);
  6725. var h = start.height + ((end.height - start.height) * amount);
  6726. return new Size(w, h);
  6727. };
  6728. return Size;
  6729. }());
  6730. BABYLON.Size = Size;
  6731. /**
  6732. * Class used to store quaternion data
  6733. * @see https://en.wikipedia.org/wiki/Quaternion
  6734. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6735. */
  6736. var Quaternion = /** @class */ (function () {
  6737. /**
  6738. * Creates a new Quaternion from the given floats
  6739. * @param x defines the first component (0 by default)
  6740. * @param y defines the second component (0 by default)
  6741. * @param z defines the third component (0 by default)
  6742. * @param w defines the fourth component (1.0 by default)
  6743. */
  6744. function Quaternion(
  6745. /** defines the first component (0 by default) */
  6746. x,
  6747. /** defines the second component (0 by default) */
  6748. y,
  6749. /** defines the third component (0 by default) */
  6750. z,
  6751. /** defines the fourth component (1.0 by default) */
  6752. w) {
  6753. if (x === void 0) { x = 0.0; }
  6754. if (y === void 0) { y = 0.0; }
  6755. if (z === void 0) { z = 0.0; }
  6756. if (w === void 0) { w = 1.0; }
  6757. this.x = x;
  6758. this.y = y;
  6759. this.z = z;
  6760. this.w = w;
  6761. }
  6762. /**
  6763. * Gets a string representation for the current quaternion
  6764. * @returns a string with the Quaternion coordinates
  6765. */
  6766. Quaternion.prototype.toString = function () {
  6767. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6768. };
  6769. /**
  6770. * Gets the class name of the quaternion
  6771. * @returns the string "Quaternion"
  6772. */
  6773. Quaternion.prototype.getClassName = function () {
  6774. return "Quaternion";
  6775. };
  6776. /**
  6777. * Gets a hash code for this quaternion
  6778. * @returns the quaternion hash code
  6779. */
  6780. Quaternion.prototype.getHashCode = function () {
  6781. var hash = this.x || 0;
  6782. hash = (hash * 397) ^ (this.y || 0);
  6783. hash = (hash * 397) ^ (this.z || 0);
  6784. hash = (hash * 397) ^ (this.w || 0);
  6785. return hash;
  6786. };
  6787. /**
  6788. * Copy the quaternion to an array
  6789. * @returns a new array populated with 4 elements from the quaternion coordinates
  6790. */
  6791. Quaternion.prototype.asArray = function () {
  6792. return [this.x, this.y, this.z, this.w];
  6793. };
  6794. /**
  6795. * Check if two quaternions are equals
  6796. * @param otherQuaternion defines the second operand
  6797. * @return true if the current quaternion and the given one coordinates are strictly equals
  6798. */
  6799. Quaternion.prototype.equals = function (otherQuaternion) {
  6800. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6801. };
  6802. /**
  6803. * Clone the current quaternion
  6804. * @returns a new quaternion copied from the current one
  6805. */
  6806. Quaternion.prototype.clone = function () {
  6807. return new Quaternion(this.x, this.y, this.z, this.w);
  6808. };
  6809. /**
  6810. * Copy a quaternion to the current one
  6811. * @param other defines the other quaternion
  6812. * @returns the updated current quaternion
  6813. */
  6814. Quaternion.prototype.copyFrom = function (other) {
  6815. this.x = other.x;
  6816. this.y = other.y;
  6817. this.z = other.z;
  6818. this.w = other.w;
  6819. return this;
  6820. };
  6821. /**
  6822. * Updates the current quaternion with the given float coordinates
  6823. * @param x defines the x coordinate
  6824. * @param y defines the y coordinate
  6825. * @param z defines the z coordinate
  6826. * @param w defines the w coordinate
  6827. * @returns the updated current quaternion
  6828. */
  6829. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  6830. this.x = x;
  6831. this.y = y;
  6832. this.z = z;
  6833. this.w = w;
  6834. return this;
  6835. };
  6836. /**
  6837. * Updates the current quaternion from the given float coordinates
  6838. * @param x defines the x coordinate
  6839. * @param y defines the y coordinate
  6840. * @param z defines the z coordinate
  6841. * @param w defines the w coordinate
  6842. * @returns the updated current quaternion
  6843. */
  6844. Quaternion.prototype.set = function (x, y, z, w) {
  6845. return this.copyFromFloats(x, y, z, w);
  6846. };
  6847. /**
  6848. * Adds two quaternions
  6849. * @param other defines the second operand
  6850. * @returns a new quaternion as the addition result of the given one and the current quaternion
  6851. */
  6852. Quaternion.prototype.add = function (other) {
  6853. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  6854. };
  6855. /**
  6856. * Add a quaternion to the current one
  6857. * @param other defines the quaternion to add
  6858. * @returns the current quaternion
  6859. */
  6860. Quaternion.prototype.addInPlace = function (other) {
  6861. this.x += other.x;
  6862. this.y += other.y;
  6863. this.z += other.z;
  6864. this.w += other.w;
  6865. return this;
  6866. };
  6867. /**
  6868. * Subtract two quaternions
  6869. * @param other defines the second operand
  6870. * @returns a new quaternion as the subtraction result of the given one from the current one
  6871. */
  6872. Quaternion.prototype.subtract = function (other) {
  6873. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  6874. };
  6875. /**
  6876. * Multiplies the current quaternion by a scale factor
  6877. * @param value defines the scale factor
  6878. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  6879. */
  6880. Quaternion.prototype.scale = function (value) {
  6881. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  6882. };
  6883. /**
  6884. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  6885. * @param scale defines the scale factor
  6886. * @param result defines the Quaternion object where to store the result
  6887. * @returns the unmodified current quaternion
  6888. */
  6889. Quaternion.prototype.scaleToRef = function (scale, result) {
  6890. result.x = this.x * scale;
  6891. result.y = this.y * scale;
  6892. result.z = this.z * scale;
  6893. result.w = this.w * scale;
  6894. return this;
  6895. };
  6896. /**
  6897. * Multiplies in place the current quaternion by a scale factor
  6898. * @param value defines the scale factor
  6899. * @returns the current modified quaternion
  6900. */
  6901. Quaternion.prototype.scaleInPlace = function (value) {
  6902. this.x *= value;
  6903. this.y *= value;
  6904. this.z *= value;
  6905. this.w *= value;
  6906. return this;
  6907. };
  6908. /**
  6909. * Scale the current quaternion values by a factor and add the result to a given quaternion
  6910. * @param scale defines the scale factor
  6911. * @param result defines the Quaternion object where to store the result
  6912. * @returns the unmodified current quaternion
  6913. */
  6914. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  6915. result.x += this.x * scale;
  6916. result.y += this.y * scale;
  6917. result.z += this.z * scale;
  6918. result.w += this.w * scale;
  6919. return this;
  6920. };
  6921. /**
  6922. * Multiplies two quaternions
  6923. * @param q1 defines the second operand
  6924. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  6925. */
  6926. Quaternion.prototype.multiply = function (q1) {
  6927. var result = new Quaternion(0, 0, 0, 1.0);
  6928. this.multiplyToRef(q1, result);
  6929. return result;
  6930. };
  6931. /**
  6932. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  6933. * @param q1 defines the second operand
  6934. * @param result defines the target quaternion
  6935. * @returns the current quaternion
  6936. */
  6937. Quaternion.prototype.multiplyToRef = function (q1, result) {
  6938. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  6939. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  6940. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  6941. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  6942. result.copyFromFloats(x, y, z, w);
  6943. return this;
  6944. };
  6945. /**
  6946. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  6947. * @param q1 defines the second operand
  6948. * @returns the currentupdated quaternion
  6949. */
  6950. Quaternion.prototype.multiplyInPlace = function (q1) {
  6951. this.multiplyToRef(q1, this);
  6952. return this;
  6953. };
  6954. /**
  6955. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  6956. * @param ref defines the target quaternion
  6957. * @returns the current quaternion
  6958. */
  6959. Quaternion.prototype.conjugateToRef = function (ref) {
  6960. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  6961. return this;
  6962. };
  6963. /**
  6964. * Conjugates in place (1-q) the current quaternion
  6965. * @returns the current updated quaternion
  6966. */
  6967. Quaternion.prototype.conjugateInPlace = function () {
  6968. this.x *= -1;
  6969. this.y *= -1;
  6970. this.z *= -1;
  6971. return this;
  6972. };
  6973. /**
  6974. * Conjugates in place (1-q) the current quaternion
  6975. * @returns a new quaternion
  6976. */
  6977. Quaternion.prototype.conjugate = function () {
  6978. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  6979. return result;
  6980. };
  6981. /**
  6982. * Gets length of current quaternion
  6983. * @returns the quaternion length (float)
  6984. */
  6985. Quaternion.prototype.length = function () {
  6986. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  6987. };
  6988. /**
  6989. * Normalize in place the current quaternion
  6990. * @returns the current updated quaternion
  6991. */
  6992. Quaternion.prototype.normalize = function () {
  6993. var length = 1.0 / this.length();
  6994. this.x *= length;
  6995. this.y *= length;
  6996. this.z *= length;
  6997. this.w *= length;
  6998. return this;
  6999. };
  7000. /**
  7001. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7002. * @param order is a reserved parameter and is ignore for now
  7003. * @returns a new Vector3 containing the Euler angles
  7004. */
  7005. Quaternion.prototype.toEulerAngles = function (order) {
  7006. if (order === void 0) { order = "YZX"; }
  7007. var result = Vector3.Zero();
  7008. this.toEulerAnglesToRef(result, order);
  7009. return result;
  7010. };
  7011. /**
  7012. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7013. * @param result defines the vector which will be filled with the Euler angles
  7014. * @param order is a reserved parameter and is ignore for now
  7015. * @returns the current unchanged quaternion
  7016. */
  7017. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7018. if (order === void 0) { order = "YZX"; }
  7019. var qz = this.z;
  7020. var qx = this.x;
  7021. var qy = this.y;
  7022. var qw = this.w;
  7023. var sqw = qw * qw;
  7024. var sqz = qz * qz;
  7025. var sqx = qx * qx;
  7026. var sqy = qy * qy;
  7027. var zAxisY = qy * qz - qx * qw;
  7028. var limit = .4999999;
  7029. if (zAxisY < -limit) {
  7030. result.y = 2 * Math.atan2(qy, qw);
  7031. result.x = Math.PI / 2;
  7032. result.z = 0;
  7033. }
  7034. else if (zAxisY > limit) {
  7035. result.y = 2 * Math.atan2(qy, qw);
  7036. result.x = -Math.PI / 2;
  7037. result.z = 0;
  7038. }
  7039. else {
  7040. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7041. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7042. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7043. }
  7044. return this;
  7045. };
  7046. /**
  7047. * Updates the given rotation matrix with the current quaternion values
  7048. * @param result defines the target matrix
  7049. * @returns the current unchanged quaternion
  7050. */
  7051. Quaternion.prototype.toRotationMatrix = function (result) {
  7052. var xx = this.x * this.x;
  7053. var yy = this.y * this.y;
  7054. var zz = this.z * this.z;
  7055. var xy = this.x * this.y;
  7056. var zw = this.z * this.w;
  7057. var zx = this.z * this.x;
  7058. var yw = this.y * this.w;
  7059. var yz = this.y * this.z;
  7060. var xw = this.x * this.w;
  7061. result.m[0] = 1.0 - (2.0 * (yy + zz));
  7062. result.m[1] = 2.0 * (xy + zw);
  7063. result.m[2] = 2.0 * (zx - yw);
  7064. result.m[3] = 0;
  7065. result.m[4] = 2.0 * (xy - zw);
  7066. result.m[5] = 1.0 - (2.0 * (zz + xx));
  7067. result.m[6] = 2.0 * (yz + xw);
  7068. result.m[7] = 0;
  7069. result.m[8] = 2.0 * (zx + yw);
  7070. result.m[9] = 2.0 * (yz - xw);
  7071. result.m[10] = 1.0 - (2.0 * (yy + xx));
  7072. result.m[11] = 0;
  7073. result.m[12] = 0;
  7074. result.m[13] = 0;
  7075. result.m[14] = 0;
  7076. result.m[15] = 1.0;
  7077. result._markAsUpdated();
  7078. return this;
  7079. };
  7080. /**
  7081. * Updates the current quaternion from the given rotation matrix values
  7082. * @param matrix defines the source matrix
  7083. * @returns the current updated quaternion
  7084. */
  7085. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7086. Quaternion.FromRotationMatrixToRef(matrix, this);
  7087. return this;
  7088. };
  7089. // Statics
  7090. /**
  7091. * Creates a new quaternion from a rotation matrix
  7092. * @param matrix defines the source matrix
  7093. * @returns a new quaternion created from the given rotation matrix values
  7094. */
  7095. Quaternion.FromRotationMatrix = function (matrix) {
  7096. var result = new Quaternion();
  7097. Quaternion.FromRotationMatrixToRef(matrix, result);
  7098. return result;
  7099. };
  7100. /**
  7101. * Updates the given quaternion with the given rotation matrix values
  7102. * @param matrix defines the source matrix
  7103. * @param result defines the target quaternion
  7104. */
  7105. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7106. var data = matrix.m;
  7107. var m11 = data[0], m12 = data[4], m13 = data[8];
  7108. var m21 = data[1], m22 = data[5], m23 = data[9];
  7109. var m31 = data[2], m32 = data[6], m33 = data[10];
  7110. var trace = m11 + m22 + m33;
  7111. var s;
  7112. if (trace > 0) {
  7113. s = 0.5 / Math.sqrt(trace + 1.0);
  7114. result.w = 0.25 / s;
  7115. result.x = (m32 - m23) * s;
  7116. result.y = (m13 - m31) * s;
  7117. result.z = (m21 - m12) * s;
  7118. }
  7119. else if (m11 > m22 && m11 > m33) {
  7120. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7121. result.w = (m32 - m23) / s;
  7122. result.x = 0.25 * s;
  7123. result.y = (m12 + m21) / s;
  7124. result.z = (m13 + m31) / s;
  7125. }
  7126. else if (m22 > m33) {
  7127. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7128. result.w = (m13 - m31) / s;
  7129. result.x = (m12 + m21) / s;
  7130. result.y = 0.25 * s;
  7131. result.z = (m23 + m32) / s;
  7132. }
  7133. else {
  7134. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7135. result.w = (m21 - m12) / s;
  7136. result.x = (m13 + m31) / s;
  7137. result.y = (m23 + m32) / s;
  7138. result.z = 0.25 * s;
  7139. }
  7140. };
  7141. /**
  7142. * Returns the dot product (float) between the quaternions "left" and "right"
  7143. * @param left defines the left operand
  7144. * @param right defines the right operand
  7145. * @returns the dot product
  7146. */
  7147. Quaternion.Dot = function (left, right) {
  7148. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7149. };
  7150. /**
  7151. * Checks if the two quaternions are close to each other
  7152. * @param quat0 defines the first quaternion to check
  7153. * @param quat1 defines the second quaternion to check
  7154. * @returns true if the two quaternions are close to each other
  7155. */
  7156. Quaternion.AreClose = function (quat0, quat1) {
  7157. var dot = Quaternion.Dot(quat0, quat1);
  7158. return dot >= 0;
  7159. };
  7160. /**
  7161. * Creates an empty quaternion
  7162. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7163. */
  7164. Quaternion.Zero = function () {
  7165. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7166. };
  7167. /**
  7168. * Inverse a given quaternion
  7169. * @param q defines the source quaternion
  7170. * @returns a new quaternion as the inverted current quaternion
  7171. */
  7172. Quaternion.Inverse = function (q) {
  7173. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7174. };
  7175. /**
  7176. * Creates an identity quaternion
  7177. * @returns the identity quaternion
  7178. */
  7179. Quaternion.Identity = function () {
  7180. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7181. };
  7182. /**
  7183. * Gets a boolean indicating if the given quaternion is identity
  7184. * @param quaternion defines the quaternion to check
  7185. * @returns true if the quaternion is identity
  7186. */
  7187. Quaternion.IsIdentity = function (quaternion) {
  7188. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7189. };
  7190. /**
  7191. * Creates a quaternion from a rotation around an axis
  7192. * @param axis defines the axis to use
  7193. * @param angle defines the angle to use
  7194. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7195. */
  7196. Quaternion.RotationAxis = function (axis, angle) {
  7197. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7198. };
  7199. /**
  7200. * Creates a rotation around an axis and stores it into the given quaternion
  7201. * @param axis defines the axis to use
  7202. * @param angle defines the angle to use
  7203. * @param result defines the target quaternion
  7204. * @returns the target quaternion
  7205. */
  7206. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7207. var sin = Math.sin(angle / 2);
  7208. axis.normalize();
  7209. result.w = Math.cos(angle / 2);
  7210. result.x = axis.x * sin;
  7211. result.y = axis.y * sin;
  7212. result.z = axis.z * sin;
  7213. return result;
  7214. };
  7215. /**
  7216. * Creates a new quaternion from data stored into an array
  7217. * @param array defines the data source
  7218. * @param offset defines the offset in the source array where the data starts
  7219. * @returns a new quaternion
  7220. */
  7221. Quaternion.FromArray = function (array, offset) {
  7222. if (!offset) {
  7223. offset = 0;
  7224. }
  7225. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7226. };
  7227. /**
  7228. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7229. * @param yaw defines the rotation around Y axis
  7230. * @param pitch defines the rotation around X axis
  7231. * @param roll defines the rotation around Z axis
  7232. * @returns the new quaternion
  7233. */
  7234. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7235. var q = new Quaternion();
  7236. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7237. return q;
  7238. };
  7239. /**
  7240. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7241. * @param yaw defines the rotation around Y axis
  7242. * @param pitch defines the rotation around X axis
  7243. * @param roll defines the rotation around Z axis
  7244. * @param result defines the target quaternion
  7245. */
  7246. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7247. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7248. var halfRoll = roll * 0.5;
  7249. var halfPitch = pitch * 0.5;
  7250. var halfYaw = yaw * 0.5;
  7251. var sinRoll = Math.sin(halfRoll);
  7252. var cosRoll = Math.cos(halfRoll);
  7253. var sinPitch = Math.sin(halfPitch);
  7254. var cosPitch = Math.cos(halfPitch);
  7255. var sinYaw = Math.sin(halfYaw);
  7256. var cosYaw = Math.cos(halfYaw);
  7257. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7258. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7259. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7260. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7261. };
  7262. /**
  7263. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7264. * @param alpha defines the rotation around first axis
  7265. * @param beta defines the rotation around second axis
  7266. * @param gamma defines the rotation around third axis
  7267. * @returns the new quaternion
  7268. */
  7269. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7270. var result = new Quaternion();
  7271. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7272. return result;
  7273. };
  7274. /**
  7275. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7276. * @param alpha defines the rotation around first axis
  7277. * @param beta defines the rotation around second axis
  7278. * @param gamma defines the rotation around third axis
  7279. * @param result defines the target quaternion
  7280. */
  7281. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7282. // Produces a quaternion from Euler angles in the z-x-z orientation
  7283. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7284. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7285. var halfBeta = beta * 0.5;
  7286. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7287. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7288. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7289. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7290. };
  7291. /**
  7292. * 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)
  7293. * @param axis1 defines the first axis
  7294. * @param axis2 defines the second axis
  7295. * @param axis3 defines the third axis
  7296. * @returns the new quaternion
  7297. */
  7298. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7299. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7300. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7301. return quat;
  7302. };
  7303. /**
  7304. * 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
  7305. * @param axis1 defines the first axis
  7306. * @param axis2 defines the second axis
  7307. * @param axis3 defines the third axis
  7308. * @param ref defines the target quaternion
  7309. */
  7310. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7311. var rotMat = MathTmp.Matrix[0];
  7312. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7313. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7314. };
  7315. /**
  7316. * Interpolates between two quaternions
  7317. * @param left defines first quaternion
  7318. * @param right defines second quaternion
  7319. * @param amount defines the gradient to use
  7320. * @returns the new interpolated quaternion
  7321. */
  7322. Quaternion.Slerp = function (left, right, amount) {
  7323. var result = Quaternion.Identity();
  7324. Quaternion.SlerpToRef(left, right, amount, result);
  7325. return result;
  7326. };
  7327. /**
  7328. * Interpolates between two quaternions and stores it into a target quaternion
  7329. * @param left defines first quaternion
  7330. * @param right defines second quaternion
  7331. * @param amount defines the gradient to use
  7332. * @param result defines the target quaternion
  7333. */
  7334. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7335. var num2;
  7336. var num3;
  7337. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7338. var flag = false;
  7339. if (num4 < 0) {
  7340. flag = true;
  7341. num4 = -num4;
  7342. }
  7343. if (num4 > 0.999999) {
  7344. num3 = 1 - amount;
  7345. num2 = flag ? -amount : amount;
  7346. }
  7347. else {
  7348. var num5 = Math.acos(num4);
  7349. var num6 = (1.0 / Math.sin(num5));
  7350. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7351. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7352. }
  7353. result.x = (num3 * left.x) + (num2 * right.x);
  7354. result.y = (num3 * left.y) + (num2 * right.y);
  7355. result.z = (num3 * left.z) + (num2 * right.z);
  7356. result.w = (num3 * left.w) + (num2 * right.w);
  7357. };
  7358. /**
  7359. * Interpolate between two quaternions using Hermite interpolation
  7360. * @param value1 defines first quaternion
  7361. * @param tangent1 defines the incoming tangent
  7362. * @param value2 defines second quaternion
  7363. * @param tangent2 defines the outgoing tangent
  7364. * @param amount defines the target quaternion
  7365. * @returns the new interpolated quaternion
  7366. */
  7367. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7368. var squared = amount * amount;
  7369. var cubed = amount * squared;
  7370. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7371. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7372. var part3 = (cubed - (2.0 * squared)) + amount;
  7373. var part4 = cubed - squared;
  7374. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7375. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7376. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7377. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7378. return new Quaternion(x, y, z, w);
  7379. };
  7380. return Quaternion;
  7381. }());
  7382. BABYLON.Quaternion = Quaternion;
  7383. /**
  7384. * Class used to store matrix data (4x4)
  7385. */
  7386. var Matrix = /** @class */ (function () {
  7387. /**
  7388. * Creates an empty matrix (filled with zeros)
  7389. */
  7390. function Matrix() {
  7391. this._isIdentity = false;
  7392. this._isIdentityDirty = true;
  7393. /**
  7394. * Gets or sets the internal data of the matrix
  7395. */
  7396. this.m = new Float32Array(16);
  7397. this._markAsUpdated();
  7398. }
  7399. /** @hidden */
  7400. Matrix.prototype._markAsUpdated = function () {
  7401. this.updateFlag = Matrix._updateFlagSeed++;
  7402. this._isIdentityDirty = true;
  7403. };
  7404. // Properties
  7405. /**
  7406. * Check if the current matrix is indentity
  7407. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  7408. * @returns true is the matrix is the identity matrix
  7409. */
  7410. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  7411. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  7412. if (this._isIdentityDirty) {
  7413. this._isIdentityDirty = false;
  7414. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  7415. this._isIdentity = false;
  7416. }
  7417. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  7418. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  7419. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  7420. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  7421. this._isIdentity = false;
  7422. }
  7423. else {
  7424. this._isIdentity = true;
  7425. }
  7426. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  7427. this._isIdentity = false;
  7428. }
  7429. }
  7430. return this._isIdentity;
  7431. };
  7432. /**
  7433. * Gets the determinant of the matrix
  7434. * @returns the matrix determinant
  7435. */
  7436. Matrix.prototype.determinant = function () {
  7437. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  7438. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  7439. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  7440. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  7441. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  7442. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  7443. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  7444. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  7445. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  7446. };
  7447. // Methods
  7448. /**
  7449. * Returns the matrix as a Float32Array
  7450. * @returns the matrix underlying array
  7451. */
  7452. Matrix.prototype.toArray = function () {
  7453. return this.m;
  7454. };
  7455. /**
  7456. * Returns the matrix as a Float32Array
  7457. * @returns the matrix underlying array.
  7458. */
  7459. Matrix.prototype.asArray = function () {
  7460. return this.toArray();
  7461. };
  7462. /**
  7463. * Inverts the current matrix in place
  7464. * @returns the current inverted matrix
  7465. */
  7466. Matrix.prototype.invert = function () {
  7467. this.invertToRef(this);
  7468. return this;
  7469. };
  7470. /**
  7471. * Sets all the matrix elements to zero
  7472. * @returns the current matrix
  7473. */
  7474. Matrix.prototype.reset = function () {
  7475. for (var index = 0; index < 16; index++) {
  7476. this.m[index] = 0.0;
  7477. }
  7478. this._markAsUpdated();
  7479. return this;
  7480. };
  7481. /**
  7482. * Adds the current matrix with a second one
  7483. * @param other defines the matrix to add
  7484. * @returns a new matrix as the addition of the current matrix and the given one
  7485. */
  7486. Matrix.prototype.add = function (other) {
  7487. var result = new Matrix();
  7488. this.addToRef(other, result);
  7489. return result;
  7490. };
  7491. /**
  7492. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7493. * @param other defines the matrix to add
  7494. * @param result defines the target matrix
  7495. * @returns the current matrix
  7496. */
  7497. Matrix.prototype.addToRef = function (other, result) {
  7498. for (var index = 0; index < 16; index++) {
  7499. result.m[index] = this.m[index] + other.m[index];
  7500. }
  7501. result._markAsUpdated();
  7502. return this;
  7503. };
  7504. /**
  7505. * Adds in place the given matrix to the current matrix
  7506. * @param other defines the second operand
  7507. * @returns the current updated matrix
  7508. */
  7509. Matrix.prototype.addToSelf = function (other) {
  7510. for (var index = 0; index < 16; index++) {
  7511. this.m[index] += other.m[index];
  7512. }
  7513. this._markAsUpdated();
  7514. return this;
  7515. };
  7516. /**
  7517. * Sets the given matrix to the current inverted Matrix
  7518. * @param other defines the target matrix
  7519. * @returns the unmodified current matrix
  7520. */
  7521. Matrix.prototype.invertToRef = function (other) {
  7522. var l1 = this.m[0];
  7523. var l2 = this.m[1];
  7524. var l3 = this.m[2];
  7525. var l4 = this.m[3];
  7526. var l5 = this.m[4];
  7527. var l6 = this.m[5];
  7528. var l7 = this.m[6];
  7529. var l8 = this.m[7];
  7530. var l9 = this.m[8];
  7531. var l10 = this.m[9];
  7532. var l11 = this.m[10];
  7533. var l12 = this.m[11];
  7534. var l13 = this.m[12];
  7535. var l14 = this.m[13];
  7536. var l15 = this.m[14];
  7537. var l16 = this.m[15];
  7538. var l17 = (l11 * l16) - (l12 * l15);
  7539. var l18 = (l10 * l16) - (l12 * l14);
  7540. var l19 = (l10 * l15) - (l11 * l14);
  7541. var l20 = (l9 * l16) - (l12 * l13);
  7542. var l21 = (l9 * l15) - (l11 * l13);
  7543. var l22 = (l9 * l14) - (l10 * l13);
  7544. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  7545. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  7546. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  7547. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  7548. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  7549. var l28 = (l7 * l16) - (l8 * l15);
  7550. var l29 = (l6 * l16) - (l8 * l14);
  7551. var l30 = (l6 * l15) - (l7 * l14);
  7552. var l31 = (l5 * l16) - (l8 * l13);
  7553. var l32 = (l5 * l15) - (l7 * l13);
  7554. var l33 = (l5 * l14) - (l6 * l13);
  7555. var l34 = (l7 * l12) - (l8 * l11);
  7556. var l35 = (l6 * l12) - (l8 * l10);
  7557. var l36 = (l6 * l11) - (l7 * l10);
  7558. var l37 = (l5 * l12) - (l8 * l9);
  7559. var l38 = (l5 * l11) - (l7 * l9);
  7560. var l39 = (l5 * l10) - (l6 * l9);
  7561. other.m[0] = l23 * l27;
  7562. other.m[4] = l24 * l27;
  7563. other.m[8] = l25 * l27;
  7564. other.m[12] = l26 * l27;
  7565. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  7566. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  7567. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  7568. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  7569. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  7570. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  7571. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  7572. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  7573. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  7574. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  7575. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  7576. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  7577. other._markAsUpdated();
  7578. return this;
  7579. };
  7580. /**
  7581. * Inserts the translation vector (using 3 floats) in the current matrix
  7582. * @param x defines the 1st component of the translation
  7583. * @param y defines the 2nd component of the translation
  7584. * @param z defines the 3rd component of the translation
  7585. * @returns the current updated matrix
  7586. */
  7587. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7588. this.m[12] = x;
  7589. this.m[13] = y;
  7590. this.m[14] = z;
  7591. this._markAsUpdated();
  7592. return this;
  7593. };
  7594. /**
  7595. * Inserts the translation vector in the current matrix
  7596. * @param vector3 defines the translation to insert
  7597. * @returns the current updated matrix
  7598. */
  7599. Matrix.prototype.setTranslation = function (vector3) {
  7600. this.m[12] = vector3.x;
  7601. this.m[13] = vector3.y;
  7602. this.m[14] = vector3.z;
  7603. this._markAsUpdated();
  7604. return this;
  7605. };
  7606. /**
  7607. * Gets the translation value of the current matrix
  7608. * @returns a new Vector3 as the extracted translation from the matrix
  7609. */
  7610. Matrix.prototype.getTranslation = function () {
  7611. return new Vector3(this.m[12], this.m[13], this.m[14]);
  7612. };
  7613. /**
  7614. * Fill a Vector3 with the extracted translation from the matrix
  7615. * @param result defines the Vector3 where to store the translation
  7616. * @returns the current matrix
  7617. */
  7618. Matrix.prototype.getTranslationToRef = function (result) {
  7619. result.x = this.m[12];
  7620. result.y = this.m[13];
  7621. result.z = this.m[14];
  7622. return this;
  7623. };
  7624. /**
  7625. * Remove rotation and scaling part from the matrix
  7626. * @returns the updated matrix
  7627. */
  7628. Matrix.prototype.removeRotationAndScaling = function () {
  7629. this.setRowFromFloats(0, 1, 0, 0, 0);
  7630. this.setRowFromFloats(1, 0, 1, 0, 0);
  7631. this.setRowFromFloats(2, 0, 0, 1, 0);
  7632. return this;
  7633. };
  7634. /**
  7635. * Multiply two matrices
  7636. * @param other defines the second operand
  7637. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7638. */
  7639. Matrix.prototype.multiply = function (other) {
  7640. var result = new Matrix();
  7641. this.multiplyToRef(other, result);
  7642. return result;
  7643. };
  7644. /**
  7645. * Copy the current matrix from the given one
  7646. * @param other defines the source matrix
  7647. * @returns the current updated matrix
  7648. */
  7649. Matrix.prototype.copyFrom = function (other) {
  7650. for (var index = 0; index < 16; index++) {
  7651. this.m[index] = other.m[index];
  7652. }
  7653. this._markAsUpdated();
  7654. return this;
  7655. };
  7656. /**
  7657. * Populates the given array from the starting index with the current matrix values
  7658. * @param array defines the target array
  7659. * @param offset defines the offset in the target array where to start storing values
  7660. * @returns the current matrix
  7661. */
  7662. Matrix.prototype.copyToArray = function (array, offset) {
  7663. if (offset === void 0) { offset = 0; }
  7664. for (var index = 0; index < 16; index++) {
  7665. array[offset + index] = this.m[index];
  7666. }
  7667. return this;
  7668. };
  7669. /**
  7670. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7671. * @param other defines the second operand
  7672. * @param result defines the matrix where to store the multiplication
  7673. * @returns the current matrix
  7674. */
  7675. Matrix.prototype.multiplyToRef = function (other, result) {
  7676. this.multiplyToArray(other, result.m, 0);
  7677. result._markAsUpdated();
  7678. return this;
  7679. };
  7680. /**
  7681. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7682. * @param other defines the second operand
  7683. * @param result defines the array where to store the multiplication
  7684. * @param offset defines the offset in the target array where to start storing values
  7685. * @returns the current matrix
  7686. */
  7687. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7688. var tm0 = this.m[0];
  7689. var tm1 = this.m[1];
  7690. var tm2 = this.m[2];
  7691. var tm3 = this.m[3];
  7692. var tm4 = this.m[4];
  7693. var tm5 = this.m[5];
  7694. var tm6 = this.m[6];
  7695. var tm7 = this.m[7];
  7696. var tm8 = this.m[8];
  7697. var tm9 = this.m[9];
  7698. var tm10 = this.m[10];
  7699. var tm11 = this.m[11];
  7700. var tm12 = this.m[12];
  7701. var tm13 = this.m[13];
  7702. var tm14 = this.m[14];
  7703. var tm15 = this.m[15];
  7704. var om0 = other.m[0];
  7705. var om1 = other.m[1];
  7706. var om2 = other.m[2];
  7707. var om3 = other.m[3];
  7708. var om4 = other.m[4];
  7709. var om5 = other.m[5];
  7710. var om6 = other.m[6];
  7711. var om7 = other.m[7];
  7712. var om8 = other.m[8];
  7713. var om9 = other.m[9];
  7714. var om10 = other.m[10];
  7715. var om11 = other.m[11];
  7716. var om12 = other.m[12];
  7717. var om13 = other.m[13];
  7718. var om14 = other.m[14];
  7719. var om15 = other.m[15];
  7720. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7721. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7722. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7723. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7724. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7725. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7726. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7727. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7728. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7729. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7730. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7731. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7732. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7733. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7734. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7735. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7736. return this;
  7737. };
  7738. /**
  7739. * Check equality between this matrix and a second one
  7740. * @param value defines the second matrix to compare
  7741. * @returns true is the current matrix and the given one values are strictly equal
  7742. */
  7743. Matrix.prototype.equals = function (value) {
  7744. return value &&
  7745. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  7746. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  7747. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  7748. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  7749. };
  7750. /**
  7751. * Clone the current matrix
  7752. * @returns a new matrix from the current matrix
  7753. */
  7754. Matrix.prototype.clone = function () {
  7755. 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]);
  7756. };
  7757. /**
  7758. * Returns the name of the current matrix class
  7759. * @returns the string "Matrix"
  7760. */
  7761. Matrix.prototype.getClassName = function () {
  7762. return "Matrix";
  7763. };
  7764. /**
  7765. * Gets the hash code of the current matrix
  7766. * @returns the hash code
  7767. */
  7768. Matrix.prototype.getHashCode = function () {
  7769. var hash = this.m[0] || 0;
  7770. for (var i = 1; i < 16; i++) {
  7771. hash = (hash * 397) ^ (this.m[i] || 0);
  7772. }
  7773. return hash;
  7774. };
  7775. /**
  7776. * Decomposes the current Matrix into a translation, rotation and scaling components
  7777. * @param scale defines the scale vector3 given as a reference to update
  7778. * @param rotation defines the rotation quaternion given as a reference to update
  7779. * @param translation defines the translation vector3 given as a reference to update
  7780. * @returns true if operation was successful
  7781. */
  7782. Matrix.prototype.decompose = function (scale, rotation, translation) {
  7783. if (translation) {
  7784. translation.x = this.m[12];
  7785. translation.y = this.m[13];
  7786. translation.z = this.m[14];
  7787. }
  7788. scale = scale || MathTmp.Vector3[0];
  7789. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  7790. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  7791. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  7792. if (this.determinant() <= 0) {
  7793. scale.y *= -1;
  7794. }
  7795. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  7796. if (rotation) {
  7797. rotation.x = 0;
  7798. rotation.y = 0;
  7799. rotation.z = 0;
  7800. rotation.w = 1;
  7801. }
  7802. return false;
  7803. }
  7804. if (rotation) {
  7805. 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]);
  7806. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  7807. }
  7808. return true;
  7809. };
  7810. /**
  7811. * Gets specific row of the matrix
  7812. * @param index defines the number of the row to get
  7813. * @returns the index-th row of the current matrix as a new Vector4
  7814. */
  7815. Matrix.prototype.getRow = function (index) {
  7816. if (index < 0 || index > 3) {
  7817. return null;
  7818. }
  7819. var i = index * 4;
  7820. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  7821. };
  7822. /**
  7823. * Sets the index-th row of the current matrix to the vector4 values
  7824. * @param index defines the number of the row to set
  7825. * @param row defines the target vector4
  7826. * @returns the updated current matrix
  7827. */
  7828. Matrix.prototype.setRow = function (index, row) {
  7829. if (index < 0 || index > 3) {
  7830. return this;
  7831. }
  7832. var i = index * 4;
  7833. this.m[i + 0] = row.x;
  7834. this.m[i + 1] = row.y;
  7835. this.m[i + 2] = row.z;
  7836. this.m[i + 3] = row.w;
  7837. this._markAsUpdated();
  7838. return this;
  7839. };
  7840. /**
  7841. * Compute the transpose of the matrix
  7842. * @returns the new transposed matrix
  7843. */
  7844. Matrix.prototype.transpose = function () {
  7845. return Matrix.Transpose(this);
  7846. };
  7847. /**
  7848. * Compute the transpose of the matrix and store it in a given matrix
  7849. * @param result defines the target matrix
  7850. * @returns the current matrix
  7851. */
  7852. Matrix.prototype.transposeToRef = function (result) {
  7853. Matrix.TransposeToRef(this, result);
  7854. return this;
  7855. };
  7856. /**
  7857. * Sets the index-th row of the current matrix with the given 4 x float values
  7858. * @param index defines the row index
  7859. * @param x defines the x component to set
  7860. * @param y defines the y component to set
  7861. * @param z defines the z component to set
  7862. * @param w defines the w component to set
  7863. * @returns the updated current matrix
  7864. */
  7865. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  7866. if (index < 0 || index > 3) {
  7867. return this;
  7868. }
  7869. var i = index * 4;
  7870. this.m[i + 0] = x;
  7871. this.m[i + 1] = y;
  7872. this.m[i + 2] = z;
  7873. this.m[i + 3] = w;
  7874. this._markAsUpdated();
  7875. return this;
  7876. };
  7877. /**
  7878. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  7879. * @param scale defines the scale factor
  7880. * @returns a new matrix
  7881. */
  7882. Matrix.prototype.scale = function (scale) {
  7883. var result = new Matrix();
  7884. this.scaleToRef(scale, result);
  7885. return result;
  7886. };
  7887. /**
  7888. * Scale the current matrix values by a factor to a given result matrix
  7889. * @param scale defines the scale factor
  7890. * @param result defines the matrix to store the result
  7891. * @returns the current matrix
  7892. */
  7893. Matrix.prototype.scaleToRef = function (scale, result) {
  7894. for (var index = 0; index < 16; index++) {
  7895. result.m[index] = this.m[index] * scale;
  7896. }
  7897. result._markAsUpdated();
  7898. return this;
  7899. };
  7900. /**
  7901. * Scale the current matrix values by a factor and add the result to a given matrix
  7902. * @param scale defines the scale factor
  7903. * @param result defines the Matrix to store the result
  7904. * @returns the current matrix
  7905. */
  7906. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  7907. for (var index = 0; index < 16; index++) {
  7908. result.m[index] += this.m[index] * scale;
  7909. }
  7910. result._markAsUpdated();
  7911. return this;
  7912. };
  7913. /**
  7914. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  7915. * @param ref matrix to store the result
  7916. */
  7917. Matrix.prototype.toNormalMatrix = function (ref) {
  7918. this.invertToRef(ref);
  7919. ref.transpose();
  7920. var m = ref.m;
  7921. 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);
  7922. };
  7923. /**
  7924. * Gets only rotation part of the current matrix
  7925. * @returns a new matrix sets to the extracted rotation matrix from the current one
  7926. */
  7927. Matrix.prototype.getRotationMatrix = function () {
  7928. var result = Matrix.Identity();
  7929. this.getRotationMatrixToRef(result);
  7930. return result;
  7931. };
  7932. /**
  7933. * Extracts the rotation matrix from the current one and sets it as the given "result"
  7934. * @param result defines the target matrix to store data to
  7935. * @returns the current matrix
  7936. */
  7937. Matrix.prototype.getRotationMatrixToRef = function (result) {
  7938. var m = this.m;
  7939. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  7940. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  7941. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  7942. if (this.determinant() <= 0) {
  7943. sy *= -1;
  7944. }
  7945. if (sx === 0 || sy === 0 || sz === 0) {
  7946. Matrix.IdentityToRef(result);
  7947. }
  7948. else {
  7949. 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);
  7950. }
  7951. return this;
  7952. };
  7953. // Statics
  7954. /**
  7955. * Creates a matrix from an array
  7956. * @param array defines the source array
  7957. * @param offset defines an offset in the source array
  7958. * @returns a new Matrix set from the starting index of the given array
  7959. */
  7960. Matrix.FromArray = function (array, offset) {
  7961. var result = new Matrix();
  7962. if (!offset) {
  7963. offset = 0;
  7964. }
  7965. Matrix.FromArrayToRef(array, offset, result);
  7966. return result;
  7967. };
  7968. /**
  7969. * Copy the content of an array into a given matrix
  7970. * @param array defines the source array
  7971. * @param offset defines an offset in the source array
  7972. * @param result defines the target matrix
  7973. */
  7974. Matrix.FromArrayToRef = function (array, offset, result) {
  7975. for (var index = 0; index < 16; index++) {
  7976. result.m[index] = array[index + offset];
  7977. }
  7978. result._markAsUpdated();
  7979. };
  7980. /**
  7981. * Stores an array into a matrix after having multiplied each component by a given factor
  7982. * @param array defines the source array
  7983. * @param offset defines the offset in the source array
  7984. * @param scale defines the scaling factor
  7985. * @param result defines the target matrix
  7986. */
  7987. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  7988. for (var index = 0; index < 16; index++) {
  7989. result.m[index] = array[index + offset] * scale;
  7990. }
  7991. result._markAsUpdated();
  7992. };
  7993. /**
  7994. * Stores a list of values (16) inside a given matrix
  7995. * @param initialM11 defines 1st value of 1st row
  7996. * @param initialM12 defines 2nd value of 1st row
  7997. * @param initialM13 defines 3rd value of 1st row
  7998. * @param initialM14 defines 4th value of 1st row
  7999. * @param initialM21 defines 1st value of 2nd row
  8000. * @param initialM22 defines 2nd value of 2nd row
  8001. * @param initialM23 defines 3rd value of 2nd row
  8002. * @param initialM24 defines 4th value of 2nd row
  8003. * @param initialM31 defines 1st value of 3rd row
  8004. * @param initialM32 defines 2nd value of 3rd row
  8005. * @param initialM33 defines 3rd value of 3rd row
  8006. * @param initialM34 defines 4th value of 3rd row
  8007. * @param initialM41 defines 1st value of 4th row
  8008. * @param initialM42 defines 2nd value of 4th row
  8009. * @param initialM43 defines 3rd value of 4th row
  8010. * @param initialM44 defines 4th value of 4th row
  8011. * @param result defines the target matrix
  8012. */
  8013. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8014. result.m[0] = initialM11;
  8015. result.m[1] = initialM12;
  8016. result.m[2] = initialM13;
  8017. result.m[3] = initialM14;
  8018. result.m[4] = initialM21;
  8019. result.m[5] = initialM22;
  8020. result.m[6] = initialM23;
  8021. result.m[7] = initialM24;
  8022. result.m[8] = initialM31;
  8023. result.m[9] = initialM32;
  8024. result.m[10] = initialM33;
  8025. result.m[11] = initialM34;
  8026. result.m[12] = initialM41;
  8027. result.m[13] = initialM42;
  8028. result.m[14] = initialM43;
  8029. result.m[15] = initialM44;
  8030. result._markAsUpdated();
  8031. };
  8032. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8033. /**
  8034. * Gets an identity matrix that must not be updated
  8035. */
  8036. get: function () {
  8037. return Matrix._identityReadOnly;
  8038. },
  8039. enumerable: true,
  8040. configurable: true
  8041. });
  8042. /**
  8043. * Creates new matrix from a list of values (16)
  8044. * @param initialM11 defines 1st value of 1st row
  8045. * @param initialM12 defines 2nd value of 1st row
  8046. * @param initialM13 defines 3rd value of 1st row
  8047. * @param initialM14 defines 4th value of 1st row
  8048. * @param initialM21 defines 1st value of 2nd row
  8049. * @param initialM22 defines 2nd value of 2nd row
  8050. * @param initialM23 defines 3rd value of 2nd row
  8051. * @param initialM24 defines 4th value of 2nd row
  8052. * @param initialM31 defines 1st value of 3rd row
  8053. * @param initialM32 defines 2nd value of 3rd row
  8054. * @param initialM33 defines 3rd value of 3rd row
  8055. * @param initialM34 defines 4th value of 3rd row
  8056. * @param initialM41 defines 1st value of 4th row
  8057. * @param initialM42 defines 2nd value of 4th row
  8058. * @param initialM43 defines 3rd value of 4th row
  8059. * @param initialM44 defines 4th value of 4th row
  8060. * @returns the new matrix
  8061. */
  8062. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8063. var result = new Matrix();
  8064. result.m[0] = initialM11;
  8065. result.m[1] = initialM12;
  8066. result.m[2] = initialM13;
  8067. result.m[3] = initialM14;
  8068. result.m[4] = initialM21;
  8069. result.m[5] = initialM22;
  8070. result.m[6] = initialM23;
  8071. result.m[7] = initialM24;
  8072. result.m[8] = initialM31;
  8073. result.m[9] = initialM32;
  8074. result.m[10] = initialM33;
  8075. result.m[11] = initialM34;
  8076. result.m[12] = initialM41;
  8077. result.m[13] = initialM42;
  8078. result.m[14] = initialM43;
  8079. result.m[15] = initialM44;
  8080. return result;
  8081. };
  8082. /**
  8083. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8084. * @param scale defines the scale vector3
  8085. * @param rotation defines the rotation quaternion
  8086. * @param translation defines the translation vector3
  8087. * @returns a new matrix
  8088. */
  8089. Matrix.Compose = function (scale, rotation, translation) {
  8090. var result = Matrix.Identity();
  8091. Matrix.ComposeToRef(scale, rotation, translation, result);
  8092. return result;
  8093. };
  8094. /**
  8095. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8096. * @param scale defines the scale vector3
  8097. * @param rotation defines the rotation quaternion
  8098. * @param translation defines the translation vector3
  8099. * @param result defines the target matrix
  8100. */
  8101. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8102. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  8103. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8104. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8105. result.setTranslation(translation);
  8106. };
  8107. /**
  8108. * Creates a new identity matrix
  8109. * @returns a new identity matrix
  8110. */
  8111. Matrix.Identity = function () {
  8112. 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);
  8113. };
  8114. /**
  8115. * Creates a new identity matrix and stores the result in a given matrix
  8116. * @param result defines the target matrix
  8117. */
  8118. Matrix.IdentityToRef = function (result) {
  8119. 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);
  8120. };
  8121. /**
  8122. * Creates a new zero matrix
  8123. * @returns a new zero matrix
  8124. */
  8125. Matrix.Zero = function () {
  8126. 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);
  8127. };
  8128. /**
  8129. * Creates a new rotation matrix for "angle" radians around the X axis
  8130. * @param angle defines the angle (in radians) to use
  8131. * @return the new matrix
  8132. */
  8133. Matrix.RotationX = function (angle) {
  8134. var result = new Matrix();
  8135. Matrix.RotationXToRef(angle, result);
  8136. return result;
  8137. };
  8138. /**
  8139. * Creates a new matrix as the invert of a given matrix
  8140. * @param source defines the source matrix
  8141. * @returns the new matrix
  8142. */
  8143. Matrix.Invert = function (source) {
  8144. var result = new Matrix();
  8145. source.invertToRef(result);
  8146. return result;
  8147. };
  8148. /**
  8149. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8150. * @param angle defines the angle (in radians) to use
  8151. * @param result defines the target matrix
  8152. */
  8153. Matrix.RotationXToRef = function (angle, result) {
  8154. var s = Math.sin(angle);
  8155. var c = Math.cos(angle);
  8156. result.m[0] = 1.0;
  8157. result.m[15] = 1.0;
  8158. result.m[5] = c;
  8159. result.m[10] = c;
  8160. result.m[9] = -s;
  8161. result.m[6] = s;
  8162. result.m[1] = 0.0;
  8163. result.m[2] = 0.0;
  8164. result.m[3] = 0.0;
  8165. result.m[4] = 0.0;
  8166. result.m[7] = 0.0;
  8167. result.m[8] = 0.0;
  8168. result.m[11] = 0.0;
  8169. result.m[12] = 0.0;
  8170. result.m[13] = 0.0;
  8171. result.m[14] = 0.0;
  8172. result._markAsUpdated();
  8173. };
  8174. /**
  8175. * Creates a new rotation matrix for "angle" radians around the Y axis
  8176. * @param angle defines the angle (in radians) to use
  8177. * @return the new matrix
  8178. */
  8179. Matrix.RotationY = function (angle) {
  8180. var result = new Matrix();
  8181. Matrix.RotationYToRef(angle, result);
  8182. return result;
  8183. };
  8184. /**
  8185. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8186. * @param angle defines the angle (in radians) to use
  8187. * @param result defines the target matrix
  8188. */
  8189. Matrix.RotationYToRef = function (angle, result) {
  8190. var s = Math.sin(angle);
  8191. var c = Math.cos(angle);
  8192. result.m[5] = 1.0;
  8193. result.m[15] = 1.0;
  8194. result.m[0] = c;
  8195. result.m[2] = -s;
  8196. result.m[8] = s;
  8197. result.m[10] = c;
  8198. result.m[1] = 0.0;
  8199. result.m[3] = 0.0;
  8200. result.m[4] = 0.0;
  8201. result.m[6] = 0.0;
  8202. result.m[7] = 0.0;
  8203. result.m[9] = 0.0;
  8204. result.m[11] = 0.0;
  8205. result.m[12] = 0.0;
  8206. result.m[13] = 0.0;
  8207. result.m[14] = 0.0;
  8208. result._markAsUpdated();
  8209. };
  8210. /**
  8211. * Creates a new rotation matrix for "angle" radians around the Z axis
  8212. * @param angle defines the angle (in radians) to use
  8213. * @return the new matrix
  8214. */
  8215. Matrix.RotationZ = function (angle) {
  8216. var result = new Matrix();
  8217. Matrix.RotationZToRef(angle, result);
  8218. return result;
  8219. };
  8220. /**
  8221. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8222. * @param angle defines the angle (in radians) to use
  8223. * @param result defines the target matrix
  8224. */
  8225. Matrix.RotationZToRef = function (angle, result) {
  8226. var s = Math.sin(angle);
  8227. var c = Math.cos(angle);
  8228. result.m[10] = 1.0;
  8229. result.m[15] = 1.0;
  8230. result.m[0] = c;
  8231. result.m[1] = s;
  8232. result.m[4] = -s;
  8233. result.m[5] = c;
  8234. result.m[2] = 0.0;
  8235. result.m[3] = 0.0;
  8236. result.m[6] = 0.0;
  8237. result.m[7] = 0.0;
  8238. result.m[8] = 0.0;
  8239. result.m[9] = 0.0;
  8240. result.m[11] = 0.0;
  8241. result.m[12] = 0.0;
  8242. result.m[13] = 0.0;
  8243. result.m[14] = 0.0;
  8244. result._markAsUpdated();
  8245. };
  8246. /**
  8247. * Creates a new rotation matrix for "angle" radians around the given axis
  8248. * @param axis defines the axis to use
  8249. * @param angle defines the angle (in radians) to use
  8250. * @return the new matrix
  8251. */
  8252. Matrix.RotationAxis = function (axis, angle) {
  8253. var result = Matrix.Zero();
  8254. Matrix.RotationAxisToRef(axis, angle, result);
  8255. return result;
  8256. };
  8257. /**
  8258. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8259. * @param axis defines the axis to use
  8260. * @param angle defines the angle (in radians) to use
  8261. * @param result defines the target matrix
  8262. */
  8263. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8264. var s = Math.sin(-angle);
  8265. var c = Math.cos(-angle);
  8266. var c1 = 1 - c;
  8267. axis.normalize();
  8268. result.m[0] = (axis.x * axis.x) * c1 + c;
  8269. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8270. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8271. result.m[3] = 0.0;
  8272. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8273. result.m[5] = (axis.y * axis.y) * c1 + c;
  8274. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8275. result.m[7] = 0.0;
  8276. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8277. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8278. result.m[10] = (axis.z * axis.z) * c1 + c;
  8279. result.m[11] = 0.0;
  8280. result.m[15] = 1.0;
  8281. result._markAsUpdated();
  8282. };
  8283. /**
  8284. * Creates a rotation matrix
  8285. * @param yaw defines the yaw angle in radians (Y axis)
  8286. * @param pitch defines the pitch angle in radians (X axis)
  8287. * @param roll defines the roll angle in radians (X axis)
  8288. * @returns the new rotation matrix
  8289. */
  8290. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8291. var result = new Matrix();
  8292. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8293. return result;
  8294. };
  8295. /**
  8296. * Creates a rotation matrix and stores it in a given matrix
  8297. * @param yaw defines the yaw angle in radians (Y axis)
  8298. * @param pitch defines the pitch angle in radians (X axis)
  8299. * @param roll defines the roll angle in radians (X axis)
  8300. * @param result defines the target matrix
  8301. */
  8302. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8303. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  8304. this._tempQuaternion.toRotationMatrix(result);
  8305. };
  8306. /**
  8307. * Creates a scaling matrix
  8308. * @param x defines the scale factor on X axis
  8309. * @param y defines the scale factor on Y axis
  8310. * @param z defines the scale factor on Z axis
  8311. * @returns the new matrix
  8312. */
  8313. Matrix.Scaling = function (x, y, z) {
  8314. var result = Matrix.Zero();
  8315. Matrix.ScalingToRef(x, y, z, result);
  8316. return result;
  8317. };
  8318. /**
  8319. * Creates a scaling matrix and stores it in a given matrix
  8320. * @param x defines the scale factor on X axis
  8321. * @param y defines the scale factor on Y axis
  8322. * @param z defines the scale factor on Z axis
  8323. * @param result defines the target matrix
  8324. */
  8325. Matrix.ScalingToRef = function (x, y, z, result) {
  8326. result.m[0] = x;
  8327. result.m[1] = 0.0;
  8328. result.m[2] = 0.0;
  8329. result.m[3] = 0.0;
  8330. result.m[4] = 0.0;
  8331. result.m[5] = y;
  8332. result.m[6] = 0.0;
  8333. result.m[7] = 0.0;
  8334. result.m[8] = 0.0;
  8335. result.m[9] = 0.0;
  8336. result.m[10] = z;
  8337. result.m[11] = 0.0;
  8338. result.m[12] = 0.0;
  8339. result.m[13] = 0.0;
  8340. result.m[14] = 0.0;
  8341. result.m[15] = 1.0;
  8342. result._markAsUpdated();
  8343. };
  8344. /**
  8345. * Creates a translation matrix
  8346. * @param x defines the translation on X axis
  8347. * @param y defines the translation on Y axis
  8348. * @param z defines the translationon Z axis
  8349. * @returns the new matrix
  8350. */
  8351. Matrix.Translation = function (x, y, z) {
  8352. var result = Matrix.Identity();
  8353. Matrix.TranslationToRef(x, y, z, result);
  8354. return result;
  8355. };
  8356. /**
  8357. * Creates a translation matrix and stores it in a given matrix
  8358. * @param x defines the translation on X axis
  8359. * @param y defines the translation on Y axis
  8360. * @param z defines the translationon Z axis
  8361. * @param result defines the target matrix
  8362. */
  8363. Matrix.TranslationToRef = function (x, y, z, result) {
  8364. 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);
  8365. };
  8366. /**
  8367. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8368. * @param startValue defines the start value
  8369. * @param endValue defines the end value
  8370. * @param gradient defines the gradient factor
  8371. * @returns the new matrix
  8372. */
  8373. Matrix.Lerp = function (startValue, endValue, gradient) {
  8374. var result = Matrix.Zero();
  8375. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8376. return result;
  8377. };
  8378. /**
  8379. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8380. * @param startValue defines the start value
  8381. * @param endValue defines the end value
  8382. * @param gradient defines the gradient factor
  8383. * @param result defines the Matrix object where to store data
  8384. */
  8385. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8386. for (var index = 0; index < 16; index++) {
  8387. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  8388. }
  8389. result._markAsUpdated();
  8390. };
  8391. /**
  8392. * Builds a new matrix whose values are computed by:
  8393. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8394. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8395. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8396. * @param startValue defines the first matrix
  8397. * @param endValue defines the second matrix
  8398. * @param gradient defines the gradient between the two matrices
  8399. * @returns the new matrix
  8400. */
  8401. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8402. var result = Matrix.Zero();
  8403. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8404. return result;
  8405. };
  8406. /**
  8407. * Update a matrix to values which are computed by:
  8408. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8409. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8410. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8411. * @param startValue defines the first matrix
  8412. * @param endValue defines the second matrix
  8413. * @param gradient defines the gradient between the two matrices
  8414. * @param result defines the target matrix
  8415. */
  8416. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8417. var startScale = MathTmp.Vector3[0];
  8418. var startRotation = MathTmp.Quaternion[0];
  8419. var startTranslation = MathTmp.Vector3[1];
  8420. startValue.decompose(startScale, startRotation, startTranslation);
  8421. var endScale = MathTmp.Vector3[2];
  8422. var endRotation = MathTmp.Quaternion[1];
  8423. var endTranslation = MathTmp.Vector3[3];
  8424. endValue.decompose(endScale, endRotation, endTranslation);
  8425. var resultScale = MathTmp.Vector3[4];
  8426. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8427. var resultRotation = MathTmp.Quaternion[2];
  8428. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8429. var resultTranslation = MathTmp.Vector3[5];
  8430. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8431. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8432. };
  8433. /**
  8434. * 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"
  8435. * This function works in left handed mode
  8436. * @param eye defines the final position of the entity
  8437. * @param target defines where the entity should look at
  8438. * @param up defines the up vector for the entity
  8439. * @returns the new matrix
  8440. */
  8441. Matrix.LookAtLH = function (eye, target, up) {
  8442. var result = Matrix.Zero();
  8443. Matrix.LookAtLHToRef(eye, target, up, result);
  8444. return result;
  8445. };
  8446. /**
  8447. * 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".
  8448. * This function works in left handed mode
  8449. * @param eye defines the final position of the entity
  8450. * @param target defines where the entity should look at
  8451. * @param up defines the up vector for the entity
  8452. * @param result defines the target matrix
  8453. */
  8454. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8455. // Z axis
  8456. target.subtractToRef(eye, this._zAxis);
  8457. this._zAxis.normalize();
  8458. // X axis
  8459. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  8460. if (this._xAxis.lengthSquared() === 0) {
  8461. this._xAxis.x = 1.0;
  8462. }
  8463. else {
  8464. this._xAxis.normalize();
  8465. }
  8466. // Y axis
  8467. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  8468. this._yAxis.normalize();
  8469. // Eye angles
  8470. var ex = -Vector3.Dot(this._xAxis, eye);
  8471. var ey = -Vector3.Dot(this._yAxis, eye);
  8472. var ez = -Vector3.Dot(this._zAxis, eye);
  8473. 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);
  8474. };
  8475. /**
  8476. * 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"
  8477. * This function works in right handed mode
  8478. * @param eye defines the final position of the entity
  8479. * @param target defines where the entity should look at
  8480. * @param up defines the up vector for the entity
  8481. * @returns the new matrix
  8482. */
  8483. Matrix.LookAtRH = function (eye, target, up) {
  8484. var result = Matrix.Zero();
  8485. Matrix.LookAtRHToRef(eye, target, up, result);
  8486. return result;
  8487. };
  8488. /**
  8489. * 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".
  8490. * This function works in right handed mode
  8491. * @param eye defines the final position of the entity
  8492. * @param target defines where the entity should look at
  8493. * @param up defines the up vector for the entity
  8494. * @param result defines the target matrix
  8495. */
  8496. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8497. // Z axis
  8498. eye.subtractToRef(target, this._zAxis);
  8499. this._zAxis.normalize();
  8500. // X axis
  8501. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  8502. if (this._xAxis.lengthSquared() === 0) {
  8503. this._xAxis.x = 1.0;
  8504. }
  8505. else {
  8506. this._xAxis.normalize();
  8507. }
  8508. // Y axis
  8509. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  8510. this._yAxis.normalize();
  8511. // Eye angles
  8512. var ex = -Vector3.Dot(this._xAxis, eye);
  8513. var ey = -Vector3.Dot(this._yAxis, eye);
  8514. var ez = -Vector3.Dot(this._zAxis, eye);
  8515. 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);
  8516. };
  8517. /**
  8518. * Create a left-handed orthographic projection matrix
  8519. * @param width defines the viewport width
  8520. * @param height defines the viewport height
  8521. * @param znear defines the near clip plane
  8522. * @param zfar defines the far clip plane
  8523. * @returns a new matrix as a left-handed orthographic projection matrix
  8524. */
  8525. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8526. var matrix = Matrix.Zero();
  8527. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8528. return matrix;
  8529. };
  8530. /**
  8531. * Store a left-handed orthographic projection to a given matrix
  8532. * @param width defines the viewport width
  8533. * @param height defines the viewport height
  8534. * @param znear defines the near clip plane
  8535. * @param zfar defines the far clip plane
  8536. * @param result defines the target matrix
  8537. */
  8538. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8539. var n = znear;
  8540. var f = zfar;
  8541. var a = 2.0 / width;
  8542. var b = 2.0 / height;
  8543. var c = 2.0 / (f - n);
  8544. var d = -(f + n) / (f - n);
  8545. 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);
  8546. };
  8547. /**
  8548. * Create a left-handed orthographic projection matrix
  8549. * @param left defines the viewport left coordinate
  8550. * @param right defines the viewport right coordinate
  8551. * @param bottom defines the viewport bottom coordinate
  8552. * @param top defines the viewport top coordinate
  8553. * @param znear defines the near clip plane
  8554. * @param zfar defines the far clip plane
  8555. * @returns a new matrix as a left-handed orthographic projection matrix
  8556. */
  8557. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8558. var matrix = Matrix.Zero();
  8559. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8560. return matrix;
  8561. };
  8562. /**
  8563. * Stores a left-handed orthographic projection into a given matrix
  8564. * @param left defines the viewport left coordinate
  8565. * @param right defines the viewport right coordinate
  8566. * @param bottom defines the viewport bottom coordinate
  8567. * @param top defines the viewport top coordinate
  8568. * @param znear defines the near clip plane
  8569. * @param zfar defines the far clip plane
  8570. * @param result defines the target matrix
  8571. */
  8572. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8573. var n = znear;
  8574. var f = zfar;
  8575. var a = 2.0 / (right - left);
  8576. var b = 2.0 / (top - bottom);
  8577. var c = 2.0 / (f - n);
  8578. var d = -(f + n) / (f - n);
  8579. var i0 = (left + right) / (left - right);
  8580. var i1 = (top + bottom) / (bottom - top);
  8581. 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);
  8582. };
  8583. /**
  8584. * Creates a right-handed orthographic projection matrix
  8585. * @param left defines the viewport left coordinate
  8586. * @param right defines the viewport right coordinate
  8587. * @param bottom defines the viewport bottom coordinate
  8588. * @param top defines the viewport top coordinate
  8589. * @param znear defines the near clip plane
  8590. * @param zfar defines the far clip plane
  8591. * @returns a new matrix as a right-handed orthographic projection matrix
  8592. */
  8593. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8594. var matrix = Matrix.Zero();
  8595. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8596. return matrix;
  8597. };
  8598. /**
  8599. * Stores a right-handed orthographic projection into a given matrix
  8600. * @param left defines the viewport left coordinate
  8601. * @param right defines the viewport right coordinate
  8602. * @param bottom defines the viewport bottom coordinate
  8603. * @param top defines the viewport top coordinate
  8604. * @param znear defines the near clip plane
  8605. * @param zfar defines the far clip plane
  8606. * @param result defines the target matrix
  8607. */
  8608. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8609. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8610. result.m[10] *= -1.0;
  8611. };
  8612. /**
  8613. * Creates a left-handed perspective projection matrix
  8614. * @param width defines the viewport width
  8615. * @param height defines the viewport height
  8616. * @param znear defines the near clip plane
  8617. * @param zfar defines the far clip plane
  8618. * @returns a new matrix as a left-handed perspective projection matrix
  8619. */
  8620. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8621. var matrix = Matrix.Zero();
  8622. var n = znear;
  8623. var f = zfar;
  8624. var a = 2.0 * n / width;
  8625. var b = 2.0 * n / height;
  8626. var c = (f + n) / (f - n);
  8627. var d = -2.0 * f * n / (f - n);
  8628. 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);
  8629. return matrix;
  8630. };
  8631. /**
  8632. * Creates a left-handed perspective projection matrix
  8633. * @param fov defines the horizontal field of view
  8634. * @param aspect defines the aspect ratio
  8635. * @param znear defines the near clip plane
  8636. * @param zfar defines the far clip plane
  8637. * @returns a new matrix as a left-handed perspective projection matrix
  8638. */
  8639. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8640. var matrix = Matrix.Zero();
  8641. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8642. return matrix;
  8643. };
  8644. /**
  8645. * Stores a left-handed perspective projection into a given matrix
  8646. * @param fov defines the horizontal field of view
  8647. * @param aspect defines the aspect ratio
  8648. * @param znear defines the near clip plane
  8649. * @param zfar defines the far clip plane
  8650. * @param result defines the target matrix
  8651. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8652. */
  8653. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8654. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8655. var n = znear;
  8656. var f = zfar;
  8657. var t = 1.0 / (Math.tan(fov * 0.5));
  8658. var a = isVerticalFovFixed ? (t / aspect) : t;
  8659. var b = isVerticalFovFixed ? t : (t * aspect);
  8660. var c = (f + n) / (f - n);
  8661. var d = -2.0 * f * n / (f - n);
  8662. 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);
  8663. };
  8664. /**
  8665. * Creates a right-handed perspective projection matrix
  8666. * @param fov defines the horizontal field of view
  8667. * @param aspect defines the aspect ratio
  8668. * @param znear defines the near clip plane
  8669. * @param zfar defines the far clip plane
  8670. * @returns a new matrix as a right-handed perspective projection matrix
  8671. */
  8672. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8673. var matrix = Matrix.Zero();
  8674. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8675. return matrix;
  8676. };
  8677. /**
  8678. * Stores a right-handed perspective projection into a given matrix
  8679. * @param fov defines the horizontal field of view
  8680. * @param aspect defines the aspect ratio
  8681. * @param znear defines the near clip plane
  8682. * @param zfar defines the far clip plane
  8683. * @param result defines the target matrix
  8684. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8685. */
  8686. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8687. //alternatively this could be expressed as:
  8688. // m = PerspectiveFovLHToRef
  8689. // m[10] *= -1.0;
  8690. // m[11] *= -1.0;
  8691. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8692. var n = znear;
  8693. var f = zfar;
  8694. var t = 1.0 / (Math.tan(fov * 0.5));
  8695. var a = isVerticalFovFixed ? (t / aspect) : t;
  8696. var b = isVerticalFovFixed ? t : (t * aspect);
  8697. var c = -(f + n) / (f - n);
  8698. var d = -2 * f * n / (f - n);
  8699. 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);
  8700. };
  8701. /**
  8702. * Stores a perspective projection for WebVR info a given matrix
  8703. * @param fov defines the field of view
  8704. * @param znear defines the near clip plane
  8705. * @param zfar defines the far clip plane
  8706. * @param result defines the target matrix
  8707. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8708. */
  8709. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8710. if (rightHanded === void 0) { rightHanded = false; }
  8711. var rightHandedFactor = rightHanded ? -1 : 1;
  8712. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8713. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8714. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8715. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8716. var xScale = 2.0 / (leftTan + rightTan);
  8717. var yScale = 2.0 / (upTan + downTan);
  8718. result.m[0] = xScale;
  8719. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  8720. result.m[5] = yScale;
  8721. result.m[6] = result.m[7] = 0.0;
  8722. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8723. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  8724. result.m[10] = -zfar / (znear - zfar);
  8725. result.m[11] = 1.0 * rightHandedFactor;
  8726. result.m[12] = result.m[13] = result.m[15] = 0.0;
  8727. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8728. result._markAsUpdated();
  8729. };
  8730. /**
  8731. * Computes a complete transformation matrix
  8732. * @param viewport defines the viewport to use
  8733. * @param world defines the world matrix
  8734. * @param view defines the view matrix
  8735. * @param projection defines the projection matrix
  8736. * @param zmin defines the near clip plane
  8737. * @param zmax defines the far clip plane
  8738. * @returns the transformation matrix
  8739. */
  8740. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  8741. var cw = viewport.width;
  8742. var ch = viewport.height;
  8743. var cx = viewport.x;
  8744. var cy = viewport.y;
  8745. 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);
  8746. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  8747. };
  8748. /**
  8749. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  8750. * @param matrix defines the matrix to use
  8751. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  8752. */
  8753. Matrix.GetAsMatrix2x2 = function (matrix) {
  8754. return new Float32Array([
  8755. matrix.m[0], matrix.m[1],
  8756. matrix.m[4], matrix.m[5]
  8757. ]);
  8758. };
  8759. /**
  8760. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  8761. * @param matrix defines the matrix to use
  8762. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  8763. */
  8764. Matrix.GetAsMatrix3x3 = function (matrix) {
  8765. return new Float32Array([
  8766. matrix.m[0], matrix.m[1], matrix.m[2],
  8767. matrix.m[4], matrix.m[5], matrix.m[6],
  8768. matrix.m[8], matrix.m[9], matrix.m[10]
  8769. ]);
  8770. };
  8771. /**
  8772. * Compute the transpose of a given matrix
  8773. * @param matrix defines the matrix to transpose
  8774. * @returns the new matrix
  8775. */
  8776. Matrix.Transpose = function (matrix) {
  8777. var result = new Matrix();
  8778. Matrix.TransposeToRef(matrix, result);
  8779. return result;
  8780. };
  8781. /**
  8782. * Compute the transpose of a matrix and store it in a target matrix
  8783. * @param matrix defines the matrix to transpose
  8784. * @param result defines the target matrix
  8785. */
  8786. Matrix.TransposeToRef = function (matrix, result) {
  8787. result.m[0] = matrix.m[0];
  8788. result.m[1] = matrix.m[4];
  8789. result.m[2] = matrix.m[8];
  8790. result.m[3] = matrix.m[12];
  8791. result.m[4] = matrix.m[1];
  8792. result.m[5] = matrix.m[5];
  8793. result.m[6] = matrix.m[9];
  8794. result.m[7] = matrix.m[13];
  8795. result.m[8] = matrix.m[2];
  8796. result.m[9] = matrix.m[6];
  8797. result.m[10] = matrix.m[10];
  8798. result.m[11] = matrix.m[14];
  8799. result.m[12] = matrix.m[3];
  8800. result.m[13] = matrix.m[7];
  8801. result.m[14] = matrix.m[11];
  8802. result.m[15] = matrix.m[15];
  8803. };
  8804. /**
  8805. * Computes a reflection matrix from a plane
  8806. * @param plane defines the reflection plane
  8807. * @returns a new matrix
  8808. */
  8809. Matrix.Reflection = function (plane) {
  8810. var matrix = new Matrix();
  8811. Matrix.ReflectionToRef(plane, matrix);
  8812. return matrix;
  8813. };
  8814. /**
  8815. * Computes a reflection matrix from a plane
  8816. * @param plane defines the reflection plane
  8817. * @param result defines the target matrix
  8818. */
  8819. Matrix.ReflectionToRef = function (plane, result) {
  8820. plane.normalize();
  8821. var x = plane.normal.x;
  8822. var y = plane.normal.y;
  8823. var z = plane.normal.z;
  8824. var temp = -2 * x;
  8825. var temp2 = -2 * y;
  8826. var temp3 = -2 * z;
  8827. result.m[0] = (temp * x) + 1;
  8828. result.m[1] = temp2 * x;
  8829. result.m[2] = temp3 * x;
  8830. result.m[3] = 0.0;
  8831. result.m[4] = temp * y;
  8832. result.m[5] = (temp2 * y) + 1;
  8833. result.m[6] = temp3 * y;
  8834. result.m[7] = 0.0;
  8835. result.m[8] = temp * z;
  8836. result.m[9] = temp2 * z;
  8837. result.m[10] = (temp3 * z) + 1;
  8838. result.m[11] = 0.0;
  8839. result.m[12] = temp * plane.d;
  8840. result.m[13] = temp2 * plane.d;
  8841. result.m[14] = temp3 * plane.d;
  8842. result.m[15] = 1.0;
  8843. result._markAsUpdated();
  8844. };
  8845. /**
  8846. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  8847. * @param xaxis defines the value of the 1st axis
  8848. * @param yaxis defines the value of the 2nd axis
  8849. * @param zaxis defines the value of the 3rd axis
  8850. * @param result defines the target matrix
  8851. */
  8852. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  8853. result.m[0] = xaxis.x;
  8854. result.m[1] = xaxis.y;
  8855. result.m[2] = xaxis.z;
  8856. result.m[3] = 0.0;
  8857. result.m[4] = yaxis.x;
  8858. result.m[5] = yaxis.y;
  8859. result.m[6] = yaxis.z;
  8860. result.m[7] = 0.0;
  8861. result.m[8] = zaxis.x;
  8862. result.m[9] = zaxis.y;
  8863. result.m[10] = zaxis.z;
  8864. result.m[11] = 0.0;
  8865. result.m[12] = 0.0;
  8866. result.m[13] = 0.0;
  8867. result.m[14] = 0.0;
  8868. result.m[15] = 1.0;
  8869. result._markAsUpdated();
  8870. };
  8871. /**
  8872. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  8873. * @param quat defines the quaternion to use
  8874. * @param result defines the target matrix
  8875. */
  8876. Matrix.FromQuaternionToRef = function (quat, result) {
  8877. var xx = quat.x * quat.x;
  8878. var yy = quat.y * quat.y;
  8879. var zz = quat.z * quat.z;
  8880. var xy = quat.x * quat.y;
  8881. var zw = quat.z * quat.w;
  8882. var zx = quat.z * quat.x;
  8883. var yw = quat.y * quat.w;
  8884. var yz = quat.y * quat.z;
  8885. var xw = quat.x * quat.w;
  8886. result.m[0] = 1.0 - (2.0 * (yy + zz));
  8887. result.m[1] = 2.0 * (xy + zw);
  8888. result.m[2] = 2.0 * (zx - yw);
  8889. result.m[3] = 0.0;
  8890. result.m[4] = 2.0 * (xy - zw);
  8891. result.m[5] = 1.0 - (2.0 * (zz + xx));
  8892. result.m[6] = 2.0 * (yz + xw);
  8893. result.m[7] = 0.0;
  8894. result.m[8] = 2.0 * (zx + yw);
  8895. result.m[9] = 2.0 * (yz - xw);
  8896. result.m[10] = 1.0 - (2.0 * (yy + xx));
  8897. result.m[11] = 0.0;
  8898. result.m[12] = 0.0;
  8899. result.m[13] = 0.0;
  8900. result.m[14] = 0.0;
  8901. result.m[15] = 1.0;
  8902. result._markAsUpdated();
  8903. };
  8904. Matrix._tempQuaternion = new Quaternion();
  8905. Matrix._xAxis = Vector3.Zero();
  8906. Matrix._yAxis = Vector3.Zero();
  8907. Matrix._zAxis = Vector3.Zero();
  8908. Matrix._updateFlagSeed = 0;
  8909. Matrix._identityReadOnly = Matrix.Identity();
  8910. return Matrix;
  8911. }());
  8912. BABYLON.Matrix = Matrix;
  8913. /**
  8914. * Represens a plane by the equation ax + by + cz + d = 0
  8915. */
  8916. var Plane = /** @class */ (function () {
  8917. /**
  8918. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  8919. * @param a a component of the plane
  8920. * @param b b component of the plane
  8921. * @param c c component of the plane
  8922. * @param d d component of the plane
  8923. */
  8924. function Plane(a, b, c, d) {
  8925. this.normal = new Vector3(a, b, c);
  8926. this.d = d;
  8927. }
  8928. /**
  8929. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  8930. */
  8931. Plane.prototype.asArray = function () {
  8932. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  8933. };
  8934. // Methods
  8935. /**
  8936. * @returns a new plane copied from the current Plane.
  8937. */
  8938. Plane.prototype.clone = function () {
  8939. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  8940. };
  8941. /**
  8942. * @returns the string "Plane".
  8943. */
  8944. Plane.prototype.getClassName = function () {
  8945. return "Plane";
  8946. };
  8947. /**
  8948. * @returns the Plane hash code.
  8949. */
  8950. Plane.prototype.getHashCode = function () {
  8951. var hash = this.normal.getHashCode();
  8952. hash = (hash * 397) ^ (this.d || 0);
  8953. return hash;
  8954. };
  8955. /**
  8956. * Normalize the current Plane in place.
  8957. * @returns the updated Plane.
  8958. */
  8959. Plane.prototype.normalize = function () {
  8960. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  8961. var magnitude = 0.0;
  8962. if (norm !== 0) {
  8963. magnitude = 1.0 / norm;
  8964. }
  8965. this.normal.x *= magnitude;
  8966. this.normal.y *= magnitude;
  8967. this.normal.z *= magnitude;
  8968. this.d *= magnitude;
  8969. return this;
  8970. };
  8971. /**
  8972. * Applies a transformation the plane and returns the result
  8973. * @param transformation the transformation matrix to be applied to the plane
  8974. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  8975. */
  8976. Plane.prototype.transform = function (transformation) {
  8977. var transposedMatrix = Matrix.Transpose(transformation);
  8978. var x = this.normal.x;
  8979. var y = this.normal.y;
  8980. var z = this.normal.z;
  8981. var d = this.d;
  8982. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  8983. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  8984. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  8985. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  8986. return new Plane(normalX, normalY, normalZ, finalD);
  8987. };
  8988. /**
  8989. * Calcualtte the dot product between the point and the plane normal
  8990. * @param point point to calculate the dot product with
  8991. * @returns the dot product (float) of the point coordinates and the plane normal.
  8992. */
  8993. Plane.prototype.dotCoordinate = function (point) {
  8994. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  8995. };
  8996. /**
  8997. * Updates the current Plane from the plane defined by the three given points.
  8998. * @param point1 one of the points used to contruct the plane
  8999. * @param point2 one of the points used to contruct the plane
  9000. * @param point3 one of the points used to contruct the plane
  9001. * @returns the updated Plane.
  9002. */
  9003. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9004. var x1 = point2.x - point1.x;
  9005. var y1 = point2.y - point1.y;
  9006. var z1 = point2.z - point1.z;
  9007. var x2 = point3.x - point1.x;
  9008. var y2 = point3.y - point1.y;
  9009. var z2 = point3.z - point1.z;
  9010. var yz = (y1 * z2) - (z1 * y2);
  9011. var xz = (z1 * x2) - (x1 * z2);
  9012. var xy = (x1 * y2) - (y1 * x2);
  9013. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9014. var invPyth;
  9015. if (pyth !== 0) {
  9016. invPyth = 1.0 / pyth;
  9017. }
  9018. else {
  9019. invPyth = 0.0;
  9020. }
  9021. this.normal.x = yz * invPyth;
  9022. this.normal.y = xz * invPyth;
  9023. this.normal.z = xy * invPyth;
  9024. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9025. return this;
  9026. };
  9027. /**
  9028. * Checks if the plane is facing a given direction
  9029. * @param direction the direction to check if the plane is facing
  9030. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9031. * @returns True is the vector "direction" is the same side than the plane normal.
  9032. */
  9033. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9034. var dot = Vector3.Dot(this.normal, direction);
  9035. return (dot <= epsilon);
  9036. };
  9037. /**
  9038. * Calculates the distance to a point
  9039. * @param point point to calculate distance to
  9040. * @returns the signed distance (float) from the given point to the Plane.
  9041. */
  9042. Plane.prototype.signedDistanceTo = function (point) {
  9043. return Vector3.Dot(point, this.normal) + this.d;
  9044. };
  9045. // Statics
  9046. /**
  9047. * Creates a plane from an array
  9048. * @param array the array to create a plane from
  9049. * @returns a new Plane from the given array.
  9050. */
  9051. Plane.FromArray = function (array) {
  9052. return new Plane(array[0], array[1], array[2], array[3]);
  9053. };
  9054. /**
  9055. * Creates a plane from three points
  9056. * @param point1 point used to create the plane
  9057. * @param point2 point used to create the plane
  9058. * @param point3 point used to create the plane
  9059. * @returns a new Plane defined by the three given points.
  9060. */
  9061. Plane.FromPoints = function (point1, point2, point3) {
  9062. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9063. result.copyFromPoints(point1, point2, point3);
  9064. return result;
  9065. };
  9066. /**
  9067. * Creates a plane from an origin point and a normal
  9068. * @param origin origin of the plane to be constructed
  9069. * @param normal normal of the plane to be constructed
  9070. * @returns a new Plane the normal vector to this plane at the given origin point.
  9071. * Note : the vector "normal" is updated because normalized.
  9072. */
  9073. Plane.FromPositionAndNormal = function (origin, normal) {
  9074. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9075. normal.normalize();
  9076. result.normal = normal;
  9077. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9078. return result;
  9079. };
  9080. /**
  9081. * Calculates the distance from a plane and a point
  9082. * @param origin origin of the plane to be constructed
  9083. * @param normal normal of the plane to be constructed
  9084. * @param point point to calculate distance to
  9085. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9086. */
  9087. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9088. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9089. return Vector3.Dot(point, normal) + d;
  9090. };
  9091. return Plane;
  9092. }());
  9093. BABYLON.Plane = Plane;
  9094. /**
  9095. * Class used to represent a viewport on screen
  9096. */
  9097. var Viewport = /** @class */ (function () {
  9098. /**
  9099. * Creates a Viewport object located at (x, y) and sized (width, height)
  9100. * @param x defines viewport left coordinate
  9101. * @param y defines viewport top coordinate
  9102. * @param width defines the viewport width
  9103. * @param height defines the viewport height
  9104. */
  9105. function Viewport(
  9106. /** viewport left coordinate */
  9107. x,
  9108. /** viewport top coordinate */
  9109. y,
  9110. /**viewport width */
  9111. width,
  9112. /** viewport height */
  9113. height) {
  9114. this.x = x;
  9115. this.y = y;
  9116. this.width = width;
  9117. this.height = height;
  9118. }
  9119. /**
  9120. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9121. * @param renderWidthOrEngine defines either an engine or the rendering width
  9122. * @param renderHeight defines the rendering height
  9123. * @returns a new Viewport
  9124. */
  9125. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9126. if (renderWidthOrEngine.getRenderWidth) {
  9127. var engine = renderWidthOrEngine;
  9128. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9129. }
  9130. var renderWidth = renderWidthOrEngine;
  9131. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9132. };
  9133. /**
  9134. * Returns a new Viewport copied from the current one
  9135. * @returns a new Viewport
  9136. */
  9137. Viewport.prototype.clone = function () {
  9138. return new Viewport(this.x, this.y, this.width, this.height);
  9139. };
  9140. return Viewport;
  9141. }());
  9142. BABYLON.Viewport = Viewport;
  9143. /**
  9144. * Reprasents a camera frustum
  9145. */
  9146. var Frustum = /** @class */ (function () {
  9147. function Frustum() {
  9148. }
  9149. /**
  9150. * Gets the planes representing the frustum
  9151. * @param transform matrix to be applied to the returned planes
  9152. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9153. */
  9154. Frustum.GetPlanes = function (transform) {
  9155. var frustumPlanes = [];
  9156. for (var index = 0; index < 6; index++) {
  9157. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9158. }
  9159. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9160. return frustumPlanes;
  9161. };
  9162. /**
  9163. * Gets the near frustum plane transformed by the transform matrix
  9164. * @param transform transformation matrix to be applied to the resulting frustum plane
  9165. * @param frustumPlane the resuling frustum plane
  9166. */
  9167. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9168. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  9169. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  9170. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  9171. frustumPlane.d = transform.m[15] + transform.m[14];
  9172. frustumPlane.normalize();
  9173. };
  9174. /**
  9175. * Gets the far frustum plane transformed by the transform matrix
  9176. * @param transform transformation matrix to be applied to the resulting frustum plane
  9177. * @param frustumPlane the resuling frustum plane
  9178. */
  9179. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9180. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  9181. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  9182. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  9183. frustumPlane.d = transform.m[15] - transform.m[14];
  9184. frustumPlane.normalize();
  9185. };
  9186. /**
  9187. * Gets the left frustum plane transformed by the transform matrix
  9188. * @param transform transformation matrix to be applied to the resulting frustum plane
  9189. * @param frustumPlane the resuling frustum plane
  9190. */
  9191. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9192. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  9193. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  9194. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  9195. frustumPlane.d = transform.m[15] + transform.m[12];
  9196. frustumPlane.normalize();
  9197. };
  9198. /**
  9199. * Gets the right frustum plane transformed by the transform matrix
  9200. * @param transform transformation matrix to be applied to the resulting frustum plane
  9201. * @param frustumPlane the resuling frustum plane
  9202. */
  9203. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9204. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  9205. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  9206. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  9207. frustumPlane.d = transform.m[15] - transform.m[12];
  9208. frustumPlane.normalize();
  9209. };
  9210. /**
  9211. * Gets the top frustum plane transformed by the transform matrix
  9212. * @param transform transformation matrix to be applied to the resulting frustum plane
  9213. * @param frustumPlane the resuling frustum plane
  9214. */
  9215. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9216. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  9217. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  9218. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  9219. frustumPlane.d = transform.m[15] - transform.m[13];
  9220. frustumPlane.normalize();
  9221. };
  9222. /**
  9223. * Gets the bottom frustum plane transformed by the transform matrix
  9224. * @param transform transformation matrix to be applied to the resulting frustum plane
  9225. * @param frustumPlane the resuling frustum plane
  9226. */
  9227. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9228. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  9229. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  9230. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  9231. frustumPlane.d = transform.m[15] + transform.m[13];
  9232. frustumPlane.normalize();
  9233. };
  9234. /**
  9235. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9236. * @param transform transformation matrix to be applied to the resulting frustum planes
  9237. * @param frustumPlanes the resuling frustum planes
  9238. */
  9239. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9240. // Near
  9241. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9242. // Far
  9243. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9244. // Left
  9245. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9246. // Right
  9247. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9248. // Top
  9249. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9250. // Bottom
  9251. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9252. };
  9253. return Frustum;
  9254. }());
  9255. BABYLON.Frustum = Frustum;
  9256. /** Defines supported spaces */
  9257. var Space;
  9258. (function (Space) {
  9259. /** Local (object) space */
  9260. Space[Space["LOCAL"] = 0] = "LOCAL";
  9261. /** World space */
  9262. Space[Space["WORLD"] = 1] = "WORLD";
  9263. /** Bone space */
  9264. Space[Space["BONE"] = 2] = "BONE";
  9265. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9266. /** Defines the 3 main axes */
  9267. var Axis = /** @class */ (function () {
  9268. function Axis() {
  9269. }
  9270. /** X axis */
  9271. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9272. /** Y axis */
  9273. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9274. /** Z axis */
  9275. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9276. return Axis;
  9277. }());
  9278. BABYLON.Axis = Axis;
  9279. /** Class used to represent a Bezier curve */
  9280. var BezierCurve = /** @class */ (function () {
  9281. function BezierCurve() {
  9282. }
  9283. /**
  9284. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9285. * @param t defines the time
  9286. * @param x1 defines the left coordinate on X axis
  9287. * @param y1 defines the left coordinate on Y axis
  9288. * @param x2 defines the right coordinate on X axis
  9289. * @param y2 defines the right coordinate on Y axis
  9290. * @returns the interpolated value
  9291. */
  9292. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9293. // Extract X (which is equal to time here)
  9294. var f0 = 1 - 3 * x2 + 3 * x1;
  9295. var f1 = 3 * x2 - 6 * x1;
  9296. var f2 = 3 * x1;
  9297. var refinedT = t;
  9298. for (var i = 0; i < 5; i++) {
  9299. var refinedT2 = refinedT * refinedT;
  9300. var refinedT3 = refinedT2 * refinedT;
  9301. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9302. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9303. refinedT -= (x - t) * slope;
  9304. refinedT = Math.min(1, Math.max(0, refinedT));
  9305. }
  9306. // Resolve cubic bezier for the given x
  9307. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9308. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9309. Math.pow(refinedT, 3);
  9310. };
  9311. return BezierCurve;
  9312. }());
  9313. BABYLON.BezierCurve = BezierCurve;
  9314. /**
  9315. * Defines potential orientation for back face culling
  9316. */
  9317. var Orientation;
  9318. (function (Orientation) {
  9319. /**
  9320. * Clockwise
  9321. */
  9322. Orientation[Orientation["CW"] = 0] = "CW";
  9323. /** Counter clockwise */
  9324. Orientation[Orientation["CCW"] = 1] = "CCW";
  9325. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9326. /**
  9327. * Defines angle representation
  9328. */
  9329. var Angle = /** @class */ (function () {
  9330. /**
  9331. * Creates an Angle object of "radians" radians (float).
  9332. */
  9333. function Angle(radians) {
  9334. this._radians = radians;
  9335. if (this._radians < 0.0) {
  9336. this._radians += (2.0 * Math.PI);
  9337. }
  9338. }
  9339. /**
  9340. * Get value in degrees
  9341. * @returns the Angle value in degrees (float)
  9342. */
  9343. Angle.prototype.degrees = function () {
  9344. return this._radians * 180.0 / Math.PI;
  9345. };
  9346. /**
  9347. * Get value in radians
  9348. * @returns the Angle value in radians (float)
  9349. */
  9350. Angle.prototype.radians = function () {
  9351. return this._radians;
  9352. };
  9353. /**
  9354. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9355. * @param a defines first vector
  9356. * @param b defines second vector
  9357. * @returns a new Angle
  9358. */
  9359. Angle.BetweenTwoPoints = function (a, b) {
  9360. var delta = b.subtract(a);
  9361. var theta = Math.atan2(delta.y, delta.x);
  9362. return new Angle(theta);
  9363. };
  9364. /**
  9365. * Gets a new Angle object from the given float in radians
  9366. * @param radians defines the angle value in radians
  9367. * @returns a new Angle
  9368. */
  9369. Angle.FromRadians = function (radians) {
  9370. return new Angle(radians);
  9371. };
  9372. /**
  9373. * Gets a new Angle object from the given float in degrees
  9374. * @param degrees defines the angle value in degrees
  9375. * @returns a new Angle
  9376. */
  9377. Angle.FromDegrees = function (degrees) {
  9378. return new Angle(degrees * Math.PI / 180.0);
  9379. };
  9380. return Angle;
  9381. }());
  9382. BABYLON.Angle = Angle;
  9383. /**
  9384. * This represents an arc in a 2d space.
  9385. */
  9386. var Arc2 = /** @class */ (function () {
  9387. /**
  9388. * Creates an Arc object from the three given points : start, middle and end.
  9389. * @param startPoint Defines the start point of the arc
  9390. * @param midPoint Defines the midlle point of the arc
  9391. * @param endPoint Defines the end point of the arc
  9392. */
  9393. function Arc2(
  9394. /** Defines the start point of the arc */
  9395. startPoint,
  9396. /** Defines the mid point of the arc */
  9397. midPoint,
  9398. /** Defines the end point of the arc */
  9399. endPoint) {
  9400. this.startPoint = startPoint;
  9401. this.midPoint = midPoint;
  9402. this.endPoint = endPoint;
  9403. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9404. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9405. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9406. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9407. 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);
  9408. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9409. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9410. var a1 = this.startAngle.degrees();
  9411. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9412. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9413. // angles correction
  9414. if (a2 - a1 > +180.0) {
  9415. a2 -= 360.0;
  9416. }
  9417. if (a2 - a1 < -180.0) {
  9418. a2 += 360.0;
  9419. }
  9420. if (a3 - a2 > +180.0) {
  9421. a3 -= 360.0;
  9422. }
  9423. if (a3 - a2 < -180.0) {
  9424. a3 += 360.0;
  9425. }
  9426. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9427. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9428. }
  9429. return Arc2;
  9430. }());
  9431. BABYLON.Arc2 = Arc2;
  9432. /**
  9433. * Represents a 2D path made up of multiple 2D points
  9434. */
  9435. var Path2 = /** @class */ (function () {
  9436. /**
  9437. * Creates a Path2 object from the starting 2D coordinates x and y.
  9438. * @param x the starting points x value
  9439. * @param y the starting points y value
  9440. */
  9441. function Path2(x, y) {
  9442. this._points = new Array();
  9443. this._length = 0.0;
  9444. /**
  9445. * If the path start and end point are the same
  9446. */
  9447. this.closed = false;
  9448. this._points.push(new Vector2(x, y));
  9449. }
  9450. /**
  9451. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9452. * @param x the added points x value
  9453. * @param y the added points y value
  9454. * @returns the updated Path2.
  9455. */
  9456. Path2.prototype.addLineTo = function (x, y) {
  9457. if (this.closed) {
  9458. return this;
  9459. }
  9460. var newPoint = new Vector2(x, y);
  9461. var previousPoint = this._points[this._points.length - 1];
  9462. this._points.push(newPoint);
  9463. this._length += newPoint.subtract(previousPoint).length();
  9464. return this;
  9465. };
  9466. /**
  9467. * 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.
  9468. * @param midX middle point x value
  9469. * @param midY middle point y value
  9470. * @param endX end point x value
  9471. * @param endY end point y value
  9472. * @param numberOfSegments (default: 36)
  9473. * @returns the updated Path2.
  9474. */
  9475. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9476. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9477. if (this.closed) {
  9478. return this;
  9479. }
  9480. var startPoint = this._points[this._points.length - 1];
  9481. var midPoint = new Vector2(midX, midY);
  9482. var endPoint = new Vector2(endX, endY);
  9483. var arc = new Arc2(startPoint, midPoint, endPoint);
  9484. var increment = arc.angle.radians() / numberOfSegments;
  9485. if (arc.orientation === Orientation.CW) {
  9486. increment *= -1;
  9487. }
  9488. var currentAngle = arc.startAngle.radians() + increment;
  9489. for (var i = 0; i < numberOfSegments; i++) {
  9490. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9491. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9492. this.addLineTo(x, y);
  9493. currentAngle += increment;
  9494. }
  9495. return this;
  9496. };
  9497. /**
  9498. * Closes the Path2.
  9499. * @returns the Path2.
  9500. */
  9501. Path2.prototype.close = function () {
  9502. this.closed = true;
  9503. return this;
  9504. };
  9505. /**
  9506. * Gets the sum of the distance between each sequential point in the path
  9507. * @returns the Path2 total length (float).
  9508. */
  9509. Path2.prototype.length = function () {
  9510. var result = this._length;
  9511. if (!this.closed) {
  9512. var lastPoint = this._points[this._points.length - 1];
  9513. var firstPoint = this._points[0];
  9514. result += (firstPoint.subtract(lastPoint).length());
  9515. }
  9516. return result;
  9517. };
  9518. /**
  9519. * Gets the points which construct the path
  9520. * @returns the Path2 internal array of points.
  9521. */
  9522. Path2.prototype.getPoints = function () {
  9523. return this._points;
  9524. };
  9525. /**
  9526. * Retreives the point at the distance aways from the starting point
  9527. * @param normalizedLengthPosition the length along the path to retreive the point from
  9528. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9529. */
  9530. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9531. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9532. return Vector2.Zero();
  9533. }
  9534. var lengthPosition = normalizedLengthPosition * this.length();
  9535. var previousOffset = 0;
  9536. for (var i = 0; i < this._points.length; i++) {
  9537. var j = (i + 1) % this._points.length;
  9538. var a = this._points[i];
  9539. var b = this._points[j];
  9540. var bToA = b.subtract(a);
  9541. var nextOffset = (bToA.length() + previousOffset);
  9542. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9543. var dir = bToA.normalize();
  9544. var localOffset = lengthPosition - previousOffset;
  9545. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9546. }
  9547. previousOffset = nextOffset;
  9548. }
  9549. return Vector2.Zero();
  9550. };
  9551. /**
  9552. * Creates a new path starting from an x and y position
  9553. * @param x starting x value
  9554. * @param y starting y value
  9555. * @returns a new Path2 starting at the coordinates (x, y).
  9556. */
  9557. Path2.StartingAt = function (x, y) {
  9558. return new Path2(x, y);
  9559. };
  9560. return Path2;
  9561. }());
  9562. BABYLON.Path2 = Path2;
  9563. /**
  9564. * Represents a 3D path made up of multiple 3D points
  9565. */
  9566. var Path3D = /** @class */ (function () {
  9567. /**
  9568. * new Path3D(path, normal, raw)
  9569. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9570. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9571. * @param path an array of Vector3, the curve axis of the Path3D
  9572. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9573. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9574. */
  9575. function Path3D(
  9576. /**
  9577. * an array of Vector3, the curve axis of the Path3D
  9578. */
  9579. path, firstNormal, raw) {
  9580. if (firstNormal === void 0) { firstNormal = null; }
  9581. this.path = path;
  9582. this._curve = new Array();
  9583. this._distances = new Array();
  9584. this._tangents = new Array();
  9585. this._normals = new Array();
  9586. this._binormals = new Array();
  9587. for (var p = 0; p < path.length; p++) {
  9588. this._curve[p] = path[p].clone(); // hard copy
  9589. }
  9590. this._raw = raw || false;
  9591. this._compute(firstNormal);
  9592. }
  9593. /**
  9594. * Returns the Path3D array of successive Vector3 designing its curve.
  9595. * @returns the Path3D array of successive Vector3 designing its curve.
  9596. */
  9597. Path3D.prototype.getCurve = function () {
  9598. return this._curve;
  9599. };
  9600. /**
  9601. * Returns an array populated with tangent vectors on each Path3D curve point.
  9602. * @returns an array populated with tangent vectors on each Path3D curve point.
  9603. */
  9604. Path3D.prototype.getTangents = function () {
  9605. return this._tangents;
  9606. };
  9607. /**
  9608. * Returns an array populated with normal vectors on each Path3D curve point.
  9609. * @returns an array populated with normal vectors on each Path3D curve point.
  9610. */
  9611. Path3D.prototype.getNormals = function () {
  9612. return this._normals;
  9613. };
  9614. /**
  9615. * Returns an array populated with binormal vectors on each Path3D curve point.
  9616. * @returns an array populated with binormal vectors on each Path3D curve point.
  9617. */
  9618. Path3D.prototype.getBinormals = function () {
  9619. return this._binormals;
  9620. };
  9621. /**
  9622. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9623. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9624. */
  9625. Path3D.prototype.getDistances = function () {
  9626. return this._distances;
  9627. };
  9628. /**
  9629. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9630. * @param path path which all values are copied into the curves points
  9631. * @param firstNormal which should be projected onto the curve
  9632. * @returns the same object updated.
  9633. */
  9634. Path3D.prototype.update = function (path, firstNormal) {
  9635. if (firstNormal === void 0) { firstNormal = null; }
  9636. for (var p = 0; p < path.length; p++) {
  9637. this._curve[p].x = path[p].x;
  9638. this._curve[p].y = path[p].y;
  9639. this._curve[p].z = path[p].z;
  9640. }
  9641. this._compute(firstNormal);
  9642. return this;
  9643. };
  9644. // private function compute() : computes tangents, normals and binormals
  9645. Path3D.prototype._compute = function (firstNormal) {
  9646. var l = this._curve.length;
  9647. // first and last tangents
  9648. this._tangents[0] = this._getFirstNonNullVector(0);
  9649. if (!this._raw) {
  9650. this._tangents[0].normalize();
  9651. }
  9652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9653. if (!this._raw) {
  9654. this._tangents[l - 1].normalize();
  9655. }
  9656. // normals and binormals at first point : arbitrary vector with _normalVector()
  9657. var tg0 = this._tangents[0];
  9658. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9659. this._normals[0] = pp0;
  9660. if (!this._raw) {
  9661. this._normals[0].normalize();
  9662. }
  9663. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9664. if (!this._raw) {
  9665. this._binormals[0].normalize();
  9666. }
  9667. this._distances[0] = 0.0;
  9668. // normals and binormals : next points
  9669. var prev; // previous vector (segment)
  9670. var cur; // current vector (segment)
  9671. var curTang; // current tangent
  9672. // previous normal
  9673. var prevBinor; // previous binormal
  9674. for (var i = 1; i < l; i++) {
  9675. // tangents
  9676. prev = this._getLastNonNullVector(i);
  9677. if (i < l - 1) {
  9678. cur = this._getFirstNonNullVector(i);
  9679. this._tangents[i] = prev.add(cur);
  9680. this._tangents[i].normalize();
  9681. }
  9682. this._distances[i] = this._distances[i - 1] + prev.length();
  9683. // normals and binormals
  9684. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9685. curTang = this._tangents[i];
  9686. prevBinor = this._binormals[i - 1];
  9687. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9688. if (!this._raw) {
  9689. this._normals[i].normalize();
  9690. }
  9691. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9692. if (!this._raw) {
  9693. this._binormals[i].normalize();
  9694. }
  9695. }
  9696. };
  9697. // private function getFirstNonNullVector(index)
  9698. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9699. Path3D.prototype._getFirstNonNullVector = function (index) {
  9700. var i = 1;
  9701. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9702. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9703. i++;
  9704. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9705. }
  9706. return nNVector;
  9707. };
  9708. // private function getLastNonNullVector(index)
  9709. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9710. Path3D.prototype._getLastNonNullVector = function (index) {
  9711. var i = 1;
  9712. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9713. while (nLVector.length() === 0 && index > i + 1) {
  9714. i++;
  9715. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9716. }
  9717. return nLVector;
  9718. };
  9719. // private function normalVector(v0, vt, va) :
  9720. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9721. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9722. Path3D.prototype._normalVector = function (v0, vt, va) {
  9723. var normal0;
  9724. var tgl = vt.length();
  9725. if (tgl === 0.0) {
  9726. tgl = 1.0;
  9727. }
  9728. if (va === undefined || va === null) {
  9729. var point;
  9730. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9731. point = new Vector3(0.0, -1.0, 0.0);
  9732. }
  9733. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9734. point = new Vector3(1.0, 0.0, 0.0);
  9735. }
  9736. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9737. point = new Vector3(0.0, 0.0, 1.0);
  9738. }
  9739. else {
  9740. point = Vector3.Zero();
  9741. }
  9742. normal0 = Vector3.Cross(vt, point);
  9743. }
  9744. else {
  9745. normal0 = Vector3.Cross(vt, va);
  9746. Vector3.CrossToRef(normal0, vt, normal0);
  9747. }
  9748. normal0.normalize();
  9749. return normal0;
  9750. };
  9751. return Path3D;
  9752. }());
  9753. BABYLON.Path3D = Path3D;
  9754. /**
  9755. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9756. * A Curve3 is designed from a series of successive Vector3.
  9757. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9758. */
  9759. var Curve3 = /** @class */ (function () {
  9760. /**
  9761. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9762. * A Curve3 is designed from a series of successive Vector3.
  9763. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  9764. * @param points points which make up the curve
  9765. */
  9766. function Curve3(points) {
  9767. this._length = 0.0;
  9768. this._points = points;
  9769. this._length = this._computeLength(points);
  9770. }
  9771. /**
  9772. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  9773. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  9774. * @param v1 (Vector3) the control point
  9775. * @param v2 (Vector3) the end point of the Quadratic Bezier
  9776. * @param nbPoints (integer) the wanted number of points in the curve
  9777. * @returns the created Curve3
  9778. */
  9779. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  9780. nbPoints = nbPoints > 2 ? nbPoints : 3;
  9781. var bez = new Array();
  9782. var equation = function (t, val0, val1, val2) {
  9783. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  9784. return res;
  9785. };
  9786. for (var i = 0; i <= nbPoints; i++) {
  9787. 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)));
  9788. }
  9789. return new Curve3(bez);
  9790. };
  9791. /**
  9792. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  9793. * @param v0 (Vector3) the origin point of the Cubic Bezier
  9794. * @param v1 (Vector3) the first control point
  9795. * @param v2 (Vector3) the second control point
  9796. * @param v3 (Vector3) the end point of the Cubic Bezier
  9797. * @param nbPoints (integer) the wanted number of points in the curve
  9798. * @returns the created Curve3
  9799. */
  9800. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  9801. nbPoints = nbPoints > 3 ? nbPoints : 4;
  9802. var bez = new Array();
  9803. var equation = function (t, val0, val1, val2, val3) {
  9804. 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;
  9805. return res;
  9806. };
  9807. for (var i = 0; i <= nbPoints; i++) {
  9808. 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)));
  9809. }
  9810. return new Curve3(bez);
  9811. };
  9812. /**
  9813. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  9814. * @param p1 (Vector3) the origin point of the Hermite Spline
  9815. * @param t1 (Vector3) the tangent vector at the origin point
  9816. * @param p2 (Vector3) the end point of the Hermite Spline
  9817. * @param t2 (Vector3) the tangent vector at the end point
  9818. * @param nbPoints (integer) the wanted number of points in the curve
  9819. * @returns the created Curve3
  9820. */
  9821. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  9822. var hermite = new Array();
  9823. var step = 1.0 / nbPoints;
  9824. for (var i = 0; i <= nbPoints; i++) {
  9825. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  9826. }
  9827. return new Curve3(hermite);
  9828. };
  9829. /**
  9830. * Returns a Curve3 object along a CatmullRom Spline curve :
  9831. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  9832. * @param nbPoints (integer) the wanted number of points between each curve control points
  9833. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  9834. * @returns the created Curve3
  9835. */
  9836. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  9837. var catmullRom = new Array();
  9838. var step = 1.0 / nbPoints;
  9839. var amount = 0.0;
  9840. if (closed) {
  9841. var pointsCount = points.length;
  9842. for (var i = 0; i < pointsCount; i++) {
  9843. amount = 0;
  9844. for (var c = 0; c < nbPoints; c++) {
  9845. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  9846. amount += step;
  9847. }
  9848. }
  9849. catmullRom.push(catmullRom[0]);
  9850. }
  9851. else {
  9852. var totalPoints = new Array();
  9853. totalPoints.push(points[0].clone());
  9854. Array.prototype.push.apply(totalPoints, points);
  9855. totalPoints.push(points[points.length - 1].clone());
  9856. for (var i = 0; i < totalPoints.length - 3; i++) {
  9857. amount = 0;
  9858. for (var c = 0; c < nbPoints; c++) {
  9859. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9860. amount += step;
  9861. }
  9862. }
  9863. i--;
  9864. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9865. }
  9866. return new Curve3(catmullRom);
  9867. };
  9868. /**
  9869. * @returns the Curve3 stored array of successive Vector3
  9870. */
  9871. Curve3.prototype.getPoints = function () {
  9872. return this._points;
  9873. };
  9874. /**
  9875. * @returns the computed length (float) of the curve.
  9876. */
  9877. Curve3.prototype.length = function () {
  9878. return this._length;
  9879. };
  9880. /**
  9881. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  9882. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  9883. * curveA and curveB keep unchanged.
  9884. * @param curve the curve to continue from this curve
  9885. * @returns the newly constructed curve
  9886. */
  9887. Curve3.prototype.continue = function (curve) {
  9888. var lastPoint = this._points[this._points.length - 1];
  9889. var continuedPoints = this._points.slice();
  9890. var curvePoints = curve.getPoints();
  9891. for (var i = 1; i < curvePoints.length; i++) {
  9892. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  9893. }
  9894. var continuedCurve = new Curve3(continuedPoints);
  9895. return continuedCurve;
  9896. };
  9897. Curve3.prototype._computeLength = function (path) {
  9898. var l = 0;
  9899. for (var i = 1; i < path.length; i++) {
  9900. l += (path[i].subtract(path[i - 1])).length();
  9901. }
  9902. return l;
  9903. };
  9904. return Curve3;
  9905. }());
  9906. BABYLON.Curve3 = Curve3;
  9907. // Vertex formats
  9908. /**
  9909. * Contains position and normal vectors for a vertex
  9910. */
  9911. var PositionNormalVertex = /** @class */ (function () {
  9912. /**
  9913. * Creates a PositionNormalVertex
  9914. * @param position the position of the vertex (defaut: 0,0,0)
  9915. * @param normal the normal of the vertex (defaut: 0,1,0)
  9916. */
  9917. function PositionNormalVertex(
  9918. /** the position of the vertex (defaut: 0,0,0) */
  9919. position,
  9920. /** the normal of the vertex (defaut: 0,1,0) */
  9921. normal) {
  9922. if (position === void 0) { position = Vector3.Zero(); }
  9923. if (normal === void 0) { normal = Vector3.Up(); }
  9924. this.position = position;
  9925. this.normal = normal;
  9926. }
  9927. /**
  9928. * Clones the PositionNormalVertex
  9929. * @returns the cloned PositionNormalVertex
  9930. */
  9931. PositionNormalVertex.prototype.clone = function () {
  9932. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  9933. };
  9934. return PositionNormalVertex;
  9935. }());
  9936. BABYLON.PositionNormalVertex = PositionNormalVertex;
  9937. /**
  9938. * Contains position, normal and uv vectors for a vertex
  9939. */
  9940. var PositionNormalTextureVertex = /** @class */ (function () {
  9941. /**
  9942. * Creates a PositionNormalTextureVertex
  9943. * @param position the position of the vertex (defaut: 0,0,0)
  9944. * @param normal the normal of the vertex (defaut: 0,1,0)
  9945. * @param uv the uv of the vertex (default: 0,0)
  9946. */
  9947. function PositionNormalTextureVertex(
  9948. /** the position of the vertex (defaut: 0,0,0) */
  9949. position,
  9950. /** the normal of the vertex (defaut: 0,1,0) */
  9951. normal,
  9952. /** the uv of the vertex (default: 0,0) */
  9953. uv) {
  9954. if (position === void 0) { position = Vector3.Zero(); }
  9955. if (normal === void 0) { normal = Vector3.Up(); }
  9956. if (uv === void 0) { uv = Vector2.Zero(); }
  9957. this.position = position;
  9958. this.normal = normal;
  9959. this.uv = uv;
  9960. }
  9961. /**
  9962. * Clones the PositionNormalTextureVertex
  9963. * @returns the cloned PositionNormalTextureVertex
  9964. */
  9965. PositionNormalTextureVertex.prototype.clone = function () {
  9966. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  9967. };
  9968. return PositionNormalTextureVertex;
  9969. }());
  9970. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  9971. // Temporary pre-allocated objects for engine internal use
  9972. // usage in any internal function :
  9973. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  9974. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  9975. /**
  9976. * @hidden
  9977. */
  9978. var Tmp = /** @class */ (function () {
  9979. function Tmp() {
  9980. }
  9981. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  9982. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  9983. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  9984. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  9985. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  9986. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  9987. Tmp.Matrix = BABYLON.Tools.BuildArray(6, Matrix.Identity); // 6 temp Matrices at once should be enough
  9988. return Tmp;
  9989. }());
  9990. BABYLON.Tmp = Tmp;
  9991. /**
  9992. * @hidden
  9993. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  9994. */
  9995. var MathTmp = /** @class */ (function () {
  9996. function MathTmp() {
  9997. }
  9998. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  9999. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10000. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10001. return MathTmp;
  10002. }());
  10003. })(BABYLON || (BABYLON = {}));
  10004. //# sourceMappingURL=babylon.math.js.map
  10005. var BABYLON;
  10006. (function (BABYLON) {
  10007. /**
  10008. * Scalar computation library
  10009. */
  10010. var Scalar = /** @class */ (function () {
  10011. function Scalar() {
  10012. }
  10013. /**
  10014. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10015. * @param a number
  10016. * @param b number
  10017. * @param epsilon (default = 1.401298E-45)
  10018. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10019. */
  10020. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10021. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10022. var num = a - b;
  10023. return -epsilon <= num && num <= epsilon;
  10024. };
  10025. /**
  10026. * Returns a string : the upper case translation of the number i to hexadecimal.
  10027. * @param i number
  10028. * @returns the upper case translation of the number i to hexadecimal.
  10029. */
  10030. Scalar.ToHex = function (i) {
  10031. var str = i.toString(16);
  10032. if (i <= 15) {
  10033. return ("0" + str).toUpperCase();
  10034. }
  10035. return str.toUpperCase();
  10036. };
  10037. /**
  10038. * Returns -1 if value is negative and +1 is value is positive.
  10039. * @param value the value
  10040. * @returns the value itself if it's equal to zero.
  10041. */
  10042. Scalar.Sign = function (value) {
  10043. value = +value; // convert to a number
  10044. if (value === 0 || isNaN(value)) {
  10045. return value;
  10046. }
  10047. return value > 0 ? 1 : -1;
  10048. };
  10049. /**
  10050. * Returns the value itself if it's between min and max.
  10051. * Returns min if the value is lower than min.
  10052. * Returns max if the value is greater than max.
  10053. * @param value the value to clmap
  10054. * @param min the min value to clamp to (default: 0)
  10055. * @param max the max value to clamp to (default: 1)
  10056. * @returns the clamped value
  10057. */
  10058. Scalar.Clamp = function (value, min, max) {
  10059. if (min === void 0) { min = 0; }
  10060. if (max === void 0) { max = 1; }
  10061. return Math.min(max, Math.max(min, value));
  10062. };
  10063. /**
  10064. * the log2 of value.
  10065. * @param value the value to compute log2 of
  10066. * @returns the log2 of value.
  10067. */
  10068. Scalar.Log2 = function (value) {
  10069. return Math.log(value) * Math.LOG2E;
  10070. };
  10071. /**
  10072. * Loops the value, so that it is never larger than length and never smaller than 0.
  10073. *
  10074. * This is similar to the modulo operator but it works with floating point numbers.
  10075. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10076. * With t = 5 and length = 2.5, the result would be 0.0.
  10077. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10078. * @param value the value
  10079. * @param length the length
  10080. * @returns the looped value
  10081. */
  10082. Scalar.Repeat = function (value, length) {
  10083. return value - Math.floor(value / length) * length;
  10084. };
  10085. /**
  10086. * Normalize the value between 0.0 and 1.0 using min and max values
  10087. * @param value value to normalize
  10088. * @param min max to normalize between
  10089. * @param max min to normalize between
  10090. * @returns the normalized value
  10091. */
  10092. Scalar.Normalize = function (value, min, max) {
  10093. return (value - min) / (max - min);
  10094. };
  10095. /**
  10096. * Denormalize the value from 0.0 and 1.0 using min and max values
  10097. * @param normalized value to denormalize
  10098. * @param min max to denormalize between
  10099. * @param max min to denormalize between
  10100. * @returns the denormalized value
  10101. */
  10102. Scalar.Denormalize = function (normalized, min, max) {
  10103. return (normalized * (max - min) + min);
  10104. };
  10105. /**
  10106. * Calculates the shortest difference between two given angles given in degrees.
  10107. * @param current current angle in degrees
  10108. * @param target target angle in degrees
  10109. * @returns the delta
  10110. */
  10111. Scalar.DeltaAngle = function (current, target) {
  10112. var num = Scalar.Repeat(target - current, 360.0);
  10113. if (num > 180.0) {
  10114. num -= 360.0;
  10115. }
  10116. return num;
  10117. };
  10118. /**
  10119. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10120. * @param tx value
  10121. * @param length length
  10122. * @returns The returned value will move back and forth between 0 and length
  10123. */
  10124. Scalar.PingPong = function (tx, length) {
  10125. var t = Scalar.Repeat(tx, length * 2.0);
  10126. return length - Math.abs(t - length);
  10127. };
  10128. /**
  10129. * Interpolates between min and max with smoothing at the limits.
  10130. *
  10131. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10132. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10133. * @param from from
  10134. * @param to to
  10135. * @param tx value
  10136. * @returns the smooth stepped value
  10137. */
  10138. Scalar.SmoothStep = function (from, to, tx) {
  10139. var t = Scalar.Clamp(tx);
  10140. t = -2.0 * t * t * t + 3.0 * t * t;
  10141. return to * t + from * (1.0 - t);
  10142. };
  10143. /**
  10144. * Moves a value current towards target.
  10145. *
  10146. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10147. * Negative values of maxDelta pushes the value away from target.
  10148. * @param current current value
  10149. * @param target target value
  10150. * @param maxDelta max distance to move
  10151. * @returns resulting value
  10152. */
  10153. Scalar.MoveTowards = function (current, target, maxDelta) {
  10154. var result = 0;
  10155. if (Math.abs(target - current) <= maxDelta) {
  10156. result = target;
  10157. }
  10158. else {
  10159. result = current + Scalar.Sign(target - current) * maxDelta;
  10160. }
  10161. return result;
  10162. };
  10163. /**
  10164. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10165. *
  10166. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10167. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10168. * @param current current value
  10169. * @param target target value
  10170. * @param maxDelta max distance to move
  10171. * @returns resulting angle
  10172. */
  10173. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10174. var num = Scalar.DeltaAngle(current, target);
  10175. var result = 0;
  10176. if (-maxDelta < num && num < maxDelta) {
  10177. result = target;
  10178. }
  10179. else {
  10180. target = current + num;
  10181. result = Scalar.MoveTowards(current, target, maxDelta);
  10182. }
  10183. return result;
  10184. };
  10185. /**
  10186. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10187. * @param start start value
  10188. * @param end target value
  10189. * @param amount amount to lerp between
  10190. * @returns the lerped value
  10191. */
  10192. Scalar.Lerp = function (start, end, amount) {
  10193. return start + ((end - start) * amount);
  10194. };
  10195. /**
  10196. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10197. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10198. * @param start start value
  10199. * @param end target value
  10200. * @param amount amount to lerp between
  10201. * @returns the lerped value
  10202. */
  10203. Scalar.LerpAngle = function (start, end, amount) {
  10204. var num = Scalar.Repeat(end - start, 360.0);
  10205. if (num > 180.0) {
  10206. num -= 360.0;
  10207. }
  10208. return start + num * Scalar.Clamp(amount);
  10209. };
  10210. /**
  10211. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10212. * @param a start value
  10213. * @param b target value
  10214. * @param value value between a and b
  10215. * @returns the inverseLerp value
  10216. */
  10217. Scalar.InverseLerp = function (a, b, value) {
  10218. var result = 0;
  10219. if (a != b) {
  10220. result = Scalar.Clamp((value - a) / (b - a));
  10221. }
  10222. else {
  10223. result = 0.0;
  10224. }
  10225. return result;
  10226. };
  10227. /**
  10228. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10229. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10230. * @param value1 spline value
  10231. * @param tangent1 spline value
  10232. * @param value2 spline value
  10233. * @param tangent2 spline value
  10234. * @param amount input value
  10235. * @returns hermite result
  10236. */
  10237. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10238. var squared = amount * amount;
  10239. var cubed = amount * squared;
  10240. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10241. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10242. var part3 = (cubed - (2.0 * squared)) + amount;
  10243. var part4 = cubed - squared;
  10244. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10245. };
  10246. /**
  10247. * Returns a random float number between and min and max values
  10248. * @param min min value of random
  10249. * @param max max value of random
  10250. * @returns random value
  10251. */
  10252. Scalar.RandomRange = function (min, max) {
  10253. if (min === max) {
  10254. return min;
  10255. }
  10256. return ((Math.random() * (max - min)) + min);
  10257. };
  10258. /**
  10259. * This function returns percentage of a number in a given range.
  10260. *
  10261. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10262. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10263. * @param number to convert to percentage
  10264. * @param min min range
  10265. * @param max max range
  10266. * @returns the percentage
  10267. */
  10268. Scalar.RangeToPercent = function (number, min, max) {
  10269. return ((number - min) / (max - min));
  10270. };
  10271. /**
  10272. * This function returns number that corresponds to the percentage in a given range.
  10273. *
  10274. * PercentToRange(0.34,0,100) will return 34.
  10275. * @param percent to convert to number
  10276. * @param min min range
  10277. * @param max max range
  10278. * @returns the number
  10279. */
  10280. Scalar.PercentToRange = function (percent, min, max) {
  10281. return ((max - min) * percent + min);
  10282. };
  10283. /**
  10284. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10285. * @param angle The angle to normalize in radian.
  10286. * @return The converted angle.
  10287. */
  10288. Scalar.NormalizeRadians = function (angle) {
  10289. // More precise but slower version kept for reference.
  10290. // angle = angle % Tools.TwoPi;
  10291. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10292. //if (angle > Math.PI) {
  10293. // angle -= Tools.TwoPi;
  10294. //}
  10295. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10296. return angle;
  10297. };
  10298. /**
  10299. * Two pi constants convenient for computation.
  10300. */
  10301. Scalar.TwoPi = Math.PI * 2;
  10302. return Scalar;
  10303. }());
  10304. BABYLON.Scalar = Scalar;
  10305. })(BABYLON || (BABYLON = {}));
  10306. //# sourceMappingURL=babylon.math.scalar.js.map
  10307. //# sourceMappingURL=babylon.mixins.js.map
  10308. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10309. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10310. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10311. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10312. //# sourceMappingURL=babylon.webgl2.js.map
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. var __decoratorInitialStore = {};
  10316. var __mergedStore = {};
  10317. var _copySource = function (creationFunction, source, instanciate) {
  10318. var destination = creationFunction();
  10319. // Tags
  10320. if (BABYLON.Tags) {
  10321. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10322. }
  10323. var classStore = getMergedStore(destination);
  10324. // Properties
  10325. for (var property in classStore) {
  10326. var propertyDescriptor = classStore[property];
  10327. var sourceProperty = source[property];
  10328. var propertyType = propertyDescriptor.type;
  10329. if (sourceProperty !== undefined && sourceProperty !== null) {
  10330. switch (propertyType) {
  10331. case 0: // Value
  10332. case 6: // Mesh reference
  10333. case 11: // Camera reference
  10334. destination[property] = sourceProperty;
  10335. break;
  10336. case 1: // Texture
  10337. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10338. break;
  10339. case 2: // Color3
  10340. case 3: // FresnelParameters
  10341. case 4: // Vector2
  10342. case 5: // Vector3
  10343. case 7: // Color Curves
  10344. case 10: // Quaternion
  10345. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10346. break;
  10347. }
  10348. }
  10349. }
  10350. return destination;
  10351. };
  10352. function getDirectStore(target) {
  10353. var classKey = target.getClassName();
  10354. if (!__decoratorInitialStore[classKey]) {
  10355. __decoratorInitialStore[classKey] = {};
  10356. }
  10357. return __decoratorInitialStore[classKey];
  10358. }
  10359. /**
  10360. * Return the list of properties flagged as serializable
  10361. * @param target: host object
  10362. */
  10363. function getMergedStore(target) {
  10364. var classKey = target.getClassName();
  10365. if (__mergedStore[classKey]) {
  10366. return __mergedStore[classKey];
  10367. }
  10368. __mergedStore[classKey] = {};
  10369. var store = __mergedStore[classKey];
  10370. var currentTarget = target;
  10371. var currentKey = classKey;
  10372. while (currentKey) {
  10373. var initialStore = __decoratorInitialStore[currentKey];
  10374. for (var property in initialStore) {
  10375. store[property] = initialStore[property];
  10376. }
  10377. var parent_1 = void 0;
  10378. var done = false;
  10379. do {
  10380. parent_1 = Object.getPrototypeOf(currentTarget);
  10381. if (!parent_1.getClassName) {
  10382. done = true;
  10383. break;
  10384. }
  10385. if (parent_1.getClassName() !== currentKey) {
  10386. break;
  10387. }
  10388. currentTarget = parent_1;
  10389. } while (parent_1);
  10390. if (done) {
  10391. break;
  10392. }
  10393. currentKey = parent_1.getClassName();
  10394. currentTarget = parent_1;
  10395. }
  10396. return store;
  10397. }
  10398. function generateSerializableMember(type, sourceName) {
  10399. return function (target, propertyKey) {
  10400. var classStore = getDirectStore(target);
  10401. if (!classStore[propertyKey]) {
  10402. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10403. }
  10404. };
  10405. }
  10406. function generateExpandMember(setCallback, targetKey) {
  10407. if (targetKey === void 0) { targetKey = null; }
  10408. return function (target, propertyKey) {
  10409. var key = targetKey || ("_" + propertyKey);
  10410. Object.defineProperty(target, propertyKey, {
  10411. get: function () {
  10412. return this[key];
  10413. },
  10414. set: function (value) {
  10415. if (this[key] === value) {
  10416. return;
  10417. }
  10418. this[key] = value;
  10419. target[setCallback].apply(this);
  10420. },
  10421. enumerable: true,
  10422. configurable: true
  10423. });
  10424. };
  10425. }
  10426. function expandToProperty(callback, targetKey) {
  10427. if (targetKey === void 0) { targetKey = null; }
  10428. return generateExpandMember(callback, targetKey);
  10429. }
  10430. BABYLON.expandToProperty = expandToProperty;
  10431. function serialize(sourceName) {
  10432. return generateSerializableMember(0, sourceName); // value member
  10433. }
  10434. BABYLON.serialize = serialize;
  10435. function serializeAsTexture(sourceName) {
  10436. return generateSerializableMember(1, sourceName); // texture member
  10437. }
  10438. BABYLON.serializeAsTexture = serializeAsTexture;
  10439. function serializeAsColor3(sourceName) {
  10440. return generateSerializableMember(2, sourceName); // color3 member
  10441. }
  10442. BABYLON.serializeAsColor3 = serializeAsColor3;
  10443. function serializeAsFresnelParameters(sourceName) {
  10444. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10445. }
  10446. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10447. function serializeAsVector2(sourceName) {
  10448. return generateSerializableMember(4, sourceName); // vector2 member
  10449. }
  10450. BABYLON.serializeAsVector2 = serializeAsVector2;
  10451. function serializeAsVector3(sourceName) {
  10452. return generateSerializableMember(5, sourceName); // vector3 member
  10453. }
  10454. BABYLON.serializeAsVector3 = serializeAsVector3;
  10455. function serializeAsMeshReference(sourceName) {
  10456. return generateSerializableMember(6, sourceName); // mesh reference member
  10457. }
  10458. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10459. function serializeAsColorCurves(sourceName) {
  10460. return generateSerializableMember(7, sourceName); // color curves
  10461. }
  10462. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10463. function serializeAsColor4(sourceName) {
  10464. return generateSerializableMember(8, sourceName); // color 4
  10465. }
  10466. BABYLON.serializeAsColor4 = serializeAsColor4;
  10467. function serializeAsImageProcessingConfiguration(sourceName) {
  10468. return generateSerializableMember(9, sourceName); // image processing
  10469. }
  10470. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10471. function serializeAsQuaternion(sourceName) {
  10472. return generateSerializableMember(10, sourceName); // quaternion member
  10473. }
  10474. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10475. /**
  10476. * Decorator used to define property that can be serialized as reference to a camera
  10477. * @param sourceName defines the name of the property to decorate
  10478. */
  10479. function serializeAsCameraReference(sourceName) {
  10480. return generateSerializableMember(11, sourceName); // camera reference member
  10481. }
  10482. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10483. /**
  10484. * Class used to help serialization objects
  10485. */
  10486. var SerializationHelper = /** @class */ (function () {
  10487. function SerializationHelper() {
  10488. }
  10489. /**
  10490. * Static function used to serialized a specific entity
  10491. * @param entity defines the entity to serialize
  10492. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10493. * @returns a JSON compatible object representing the serialization of the entity
  10494. */
  10495. SerializationHelper.Serialize = function (entity, serializationObject) {
  10496. if (!serializationObject) {
  10497. serializationObject = {};
  10498. }
  10499. // Tags
  10500. if (BABYLON.Tags) {
  10501. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10502. }
  10503. var serializedProperties = getMergedStore(entity);
  10504. // Properties
  10505. for (var property in serializedProperties) {
  10506. var propertyDescriptor = serializedProperties[property];
  10507. var targetPropertyName = propertyDescriptor.sourceName || property;
  10508. var propertyType = propertyDescriptor.type;
  10509. var sourceProperty = entity[property];
  10510. if (sourceProperty !== undefined && sourceProperty !== null) {
  10511. switch (propertyType) {
  10512. case 0: // Value
  10513. serializationObject[targetPropertyName] = sourceProperty;
  10514. break;
  10515. case 1: // Texture
  10516. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10517. break;
  10518. case 2: // Color3
  10519. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10520. break;
  10521. case 3: // FresnelParameters
  10522. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10523. break;
  10524. case 4: // Vector2
  10525. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10526. break;
  10527. case 5: // Vector3
  10528. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10529. break;
  10530. case 6: // Mesh reference
  10531. serializationObject[targetPropertyName] = sourceProperty.id;
  10532. break;
  10533. case 7: // Color Curves
  10534. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10535. break;
  10536. case 8: // Color 4
  10537. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10538. break;
  10539. case 9: // Image Processing
  10540. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10541. break;
  10542. case 10: // Quaternion
  10543. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10544. break;
  10545. case 11: // Camera reference
  10546. serializationObject[targetPropertyName] = sourceProperty.id;
  10547. break;
  10548. }
  10549. }
  10550. }
  10551. return serializationObject;
  10552. };
  10553. /**
  10554. * Creates a new entity from a serialization data object
  10555. * @param creationFunction defines a function used to instanciated the new entity
  10556. * @param source defines the source serialization data
  10557. * @param scene defines the hosting scene
  10558. * @param rootUrl defines the root url for resources
  10559. * @returns a new entity
  10560. */
  10561. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10562. if (rootUrl === void 0) { rootUrl = null; }
  10563. var destination = creationFunction();
  10564. if (!rootUrl) {
  10565. rootUrl = "";
  10566. }
  10567. // Tags
  10568. if (BABYLON.Tags) {
  10569. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10570. }
  10571. var classStore = getMergedStore(destination);
  10572. // Properties
  10573. for (var property in classStore) {
  10574. var propertyDescriptor = classStore[property];
  10575. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10576. var propertyType = propertyDescriptor.type;
  10577. if (sourceProperty !== undefined && sourceProperty !== null) {
  10578. var dest = destination;
  10579. switch (propertyType) {
  10580. case 0: // Value
  10581. dest[property] = sourceProperty;
  10582. break;
  10583. case 1: // Texture
  10584. if (scene) {
  10585. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10586. }
  10587. break;
  10588. case 2: // Color3
  10589. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10590. break;
  10591. case 3: // FresnelParameters
  10592. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10593. break;
  10594. case 4: // Vector2
  10595. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10596. break;
  10597. case 5: // Vector3
  10598. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10599. break;
  10600. case 6: // Mesh reference
  10601. if (scene) {
  10602. dest[property] = scene.getLastMeshByID(sourceProperty);
  10603. }
  10604. break;
  10605. case 7: // Color Curves
  10606. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10607. break;
  10608. case 8: // Color 4
  10609. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10610. break;
  10611. case 9: // Image Processing
  10612. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10613. break;
  10614. case 10: // Quaternion
  10615. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10616. break;
  10617. case 11: // Camera reference
  10618. if (scene) {
  10619. dest[property] = scene.getCameraByID(sourceProperty);
  10620. }
  10621. break;
  10622. }
  10623. }
  10624. }
  10625. return destination;
  10626. };
  10627. /**
  10628. * Clones an object
  10629. * @param creationFunction defines the function used to instanciate the new object
  10630. * @param source defines the source object
  10631. * @returns the cloned object
  10632. */
  10633. SerializationHelper.Clone = function (creationFunction, source) {
  10634. return _copySource(creationFunction, source, false);
  10635. };
  10636. /**
  10637. * Instanciates a new object based on a source one (some data will be shared between both object)
  10638. * @param creationFunction defines the function used to instanciate the new object
  10639. * @param source defines the source object
  10640. * @returns the new object
  10641. */
  10642. SerializationHelper.Instanciate = function (creationFunction, source) {
  10643. return _copySource(creationFunction, source, true);
  10644. };
  10645. return SerializationHelper;
  10646. }());
  10647. BABYLON.SerializationHelper = SerializationHelper;
  10648. })(BABYLON || (BABYLON = {}));
  10649. //# sourceMappingURL=babylon.decorators.js.map
  10650. var BABYLON;
  10651. (function (BABYLON) {
  10652. /**
  10653. * Wrapper class for promise with external resolve and reject.
  10654. */
  10655. var Deferred = /** @class */ (function () {
  10656. /**
  10657. * Constructor for this deferred object.
  10658. */
  10659. function Deferred() {
  10660. var _this = this;
  10661. this.promise = new Promise(function (resolve, reject) {
  10662. _this._resolve = resolve;
  10663. _this._reject = reject;
  10664. });
  10665. }
  10666. Object.defineProperty(Deferred.prototype, "resolve", {
  10667. /**
  10668. * The resolve method of the promise associated with this deferred object.
  10669. */
  10670. get: function () {
  10671. return this._resolve;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Deferred.prototype, "reject", {
  10677. /**
  10678. * The reject method of the promise associated with this deferred object.
  10679. */
  10680. get: function () {
  10681. return this._reject;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. return Deferred;
  10687. }());
  10688. BABYLON.Deferred = Deferred;
  10689. })(BABYLON || (BABYLON = {}));
  10690. //# sourceMappingURL=babylon.deferred.js.map
  10691. var BABYLON;
  10692. (function (BABYLON) {
  10693. /**
  10694. * A class serves as a medium between the observable and its observers
  10695. */
  10696. var EventState = /** @class */ (function () {
  10697. /**
  10698. * Create a new EventState
  10699. * @param mask defines the mask associated with this state
  10700. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10701. * @param target defines the original target of the state
  10702. * @param currentTarget defines the current target of the state
  10703. */
  10704. function EventState(mask, skipNextObservers, target, currentTarget) {
  10705. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10706. this.initalize(mask, skipNextObservers, target, currentTarget);
  10707. }
  10708. /**
  10709. * Initialize the current event state
  10710. * @param mask defines the mask associated with this state
  10711. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10712. * @param target defines the original target of the state
  10713. * @param currentTarget defines the current target of the state
  10714. * @returns the current event state
  10715. */
  10716. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10717. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10718. this.mask = mask;
  10719. this.skipNextObservers = skipNextObservers;
  10720. this.target = target;
  10721. this.currentTarget = currentTarget;
  10722. return this;
  10723. };
  10724. return EventState;
  10725. }());
  10726. BABYLON.EventState = EventState;
  10727. /**
  10728. * Represent an Observer registered to a given Observable object.
  10729. */
  10730. var Observer = /** @class */ (function () {
  10731. /**
  10732. * Creates a new observer
  10733. * @param callback defines the callback to call when the observer is notified
  10734. * @param mask defines the mask of the observer (used to filter notifications)
  10735. * @param scope defines the current scope used to restore the JS context
  10736. */
  10737. function Observer(
  10738. /**
  10739. * Defines the callback to call when the observer is notified
  10740. */
  10741. callback,
  10742. /**
  10743. * Defines the mask of the observer (used to filter notifications)
  10744. */
  10745. mask,
  10746. /**
  10747. * Defines the current scope used to restore the JS context
  10748. */
  10749. scope) {
  10750. if (scope === void 0) { scope = null; }
  10751. this.callback = callback;
  10752. this.mask = mask;
  10753. this.scope = scope;
  10754. /** @hidden */
  10755. this._willBeUnregistered = false;
  10756. /**
  10757. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10758. */
  10759. this.unregisterOnNextCall = false;
  10760. }
  10761. return Observer;
  10762. }());
  10763. BABYLON.Observer = Observer;
  10764. /**
  10765. * Represent a list of observers registered to multiple Observables object.
  10766. */
  10767. var MultiObserver = /** @class */ (function () {
  10768. function MultiObserver() {
  10769. }
  10770. /**
  10771. * Release associated resources
  10772. */
  10773. MultiObserver.prototype.dispose = function () {
  10774. if (this._observers && this._observables) {
  10775. for (var index = 0; index < this._observers.length; index++) {
  10776. this._observables[index].remove(this._observers[index]);
  10777. }
  10778. }
  10779. this._observers = null;
  10780. this._observables = null;
  10781. };
  10782. /**
  10783. * Raise a callback when one of the observable will notify
  10784. * @param observables defines a list of observables to watch
  10785. * @param callback defines the callback to call on notification
  10786. * @param mask defines the mask used to filter notifications
  10787. * @param scope defines the current scope used to restore the JS context
  10788. * @returns the new MultiObserver
  10789. */
  10790. MultiObserver.Watch = function (observables, callback, mask, scope) {
  10791. if (mask === void 0) { mask = -1; }
  10792. if (scope === void 0) { scope = null; }
  10793. var result = new MultiObserver();
  10794. result._observers = new Array();
  10795. result._observables = observables;
  10796. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  10797. var observable = observables_1[_i];
  10798. var observer = observable.add(callback, mask, false, scope);
  10799. if (observer) {
  10800. result._observers.push(observer);
  10801. }
  10802. }
  10803. return result;
  10804. };
  10805. return MultiObserver;
  10806. }());
  10807. BABYLON.MultiObserver = MultiObserver;
  10808. /**
  10809. * The Observable class is a simple implementation of the Observable pattern.
  10810. *
  10811. * 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.
  10812. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  10813. * 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).
  10814. * 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.
  10815. */
  10816. var Observable = /** @class */ (function () {
  10817. /**
  10818. * Creates a new observable
  10819. * @param onObserverAdded defines a callback to call when a new observer is added
  10820. */
  10821. function Observable(onObserverAdded) {
  10822. this._observers = new Array();
  10823. this._eventState = new EventState(0);
  10824. if (onObserverAdded) {
  10825. this._onObserverAdded = onObserverAdded;
  10826. }
  10827. }
  10828. /**
  10829. * Create a new Observer with the specified callback
  10830. * @param callback the callback that will be executed for that Observer
  10831. * @param mask the mask used to filter observers
  10832. * @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.
  10833. * @param scope optional scope for the callback to be called from
  10834. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  10835. * @returns the new observer created for the callback
  10836. */
  10837. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  10838. if (mask === void 0) { mask = -1; }
  10839. if (insertFirst === void 0) { insertFirst = false; }
  10840. if (scope === void 0) { scope = null; }
  10841. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  10842. if (!callback) {
  10843. return null;
  10844. }
  10845. var observer = new Observer(callback, mask, scope);
  10846. observer.unregisterOnNextCall = unregisterOnFirstCall;
  10847. if (insertFirst) {
  10848. this._observers.unshift(observer);
  10849. }
  10850. else {
  10851. this._observers.push(observer);
  10852. }
  10853. if (this._onObserverAdded) {
  10854. this._onObserverAdded(observer);
  10855. }
  10856. return observer;
  10857. };
  10858. /**
  10859. * Create a new Observer with the specified callback and unregisters after the next notification
  10860. * @param callback the callback that will be executed for that Observer
  10861. * @returns the new observer created for the callback
  10862. */
  10863. Observable.prototype.addOnce = function (callback) {
  10864. return this.add(callback, undefined, undefined, undefined, true);
  10865. };
  10866. /**
  10867. * Remove an Observer from the Observable object
  10868. * @param observer the instance of the Observer to remove
  10869. * @returns false if it doesn't belong to this Observable
  10870. */
  10871. Observable.prototype.remove = function (observer) {
  10872. if (!observer) {
  10873. return false;
  10874. }
  10875. var index = this._observers.indexOf(observer);
  10876. if (index !== -1) {
  10877. this._deferUnregister(observer);
  10878. return true;
  10879. }
  10880. return false;
  10881. };
  10882. /**
  10883. * Remove a callback from the Observable object
  10884. * @param callback the callback to remove
  10885. * @param scope optional scope. If used only the callbacks with this scope will be removed
  10886. * @returns false if it doesn't belong to this Observable
  10887. */
  10888. Observable.prototype.removeCallback = function (callback, scope) {
  10889. for (var index = 0; index < this._observers.length; index++) {
  10890. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  10891. this._deferUnregister(this._observers[index]);
  10892. return true;
  10893. }
  10894. }
  10895. return false;
  10896. };
  10897. Observable.prototype._deferUnregister = function (observer) {
  10898. var _this = this;
  10899. observer.unregisterOnNextCall = false;
  10900. observer._willBeUnregistered = true;
  10901. BABYLON.Tools.SetImmediate(function () {
  10902. _this._remove(observer);
  10903. });
  10904. };
  10905. // This should only be called when not iterating over _observers to avoid callback skipping.
  10906. // Removes an observer from the _observer Array.
  10907. Observable.prototype._remove = function (observer) {
  10908. if (!observer) {
  10909. return false;
  10910. }
  10911. var index = this._observers.indexOf(observer);
  10912. if (index !== -1) {
  10913. this._observers.splice(index, 1);
  10914. return true;
  10915. }
  10916. return false;
  10917. };
  10918. /**
  10919. * Notify all Observers by calling their respective callback with the given data
  10920. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  10921. * @param eventData defines the data to send to all observers
  10922. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  10923. * @param target defines the original target of the state
  10924. * @param currentTarget defines the current target of the state
  10925. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  10926. */
  10927. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  10928. if (mask === void 0) { mask = -1; }
  10929. if (!this._observers.length) {
  10930. return true;
  10931. }
  10932. var state = this._eventState;
  10933. state.mask = mask;
  10934. state.target = target;
  10935. state.currentTarget = currentTarget;
  10936. state.skipNextObservers = false;
  10937. state.lastReturnValue = eventData;
  10938. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  10939. var obs = _a[_i];
  10940. if (obs._willBeUnregistered) {
  10941. continue;
  10942. }
  10943. if (obs.mask & mask) {
  10944. if (obs.scope) {
  10945. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  10946. }
  10947. else {
  10948. state.lastReturnValue = obs.callback(eventData, state);
  10949. }
  10950. if (obs.unregisterOnNextCall) {
  10951. this._deferUnregister(obs);
  10952. }
  10953. }
  10954. if (state.skipNextObservers) {
  10955. return false;
  10956. }
  10957. }
  10958. return true;
  10959. };
  10960. /**
  10961. * Calling this will execute each callback, expecting it to be a promise or return a value.
  10962. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  10963. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  10964. * and it is crucial that all callbacks will be executed.
  10965. * The order of the callbacks is kept, callbacks are not executed parallel.
  10966. *
  10967. * @param eventData The data to be sent to each callback
  10968. * @param mask is used to filter observers defaults to -1
  10969. * @param target defines the callback target (see EventState)
  10970. * @param currentTarget defines he current object in the bubbling phase
  10971. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  10972. */
  10973. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  10974. var _this = this;
  10975. if (mask === void 0) { mask = -1; }
  10976. // create an empty promise
  10977. var p = Promise.resolve(eventData);
  10978. // no observers? return this promise.
  10979. if (!this._observers.length) {
  10980. return p;
  10981. }
  10982. var state = this._eventState;
  10983. state.mask = mask;
  10984. state.target = target;
  10985. state.currentTarget = currentTarget;
  10986. state.skipNextObservers = false;
  10987. // execute one callback after another (not using Promise.all, the order is important)
  10988. this._observers.forEach(function (obs) {
  10989. if (state.skipNextObservers) {
  10990. return;
  10991. }
  10992. if (obs._willBeUnregistered) {
  10993. return;
  10994. }
  10995. if (obs.mask & mask) {
  10996. if (obs.scope) {
  10997. p = p.then(function (lastReturnedValue) {
  10998. state.lastReturnValue = lastReturnedValue;
  10999. return obs.callback.apply(obs.scope, [eventData, state]);
  11000. });
  11001. }
  11002. else {
  11003. p = p.then(function (lastReturnedValue) {
  11004. state.lastReturnValue = lastReturnedValue;
  11005. return obs.callback(eventData, state);
  11006. });
  11007. }
  11008. if (obs.unregisterOnNextCall) {
  11009. _this._deferUnregister(obs);
  11010. }
  11011. }
  11012. });
  11013. // return the eventData
  11014. return p.then(function () { return eventData; });
  11015. };
  11016. /**
  11017. * Notify a specific observer
  11018. * @param observer defines the observer to notify
  11019. * @param eventData defines the data to be sent to each callback
  11020. * @param mask is used to filter observers defaults to -1
  11021. */
  11022. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11023. if (mask === void 0) { mask = -1; }
  11024. var state = this._eventState;
  11025. state.mask = mask;
  11026. state.skipNextObservers = false;
  11027. observer.callback(eventData, state);
  11028. };
  11029. /**
  11030. * Gets a boolean indicating if the observable has at least one observer
  11031. * @returns true is the Observable has at least one Observer registered
  11032. */
  11033. Observable.prototype.hasObservers = function () {
  11034. return this._observers.length > 0;
  11035. };
  11036. /**
  11037. * Clear the list of observers
  11038. */
  11039. Observable.prototype.clear = function () {
  11040. this._observers = new Array();
  11041. this._onObserverAdded = null;
  11042. };
  11043. /**
  11044. * Clone the current observable
  11045. * @returns a new observable
  11046. */
  11047. Observable.prototype.clone = function () {
  11048. var result = new Observable();
  11049. result._observers = this._observers.slice(0);
  11050. return result;
  11051. };
  11052. /**
  11053. * Does this observable handles observer registered with a given mask
  11054. * @param mask defines the mask to be tested
  11055. * @return whether or not one observer registered with the given mask is handeled
  11056. **/
  11057. Observable.prototype.hasSpecificMask = function (mask) {
  11058. if (mask === void 0) { mask = -1; }
  11059. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11060. var obs = _a[_i];
  11061. if (obs.mask & mask || obs.mask === mask) {
  11062. return true;
  11063. }
  11064. }
  11065. return false;
  11066. };
  11067. return Observable;
  11068. }());
  11069. BABYLON.Observable = Observable;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.observable.js.map
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. /**
  11075. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11076. */
  11077. var SmartArray = /** @class */ (function () {
  11078. /**
  11079. * Instantiates a Smart Array.
  11080. * @param capacity defines the default capacity of the array.
  11081. */
  11082. function SmartArray(capacity) {
  11083. /**
  11084. * The active length of the array.
  11085. */
  11086. this.length = 0;
  11087. this.data = new Array(capacity);
  11088. this._id = SmartArray._GlobalId++;
  11089. }
  11090. /**
  11091. * Pushes a value at the end of the active data.
  11092. * @param value defines the object to push in the array.
  11093. */
  11094. SmartArray.prototype.push = function (value) {
  11095. this.data[this.length++] = value;
  11096. if (this.length > this.data.length) {
  11097. this.data.length *= 2;
  11098. }
  11099. };
  11100. /**
  11101. * Iterates over the active data and apply the lambda to them.
  11102. * @param func defines the action to apply on each value.
  11103. */
  11104. SmartArray.prototype.forEach = function (func) {
  11105. for (var index = 0; index < this.length; index++) {
  11106. func(this.data[index]);
  11107. }
  11108. };
  11109. /**
  11110. * Sorts the full sets of data.
  11111. * @param compareFn defines the comparison function to apply.
  11112. */
  11113. SmartArray.prototype.sort = function (compareFn) {
  11114. this.data.sort(compareFn);
  11115. };
  11116. /**
  11117. * Resets the active data to an empty array.
  11118. */
  11119. SmartArray.prototype.reset = function () {
  11120. this.length = 0;
  11121. };
  11122. /**
  11123. * Releases all the data from the array as well as the array.
  11124. */
  11125. SmartArray.prototype.dispose = function () {
  11126. this.reset();
  11127. if (this.data) {
  11128. this.data.length = 0;
  11129. this.data = [];
  11130. }
  11131. };
  11132. /**
  11133. * Concats the active data with a given array.
  11134. * @param array defines the data to concatenate with.
  11135. */
  11136. SmartArray.prototype.concat = function (array) {
  11137. if (array.length === 0) {
  11138. return;
  11139. }
  11140. if (this.length + array.length > this.data.length) {
  11141. this.data.length = (this.length + array.length) * 2;
  11142. }
  11143. for (var index = 0; index < array.length; index++) {
  11144. this.data[this.length++] = (array.data || array)[index];
  11145. }
  11146. };
  11147. /**
  11148. * Returns the position of a value in the active data.
  11149. * @param value defines the value to find the index for
  11150. * @returns the index if found in the active data otherwise -1
  11151. */
  11152. SmartArray.prototype.indexOf = function (value) {
  11153. var position = this.data.indexOf(value);
  11154. if (position >= this.length) {
  11155. return -1;
  11156. }
  11157. return position;
  11158. };
  11159. /**
  11160. * Returns whether an element is part of the active data.
  11161. * @param value defines the value to look for
  11162. * @returns true if found in the active data otherwise false
  11163. */
  11164. SmartArray.prototype.contains = function (value) {
  11165. return this.indexOf(value) !== -1;
  11166. };
  11167. // Statics
  11168. SmartArray._GlobalId = 0;
  11169. return SmartArray;
  11170. }());
  11171. BABYLON.SmartArray = SmartArray;
  11172. /**
  11173. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11174. * The data in this array can only be present once
  11175. */
  11176. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11177. __extends(SmartArrayNoDuplicate, _super);
  11178. function SmartArrayNoDuplicate() {
  11179. var _this = _super !== null && _super.apply(this, arguments) || this;
  11180. _this._duplicateId = 0;
  11181. return _this;
  11182. }
  11183. /**
  11184. * Pushes a value at the end of the active data.
  11185. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11186. * @param value defines the object to push in the array.
  11187. */
  11188. SmartArrayNoDuplicate.prototype.push = function (value) {
  11189. _super.prototype.push.call(this, value);
  11190. if (!value.__smartArrayFlags) {
  11191. value.__smartArrayFlags = {};
  11192. }
  11193. value.__smartArrayFlags[this._id] = this._duplicateId;
  11194. };
  11195. /**
  11196. * Pushes a value at the end of the active data.
  11197. * If the data is already present, it won t be added again
  11198. * @param value defines the object to push in the array.
  11199. * @returns true if added false if it was already present
  11200. */
  11201. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11202. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11203. return false;
  11204. }
  11205. this.push(value);
  11206. return true;
  11207. };
  11208. /**
  11209. * Resets the active data to an empty array.
  11210. */
  11211. SmartArrayNoDuplicate.prototype.reset = function () {
  11212. _super.prototype.reset.call(this);
  11213. this._duplicateId++;
  11214. };
  11215. /**
  11216. * Concats the active data with a given array.
  11217. * This ensures no dupplicate will be present in the result.
  11218. * @param array defines the data to concatenate with.
  11219. */
  11220. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11221. if (array.length === 0) {
  11222. return;
  11223. }
  11224. if (this.length + array.length > this.data.length) {
  11225. this.data.length = (this.length + array.length) * 2;
  11226. }
  11227. for (var index = 0; index < array.length; index++) {
  11228. var item = (array.data || array)[index];
  11229. this.pushNoDuplicate(item);
  11230. }
  11231. };
  11232. return SmartArrayNoDuplicate;
  11233. }(SmartArray));
  11234. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11235. })(BABYLON || (BABYLON = {}));
  11236. //# sourceMappingURL=babylon.smartArray.js.map
  11237. var BABYLON;
  11238. (function (BABYLON) {
  11239. var PromiseStates;
  11240. (function (PromiseStates) {
  11241. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11242. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11243. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11244. })(PromiseStates || (PromiseStates = {}));
  11245. var FulFillmentAgregator = /** @class */ (function () {
  11246. function FulFillmentAgregator() {
  11247. this.count = 0;
  11248. this.target = 0;
  11249. this.results = [];
  11250. }
  11251. return FulFillmentAgregator;
  11252. }());
  11253. var InternalPromise = /** @class */ (function () {
  11254. function InternalPromise(resolver) {
  11255. var _this = this;
  11256. this._state = PromiseStates.Pending;
  11257. this._children = new Array();
  11258. this._rejectWasConsumed = false;
  11259. if (!resolver) {
  11260. return;
  11261. }
  11262. try {
  11263. resolver(function (value) {
  11264. _this._resolve(value);
  11265. }, function (reason) {
  11266. _this._reject(reason);
  11267. });
  11268. }
  11269. catch (e) {
  11270. this._reject(e);
  11271. }
  11272. }
  11273. Object.defineProperty(InternalPromise.prototype, "_result", {
  11274. get: function () {
  11275. return this._resultValue;
  11276. },
  11277. set: function (value) {
  11278. this._resultValue = value;
  11279. if (this._parent && this._parent._result === undefined) {
  11280. this._parent._result = value;
  11281. }
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. InternalPromise.prototype.catch = function (onRejected) {
  11287. return this.then(undefined, onRejected);
  11288. };
  11289. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11290. var _this = this;
  11291. var newPromise = new InternalPromise();
  11292. newPromise._onFulfilled = onFulfilled;
  11293. newPromise._onRejected = onRejected;
  11294. // Composition
  11295. this._children.push(newPromise);
  11296. newPromise._parent = this;
  11297. if (this._state !== PromiseStates.Pending) {
  11298. BABYLON.Tools.SetImmediate(function () {
  11299. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11300. var returnedValue = newPromise._resolve(_this._result);
  11301. if (returnedValue !== undefined && returnedValue !== null) {
  11302. if (returnedValue._state !== undefined) {
  11303. var returnedPromise = returnedValue;
  11304. newPromise._children.push(returnedPromise);
  11305. returnedPromise._parent = newPromise;
  11306. newPromise = returnedPromise;
  11307. }
  11308. else {
  11309. newPromise._result = returnedValue;
  11310. }
  11311. }
  11312. }
  11313. else {
  11314. newPromise._reject(_this._reason);
  11315. }
  11316. });
  11317. }
  11318. return newPromise;
  11319. };
  11320. InternalPromise.prototype._moveChildren = function (children) {
  11321. var _this = this;
  11322. var _a;
  11323. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11324. this._children.forEach(function (child) {
  11325. child._parent = _this;
  11326. });
  11327. if (this._state === PromiseStates.Fulfilled) {
  11328. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11329. var child = _b[_i];
  11330. child._resolve(this._result);
  11331. }
  11332. }
  11333. else if (this._state === PromiseStates.Rejected) {
  11334. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11335. var child = _d[_c];
  11336. child._reject(this._reason);
  11337. }
  11338. }
  11339. };
  11340. InternalPromise.prototype._resolve = function (value) {
  11341. try {
  11342. this._state = PromiseStates.Fulfilled;
  11343. var returnedValue = null;
  11344. if (this._onFulfilled) {
  11345. returnedValue = this._onFulfilled(value);
  11346. }
  11347. if (returnedValue !== undefined && returnedValue !== null) {
  11348. if (returnedValue._state !== undefined) {
  11349. // Transmit children
  11350. var returnedPromise = returnedValue;
  11351. returnedPromise._parent = this;
  11352. returnedPromise._moveChildren(this._children);
  11353. value = returnedPromise._result;
  11354. }
  11355. else {
  11356. value = returnedValue;
  11357. }
  11358. }
  11359. this._result = value;
  11360. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11361. var child = _a[_i];
  11362. child._resolve(value);
  11363. }
  11364. this._children.length = 0;
  11365. delete this._onFulfilled;
  11366. delete this._onRejected;
  11367. }
  11368. catch (e) {
  11369. this._reject(e, true);
  11370. }
  11371. };
  11372. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11373. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11374. this._state = PromiseStates.Rejected;
  11375. this._reason = reason;
  11376. if (this._onRejected && !onLocalThrow) {
  11377. try {
  11378. this._onRejected(reason);
  11379. this._rejectWasConsumed = true;
  11380. }
  11381. catch (e) {
  11382. reason = e;
  11383. }
  11384. }
  11385. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11386. var child = _a[_i];
  11387. if (this._rejectWasConsumed) {
  11388. child._resolve(null);
  11389. }
  11390. else {
  11391. child._reject(reason);
  11392. }
  11393. }
  11394. this._children.length = 0;
  11395. delete this._onFulfilled;
  11396. delete this._onRejected;
  11397. };
  11398. InternalPromise.resolve = function (value) {
  11399. var newPromise = new InternalPromise();
  11400. newPromise._resolve(value);
  11401. return newPromise;
  11402. };
  11403. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11404. promise.then(function (value) {
  11405. agregator.results[index] = value;
  11406. agregator.count++;
  11407. if (agregator.count === agregator.target) {
  11408. agregator.rootPromise._resolve(agregator.results);
  11409. }
  11410. return null;
  11411. }, function (reason) {
  11412. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11413. agregator.rootPromise._reject(reason);
  11414. }
  11415. });
  11416. };
  11417. InternalPromise.all = function (promises) {
  11418. var newPromise = new InternalPromise();
  11419. var agregator = new FulFillmentAgregator();
  11420. agregator.target = promises.length;
  11421. agregator.rootPromise = newPromise;
  11422. if (promises.length) {
  11423. for (var index = 0; index < promises.length; index++) {
  11424. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11425. }
  11426. }
  11427. else {
  11428. newPromise._resolve([]);
  11429. }
  11430. return newPromise;
  11431. };
  11432. InternalPromise.race = function (promises) {
  11433. var newPromise = new InternalPromise();
  11434. if (promises.length) {
  11435. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11436. var promise = promises_1[_i];
  11437. promise.then(function (value) {
  11438. if (newPromise) {
  11439. newPromise._resolve(value);
  11440. newPromise = null;
  11441. }
  11442. return null;
  11443. }, function (reason) {
  11444. if (newPromise) {
  11445. newPromise._reject(reason);
  11446. newPromise = null;
  11447. }
  11448. });
  11449. }
  11450. }
  11451. return newPromise;
  11452. };
  11453. return InternalPromise;
  11454. }());
  11455. /**
  11456. * Helper class that provides a small promise polyfill
  11457. */
  11458. var PromisePolyfill = /** @class */ (function () {
  11459. function PromisePolyfill() {
  11460. }
  11461. /**
  11462. * Static function used to check if the polyfill is required
  11463. * If this is the case then the function will inject the polyfill to window.Promise
  11464. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11465. */
  11466. PromisePolyfill.Apply = function (force) {
  11467. if (force === void 0) { force = false; }
  11468. if (force || typeof Promise === 'undefined') {
  11469. var root = window;
  11470. root.Promise = InternalPromise;
  11471. }
  11472. };
  11473. return PromisePolyfill;
  11474. }());
  11475. BABYLON.PromisePolyfill = PromisePolyfill;
  11476. })(BABYLON || (BABYLON = {}));
  11477. //# sourceMappingURL=babylon.promise.js.map
  11478. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11479. var BABYLON;
  11480. (function (BABYLON) {
  11481. /**
  11482. * Helper class to push actions to a pool of workers.
  11483. */
  11484. var WorkerPool = /** @class */ (function () {
  11485. /**
  11486. * Constructor
  11487. * @param workers Array of workers to use for actions
  11488. */
  11489. function WorkerPool(workers) {
  11490. this._pendingActions = new Array();
  11491. this._workerInfos = workers.map(function (worker) { return ({
  11492. worker: worker,
  11493. active: false
  11494. }); });
  11495. }
  11496. /**
  11497. * Terminates all workers and clears any pending actions.
  11498. */
  11499. WorkerPool.prototype.dispose = function () {
  11500. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11501. var workerInfo = _a[_i];
  11502. workerInfo.worker.terminate();
  11503. }
  11504. delete this._workerInfos;
  11505. delete this._pendingActions;
  11506. };
  11507. /**
  11508. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11509. * pended until a worker has completed its action.
  11510. * @param action The action to perform. Call onComplete when the action is complete.
  11511. */
  11512. WorkerPool.prototype.push = function (action) {
  11513. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11514. var workerInfo = _a[_i];
  11515. if (!workerInfo.active) {
  11516. this._execute(workerInfo, action);
  11517. return;
  11518. }
  11519. }
  11520. this._pendingActions.push(action);
  11521. };
  11522. WorkerPool.prototype._execute = function (workerInfo, action) {
  11523. var _this = this;
  11524. workerInfo.active = true;
  11525. action(workerInfo.worker, function () {
  11526. workerInfo.active = false;
  11527. var nextAction = _this._pendingActions.shift();
  11528. if (nextAction) {
  11529. _this._execute(workerInfo, nextAction);
  11530. }
  11531. });
  11532. };
  11533. return WorkerPool;
  11534. }());
  11535. BABYLON.WorkerPool = WorkerPool;
  11536. })(BABYLON || (BABYLON = {}));
  11537. //# sourceMappingURL=babylon.workerPool.js.map
  11538. var BABYLON;
  11539. (function (BABYLON) {
  11540. /**
  11541. * @hidden
  11542. **/
  11543. var _AlphaState = /** @class */ (function () {
  11544. /**
  11545. * Initializes the state.
  11546. */
  11547. function _AlphaState() {
  11548. this._isAlphaBlendDirty = false;
  11549. this._isBlendFunctionParametersDirty = false;
  11550. this._isBlendEquationParametersDirty = false;
  11551. this._isBlendConstantsDirty = false;
  11552. this._alphaBlend = false;
  11553. this._blendFunctionParameters = new Array(4);
  11554. this._blendEquationParameters = new Array(2);
  11555. this._blendConstants = new Array(4);
  11556. this.reset();
  11557. }
  11558. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11559. get: function () {
  11560. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11561. },
  11562. enumerable: true,
  11563. configurable: true
  11564. });
  11565. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11566. get: function () {
  11567. return this._alphaBlend;
  11568. },
  11569. set: function (value) {
  11570. if (this._alphaBlend === value) {
  11571. return;
  11572. }
  11573. this._alphaBlend = value;
  11574. this._isAlphaBlendDirty = true;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11580. if (this._blendConstants[0] === r &&
  11581. this._blendConstants[1] === g &&
  11582. this._blendConstants[2] === b &&
  11583. this._blendConstants[3] === a) {
  11584. return;
  11585. }
  11586. this._blendConstants[0] = r;
  11587. this._blendConstants[1] = g;
  11588. this._blendConstants[2] = b;
  11589. this._blendConstants[3] = a;
  11590. this._isBlendConstantsDirty = true;
  11591. };
  11592. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11593. if (this._blendFunctionParameters[0] === value0 &&
  11594. this._blendFunctionParameters[1] === value1 &&
  11595. this._blendFunctionParameters[2] === value2 &&
  11596. this._blendFunctionParameters[3] === value3) {
  11597. return;
  11598. }
  11599. this._blendFunctionParameters[0] = value0;
  11600. this._blendFunctionParameters[1] = value1;
  11601. this._blendFunctionParameters[2] = value2;
  11602. this._blendFunctionParameters[3] = value3;
  11603. this._isBlendFunctionParametersDirty = true;
  11604. };
  11605. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11606. if (this._blendEquationParameters[0] === rgb &&
  11607. this._blendEquationParameters[1] === alpha) {
  11608. return;
  11609. }
  11610. this._blendEquationParameters[0] = rgb;
  11611. this._blendEquationParameters[1] = alpha;
  11612. this._isBlendEquationParametersDirty = true;
  11613. };
  11614. _AlphaState.prototype.reset = function () {
  11615. this._alphaBlend = false;
  11616. this._blendFunctionParameters[0] = null;
  11617. this._blendFunctionParameters[1] = null;
  11618. this._blendFunctionParameters[2] = null;
  11619. this._blendFunctionParameters[3] = null;
  11620. this._blendEquationParameters[0] = null;
  11621. this._blendEquationParameters[1] = null;
  11622. this._blendConstants[0] = null;
  11623. this._blendConstants[1] = null;
  11624. this._blendConstants[2] = null;
  11625. this._blendConstants[3] = null;
  11626. this._isAlphaBlendDirty = true;
  11627. this._isBlendFunctionParametersDirty = false;
  11628. this._isBlendEquationParametersDirty = false;
  11629. this._isBlendConstantsDirty = false;
  11630. };
  11631. _AlphaState.prototype.apply = function (gl) {
  11632. if (!this.isDirty) {
  11633. return;
  11634. }
  11635. // Alpha blend
  11636. if (this._isAlphaBlendDirty) {
  11637. if (this._alphaBlend) {
  11638. gl.enable(gl.BLEND);
  11639. }
  11640. else {
  11641. gl.disable(gl.BLEND);
  11642. }
  11643. this._isAlphaBlendDirty = false;
  11644. }
  11645. // Alpha function
  11646. if (this._isBlendFunctionParametersDirty) {
  11647. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11648. this._isBlendFunctionParametersDirty = false;
  11649. }
  11650. // Alpha equation
  11651. if (this._isBlendEquationParametersDirty) {
  11652. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11653. this._isBlendEquationParametersDirty = false;
  11654. }
  11655. // Constants
  11656. if (this._isBlendConstantsDirty) {
  11657. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11658. this._isBlendConstantsDirty = false;
  11659. }
  11660. };
  11661. return _AlphaState;
  11662. }());
  11663. BABYLON._AlphaState = _AlphaState;
  11664. })(BABYLON || (BABYLON = {}));
  11665. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11666. var BABYLON;
  11667. (function (BABYLON) {
  11668. /**
  11669. * @hidden
  11670. **/
  11671. var _DepthCullingState = /** @class */ (function () {
  11672. /**
  11673. * Initializes the state.
  11674. */
  11675. function _DepthCullingState() {
  11676. this._isDepthTestDirty = false;
  11677. this._isDepthMaskDirty = false;
  11678. this._isDepthFuncDirty = false;
  11679. this._isCullFaceDirty = false;
  11680. this._isCullDirty = false;
  11681. this._isZOffsetDirty = false;
  11682. this._isFrontFaceDirty = false;
  11683. this.reset();
  11684. }
  11685. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11686. get: function () {
  11687. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11693. get: function () {
  11694. return this._zOffset;
  11695. },
  11696. set: function (value) {
  11697. if (this._zOffset === value) {
  11698. return;
  11699. }
  11700. this._zOffset = value;
  11701. this._isZOffsetDirty = true;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11707. get: function () {
  11708. return this._cullFace;
  11709. },
  11710. set: function (value) {
  11711. if (this._cullFace === value) {
  11712. return;
  11713. }
  11714. this._cullFace = value;
  11715. this._isCullFaceDirty = true;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11721. get: function () {
  11722. return this._cull;
  11723. },
  11724. set: function (value) {
  11725. if (this._cull === value) {
  11726. return;
  11727. }
  11728. this._cull = value;
  11729. this._isCullDirty = true;
  11730. },
  11731. enumerable: true,
  11732. configurable: true
  11733. });
  11734. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11735. get: function () {
  11736. return this._depthFunc;
  11737. },
  11738. set: function (value) {
  11739. if (this._depthFunc === value) {
  11740. return;
  11741. }
  11742. this._depthFunc = value;
  11743. this._isDepthFuncDirty = true;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11749. get: function () {
  11750. return this._depthMask;
  11751. },
  11752. set: function (value) {
  11753. if (this._depthMask === value) {
  11754. return;
  11755. }
  11756. this._depthMask = value;
  11757. this._isDepthMaskDirty = true;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11763. get: function () {
  11764. return this._depthTest;
  11765. },
  11766. set: function (value) {
  11767. if (this._depthTest === value) {
  11768. return;
  11769. }
  11770. this._depthTest = value;
  11771. this._isDepthTestDirty = true;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11777. get: function () {
  11778. return this._frontFace;
  11779. },
  11780. set: function (value) {
  11781. if (this._frontFace === value) {
  11782. return;
  11783. }
  11784. this._frontFace = value;
  11785. this._isFrontFaceDirty = true;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. _DepthCullingState.prototype.reset = function () {
  11791. this._depthMask = true;
  11792. this._depthTest = true;
  11793. this._depthFunc = null;
  11794. this._cullFace = null;
  11795. this._cull = null;
  11796. this._zOffset = 0;
  11797. this._frontFace = null;
  11798. this._isDepthTestDirty = true;
  11799. this._isDepthMaskDirty = true;
  11800. this._isDepthFuncDirty = false;
  11801. this._isCullFaceDirty = false;
  11802. this._isCullDirty = false;
  11803. this._isZOffsetDirty = false;
  11804. this._isFrontFaceDirty = false;
  11805. };
  11806. _DepthCullingState.prototype.apply = function (gl) {
  11807. if (!this.isDirty) {
  11808. return;
  11809. }
  11810. // Cull
  11811. if (this._isCullDirty) {
  11812. if (this.cull) {
  11813. gl.enable(gl.CULL_FACE);
  11814. }
  11815. else {
  11816. gl.disable(gl.CULL_FACE);
  11817. }
  11818. this._isCullDirty = false;
  11819. }
  11820. // Cull face
  11821. if (this._isCullFaceDirty) {
  11822. gl.cullFace(this.cullFace);
  11823. this._isCullFaceDirty = false;
  11824. }
  11825. // Depth mask
  11826. if (this._isDepthMaskDirty) {
  11827. gl.depthMask(this.depthMask);
  11828. this._isDepthMaskDirty = false;
  11829. }
  11830. // Depth test
  11831. if (this._isDepthTestDirty) {
  11832. if (this.depthTest) {
  11833. gl.enable(gl.DEPTH_TEST);
  11834. }
  11835. else {
  11836. gl.disable(gl.DEPTH_TEST);
  11837. }
  11838. this._isDepthTestDirty = false;
  11839. }
  11840. // Depth func
  11841. if (this._isDepthFuncDirty) {
  11842. gl.depthFunc(this.depthFunc);
  11843. this._isDepthFuncDirty = false;
  11844. }
  11845. // zOffset
  11846. if (this._isZOffsetDirty) {
  11847. if (this.zOffset) {
  11848. gl.enable(gl.POLYGON_OFFSET_FILL);
  11849. gl.polygonOffset(this.zOffset, 0);
  11850. }
  11851. else {
  11852. gl.disable(gl.POLYGON_OFFSET_FILL);
  11853. }
  11854. this._isZOffsetDirty = false;
  11855. }
  11856. // Front face
  11857. if (this._isFrontFaceDirty) {
  11858. gl.frontFace(this.frontFace);
  11859. this._isFrontFaceDirty = false;
  11860. }
  11861. };
  11862. return _DepthCullingState;
  11863. }());
  11864. BABYLON._DepthCullingState = _DepthCullingState;
  11865. })(BABYLON || (BABYLON = {}));
  11866. //# sourceMappingURL=babylon.depthCullingState.js.map
  11867. var BABYLON;
  11868. (function (BABYLON) {
  11869. /**
  11870. * @hidden
  11871. **/
  11872. var _StencilState = /** @class */ (function () {
  11873. function _StencilState() {
  11874. this._isStencilTestDirty = false;
  11875. this._isStencilMaskDirty = false;
  11876. this._isStencilFuncDirty = false;
  11877. this._isStencilOpDirty = false;
  11878. this.reset();
  11879. }
  11880. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11881. get: function () {
  11882. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11888. get: function () {
  11889. return this._stencilFunc;
  11890. },
  11891. set: function (value) {
  11892. if (this._stencilFunc === value) {
  11893. return;
  11894. }
  11895. this._stencilFunc = value;
  11896. this._isStencilFuncDirty = true;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11902. get: function () {
  11903. return this._stencilFuncRef;
  11904. },
  11905. set: function (value) {
  11906. if (this._stencilFuncRef === value) {
  11907. return;
  11908. }
  11909. this._stencilFuncRef = value;
  11910. this._isStencilFuncDirty = true;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11916. get: function () {
  11917. return this._stencilFuncMask;
  11918. },
  11919. set: function (value) {
  11920. if (this._stencilFuncMask === value) {
  11921. return;
  11922. }
  11923. this._stencilFuncMask = value;
  11924. this._isStencilFuncDirty = true;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11930. get: function () {
  11931. return this._stencilOpStencilFail;
  11932. },
  11933. set: function (value) {
  11934. if (this._stencilOpStencilFail === value) {
  11935. return;
  11936. }
  11937. this._stencilOpStencilFail = value;
  11938. this._isStencilOpDirty = true;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11944. get: function () {
  11945. return this._stencilOpDepthFail;
  11946. },
  11947. set: function (value) {
  11948. if (this._stencilOpDepthFail === value) {
  11949. return;
  11950. }
  11951. this._stencilOpDepthFail = value;
  11952. this._isStencilOpDirty = true;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11958. get: function () {
  11959. return this._stencilOpStencilDepthPass;
  11960. },
  11961. set: function (value) {
  11962. if (this._stencilOpStencilDepthPass === value) {
  11963. return;
  11964. }
  11965. this._stencilOpStencilDepthPass = value;
  11966. this._isStencilOpDirty = true;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11972. get: function () {
  11973. return this._stencilMask;
  11974. },
  11975. set: function (value) {
  11976. if (this._stencilMask === value) {
  11977. return;
  11978. }
  11979. this._stencilMask = value;
  11980. this._isStencilMaskDirty = true;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11986. get: function () {
  11987. return this._stencilTest;
  11988. },
  11989. set: function (value) {
  11990. if (this._stencilTest === value) {
  11991. return;
  11992. }
  11993. this._stencilTest = value;
  11994. this._isStencilTestDirty = true;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. _StencilState.prototype.reset = function () {
  12000. this._stencilTest = false;
  12001. this._stencilMask = 0xFF;
  12002. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12003. this._stencilFuncRef = 1;
  12004. this._stencilFuncMask = 0xFF;
  12005. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12006. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12007. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12008. this._isStencilTestDirty = true;
  12009. this._isStencilMaskDirty = true;
  12010. this._isStencilFuncDirty = true;
  12011. this._isStencilOpDirty = true;
  12012. };
  12013. _StencilState.prototype.apply = function (gl) {
  12014. if (!this.isDirty) {
  12015. return;
  12016. }
  12017. // Stencil test
  12018. if (this._isStencilTestDirty) {
  12019. if (this.stencilTest) {
  12020. gl.enable(gl.STENCIL_TEST);
  12021. }
  12022. else {
  12023. gl.disable(gl.STENCIL_TEST);
  12024. }
  12025. this._isStencilTestDirty = false;
  12026. }
  12027. // Stencil mask
  12028. if (this._isStencilMaskDirty) {
  12029. gl.stencilMask(this.stencilMask);
  12030. this._isStencilMaskDirty = false;
  12031. }
  12032. // Stencil func
  12033. if (this._isStencilFuncDirty) {
  12034. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12035. this._isStencilFuncDirty = false;
  12036. }
  12037. // Stencil op
  12038. if (this._isStencilOpDirty) {
  12039. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12040. this._isStencilOpDirty = false;
  12041. }
  12042. };
  12043. return _StencilState;
  12044. }());
  12045. BABYLON._StencilState = _StencilState;
  12046. })(BABYLON || (BABYLON = {}));
  12047. //# sourceMappingURL=babylon.stencilState.js.map
  12048. var __assign = (this && this.__assign) || function () {
  12049. __assign = Object.assign || function(t) {
  12050. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12051. s = arguments[i];
  12052. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12053. t[p] = s[p];
  12054. }
  12055. return t;
  12056. };
  12057. return __assign.apply(this, arguments);
  12058. };
  12059. var BABYLON;
  12060. (function (BABYLON) {
  12061. /**
  12062. * Keeps track of all the buffer info used in engine.
  12063. */
  12064. var BufferPointer = /** @class */ (function () {
  12065. function BufferPointer() {
  12066. }
  12067. return BufferPointer;
  12068. }());
  12069. /**
  12070. * Interface for attribute information associated with buffer instanciation
  12071. */
  12072. var InstancingAttributeInfo = /** @class */ (function () {
  12073. function InstancingAttributeInfo() {
  12074. }
  12075. return InstancingAttributeInfo;
  12076. }());
  12077. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12078. /**
  12079. * Define options used to create a render target texture
  12080. */
  12081. var RenderTargetCreationOptions = /** @class */ (function () {
  12082. function RenderTargetCreationOptions() {
  12083. }
  12084. return RenderTargetCreationOptions;
  12085. }());
  12086. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12087. /**
  12088. * Define options used to create a depth texture
  12089. */
  12090. var DepthTextureCreationOptions = /** @class */ (function () {
  12091. function DepthTextureCreationOptions() {
  12092. }
  12093. return DepthTextureCreationOptions;
  12094. }());
  12095. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12096. /**
  12097. * Class used to describe the capabilities of the engine relatively to the current browser
  12098. */
  12099. var EngineCapabilities = /** @class */ (function () {
  12100. function EngineCapabilities() {
  12101. }
  12102. return EngineCapabilities;
  12103. }());
  12104. BABYLON.EngineCapabilities = EngineCapabilities;
  12105. /**
  12106. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12107. */
  12108. var Engine = /** @class */ (function () {
  12109. /**
  12110. * Creates a new engine
  12111. * @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
  12112. * @param antialias defines enable antialiasing (default: false)
  12113. * @param options defines further options to be sent to the getContext() function
  12114. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12115. */
  12116. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12117. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12118. var _this = this;
  12119. // Public members
  12120. /**
  12121. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12122. */
  12123. this.forcePOTTextures = false;
  12124. /**
  12125. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12126. */
  12127. this.isFullscreen = false;
  12128. /**
  12129. * Gets a boolean indicating if the pointer is currently locked
  12130. */
  12131. this.isPointerLock = false;
  12132. /**
  12133. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12134. */
  12135. this.cullBackFaces = true;
  12136. /**
  12137. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12138. */
  12139. this.renderEvenInBackground = true;
  12140. /**
  12141. * Gets or sets a boolean indicating that cache can be kept between frames
  12142. */
  12143. this.preventCacheWipeBetweenFrames = false;
  12144. /**
  12145. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12146. **/
  12147. this.enableOfflineSupport = false;
  12148. /**
  12149. * 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)
  12150. **/
  12151. this.disableManifestCheck = false;
  12152. /**
  12153. * Gets the list of created scenes
  12154. */
  12155. this.scenes = new Array();
  12156. /**
  12157. * Gets the list of created postprocesses
  12158. */
  12159. this.postProcesses = new Array();
  12160. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12161. this.validateShaderPrograms = false;
  12162. // Observables
  12163. /**
  12164. * Observable event triggered each time the rendering canvas is resized
  12165. */
  12166. this.onResizeObservable = new BABYLON.Observable();
  12167. /**
  12168. * Observable event triggered each time the canvas loses focus
  12169. */
  12170. this.onCanvasBlurObservable = new BABYLON.Observable();
  12171. /**
  12172. * Observable event triggered each time the canvas gains focus
  12173. */
  12174. this.onCanvasFocusObservable = new BABYLON.Observable();
  12175. /**
  12176. * Observable event triggered each time the canvas receives pointerout event
  12177. */
  12178. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12179. /**
  12180. * Observable event triggered before each texture is initialized
  12181. */
  12182. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12183. //WebVR
  12184. this._vrDisplay = undefined;
  12185. this._vrSupported = false;
  12186. this._vrExclusivePointerMode = false;
  12187. // Uniform buffers list
  12188. /**
  12189. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12190. */
  12191. this.disableUniformBuffers = false;
  12192. /** @hidden */
  12193. this._uniformBuffers = new Array();
  12194. // Observables
  12195. /**
  12196. * Observable raised when the engine begins a new frame
  12197. */
  12198. this.onBeginFrameObservable = new BABYLON.Observable();
  12199. /**
  12200. * If set, will be used to request the next animation frame for the render loop
  12201. */
  12202. this.customAnimationFrameRequester = null;
  12203. /**
  12204. * Observable raised when the engine ends the current frame
  12205. */
  12206. this.onEndFrameObservable = new BABYLON.Observable();
  12207. /**
  12208. * Observable raised when the engine is about to compile a shader
  12209. */
  12210. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12211. /**
  12212. * Observable raised when the engine has jsut compiled a shader
  12213. */
  12214. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12215. this._windowIsBackground = false;
  12216. this._webGLVersion = 1.0;
  12217. /** @hidden */
  12218. this._badOS = false;
  12219. /** @hidden */
  12220. this._badDesktopOS = false;
  12221. /**
  12222. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12223. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12224. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12225. */
  12226. this.disableTextureBindingOptimization = false;
  12227. /**
  12228. * Observable signaled when VR display mode changes
  12229. */
  12230. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12231. /**
  12232. * Observable signaled when VR request present is complete
  12233. */
  12234. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12235. /**
  12236. * Observable signaled when VR request present starts
  12237. */
  12238. this.onVRRequestPresentStart = new BABYLON.Observable();
  12239. this._colorWrite = true;
  12240. /** @hidden */
  12241. this._drawCalls = new BABYLON.PerfCounter();
  12242. /** @hidden */
  12243. this._textureCollisions = new BABYLON.PerfCounter();
  12244. this._renderingQueueLaunched = false;
  12245. this._activeRenderLoops = new Array();
  12246. // Deterministic lockstepMaxSteps
  12247. this._deterministicLockstep = false;
  12248. this._lockstepMaxSteps = 4;
  12249. // Lost context
  12250. /**
  12251. * Observable signaled when a context lost event is raised
  12252. */
  12253. this.onContextLostObservable = new BABYLON.Observable();
  12254. /**
  12255. * Observable signaled when a context restored event is raised
  12256. */
  12257. this.onContextRestoredObservable = new BABYLON.Observable();
  12258. this._contextWasLost = false;
  12259. this._doNotHandleContextLost = false;
  12260. // FPS
  12261. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12262. this._fps = 60;
  12263. this._deltaTime = 0;
  12264. /**
  12265. * Turn this value on if you want to pause FPS computation when in background
  12266. */
  12267. this.disablePerformanceMonitorInBackground = false;
  12268. // States
  12269. /** @hidden */
  12270. this._depthCullingState = new BABYLON._DepthCullingState();
  12271. /** @hidden */
  12272. this._stencilState = new BABYLON._StencilState();
  12273. /** @hidden */
  12274. this._alphaState = new BABYLON._AlphaState();
  12275. /** @hidden */
  12276. this._alphaMode = Engine.ALPHA_DISABLE;
  12277. // Cache
  12278. this._internalTexturesCache = new Array();
  12279. /** @hidden */
  12280. this._activeChannel = 0;
  12281. this._currentTextureChannel = -1;
  12282. /** @hidden */
  12283. this._boundTexturesCache = {};
  12284. this._compiledEffects = {};
  12285. this._vertexAttribArraysEnabled = [];
  12286. this._uintIndicesCurrentlySet = false;
  12287. this._currentBoundBuffer = new Array();
  12288. /** @hidden */
  12289. this._currentFramebuffer = null;
  12290. this._currentBufferPointers = new Array();
  12291. this._currentInstanceLocations = new Array();
  12292. this._currentInstanceBuffers = new Array();
  12293. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12294. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12295. this._vaoRecordInProgress = false;
  12296. this._mustWipeVertexAttributes = false;
  12297. this._nextFreeTextureSlots = new Array();
  12298. this._maxSimultaneousTextures = 0;
  12299. this._activeRequests = new Array();
  12300. // Hardware supported Compressed Textures
  12301. this._texturesSupported = new Array();
  12302. /**
  12303. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12304. */
  12305. this.premultipliedAlpha = true;
  12306. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12307. this._onVRFullScreenTriggered = function () {
  12308. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12309. //get the old size before we change
  12310. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12311. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12312. //get the width and height, change the render size
  12313. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12314. _this.setHardwareScalingLevel(1);
  12315. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12316. }
  12317. else {
  12318. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12319. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12320. }
  12321. };
  12322. this._unpackFlipYCached = null;
  12323. /**
  12324. * In case you are sharing the context with other applications, it might
  12325. * be interested to not cache the unpack flip y state to ensure a consistent
  12326. * value would be set.
  12327. */
  12328. this.enableUnpackFlipYCached = true;
  12329. this._boundUniforms = {};
  12330. // Register promises
  12331. BABYLON.PromisePolyfill.Apply();
  12332. var canvas = null;
  12333. Engine.Instances.push(this);
  12334. if (!canvasOrContext) {
  12335. return;
  12336. }
  12337. options = options || {};
  12338. if (canvasOrContext.getContext) {
  12339. canvas = canvasOrContext;
  12340. this._renderingCanvas = canvas;
  12341. if (antialias != null) {
  12342. options.antialias = antialias;
  12343. }
  12344. if (options.deterministicLockstep === undefined) {
  12345. options.deterministicLockstep = false;
  12346. }
  12347. if (options.lockstepMaxSteps === undefined) {
  12348. options.lockstepMaxSteps = 4;
  12349. }
  12350. if (options.preserveDrawingBuffer === undefined) {
  12351. options.preserveDrawingBuffer = false;
  12352. }
  12353. if (options.audioEngine === undefined) {
  12354. options.audioEngine = true;
  12355. }
  12356. if (options.stencil === undefined) {
  12357. options.stencil = true;
  12358. }
  12359. if (options.premultipliedAlpha === false) {
  12360. this.premultipliedAlpha = false;
  12361. }
  12362. this._deterministicLockstep = options.deterministicLockstep;
  12363. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12364. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12365. // Exceptions
  12366. if (navigator && navigator.userAgent) {
  12367. var ua = navigator.userAgent;
  12368. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12369. var exception = _a[_i];
  12370. var key = exception.key;
  12371. var targets = exception.targets;
  12372. if (ua.indexOf(key) > -1) {
  12373. if (exception.capture && exception.captureConstraint) {
  12374. var capture = exception.capture;
  12375. var constraint = exception.captureConstraint;
  12376. var regex = new RegExp(capture);
  12377. var matches = regex.exec(ua);
  12378. if (matches && matches.length > 0) {
  12379. var capturedValue = parseInt(matches[matches.length - 1]);
  12380. if (capturedValue >= constraint) {
  12381. continue;
  12382. }
  12383. }
  12384. }
  12385. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12386. var target = targets_1[_b];
  12387. switch (target) {
  12388. case "uniformBuffer":
  12389. this.disableUniformBuffers = true;
  12390. break;
  12391. case "textureBindingOptimization":
  12392. this.disableTextureBindingOptimization = true;
  12393. break;
  12394. }
  12395. }
  12396. }
  12397. }
  12398. }
  12399. // GL
  12400. if (!options.disableWebGL2Support) {
  12401. try {
  12402. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12403. if (this._gl) {
  12404. this._webGLVersion = 2.0;
  12405. // Prevent weird browsers to lie :-)
  12406. if (!this._gl.deleteQuery) {
  12407. this._webGLVersion = 1.0;
  12408. }
  12409. }
  12410. }
  12411. catch (e) {
  12412. // Do nothing
  12413. }
  12414. }
  12415. if (!this._gl) {
  12416. if (!canvas) {
  12417. throw new Error("The provided canvas is null or undefined.");
  12418. }
  12419. try {
  12420. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12421. }
  12422. catch (e) {
  12423. throw new Error("WebGL not supported");
  12424. }
  12425. }
  12426. if (!this._gl) {
  12427. throw new Error("WebGL not supported");
  12428. }
  12429. this._onCanvasFocus = function () {
  12430. _this.onCanvasFocusObservable.notifyObservers(_this);
  12431. };
  12432. this._onCanvasBlur = function () {
  12433. _this.onCanvasBlurObservable.notifyObservers(_this);
  12434. };
  12435. canvas.addEventListener("focus", this._onCanvasFocus);
  12436. canvas.addEventListener("blur", this._onCanvasBlur);
  12437. this._onBlur = function () {
  12438. if (_this.disablePerformanceMonitorInBackground) {
  12439. _this._performanceMonitor.disable();
  12440. }
  12441. _this._windowIsBackground = true;
  12442. };
  12443. this._onFocus = function () {
  12444. if (_this.disablePerformanceMonitorInBackground) {
  12445. _this._performanceMonitor.enable();
  12446. }
  12447. _this._windowIsBackground = false;
  12448. };
  12449. this._onCanvasPointerOut = function (ev) {
  12450. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12451. };
  12452. window.addEventListener("blur", this._onBlur);
  12453. window.addEventListener("focus", this._onFocus);
  12454. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12455. // Context lost
  12456. if (!this._doNotHandleContextLost) {
  12457. this._onContextLost = function (evt) {
  12458. evt.preventDefault();
  12459. _this._contextWasLost = true;
  12460. BABYLON.Tools.Warn("WebGL context lost.");
  12461. _this.onContextLostObservable.notifyObservers(_this);
  12462. };
  12463. this._onContextRestored = function (evt) {
  12464. // Adding a timeout to avoid race condition at browser level
  12465. setTimeout(function () {
  12466. // Rebuild gl context
  12467. _this._initGLContext();
  12468. // Rebuild effects
  12469. _this._rebuildEffects();
  12470. // Rebuild textures
  12471. _this._rebuildInternalTextures();
  12472. // Rebuild buffers
  12473. _this._rebuildBuffers();
  12474. // Cache
  12475. _this.wipeCaches(true);
  12476. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12477. _this.onContextRestoredObservable.notifyObservers(_this);
  12478. _this._contextWasLost = false;
  12479. }, 0);
  12480. };
  12481. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12482. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12483. }
  12484. }
  12485. else {
  12486. this._gl = canvasOrContext;
  12487. this._renderingCanvas = this._gl.canvas;
  12488. if (this._gl.renderbufferStorageMultisample) {
  12489. this._webGLVersion = 2.0;
  12490. }
  12491. var attributes = this._gl.getContextAttributes();
  12492. if (attributes) {
  12493. options.stencil = attributes.stencil;
  12494. }
  12495. }
  12496. // Viewport
  12497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12499. this.resize();
  12500. this._isStencilEnable = options.stencil ? true : false;
  12501. this._initGLContext();
  12502. if (canvas) {
  12503. // Fullscreen
  12504. this._onFullscreenChange = function () {
  12505. if (document.fullscreen !== undefined) {
  12506. _this.isFullscreen = document.fullscreen;
  12507. }
  12508. else if (document.mozFullScreen !== undefined) {
  12509. _this.isFullscreen = document.mozFullScreen;
  12510. }
  12511. else if (document.webkitIsFullScreen !== undefined) {
  12512. _this.isFullscreen = document.webkitIsFullScreen;
  12513. }
  12514. else if (document.msIsFullScreen !== undefined) {
  12515. _this.isFullscreen = document.msIsFullScreen;
  12516. }
  12517. // Pointer lock
  12518. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12519. canvas.requestPointerLock = canvas.requestPointerLock ||
  12520. canvas.msRequestPointerLock ||
  12521. canvas.mozRequestPointerLock ||
  12522. canvas.webkitRequestPointerLock;
  12523. if (canvas.requestPointerLock) {
  12524. canvas.requestPointerLock();
  12525. }
  12526. }
  12527. };
  12528. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12529. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12530. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12531. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12532. // Pointer lock
  12533. this._onPointerLockChange = function () {
  12534. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12535. document.webkitPointerLockElement === canvas ||
  12536. document.msPointerLockElement === canvas ||
  12537. document.pointerLockElement === canvas);
  12538. };
  12539. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12540. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12541. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12542. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12543. this._onVRDisplayPointerRestricted = function () {
  12544. if (canvas) {
  12545. canvas.requestPointerLock();
  12546. }
  12547. };
  12548. this._onVRDisplayPointerUnrestricted = function () {
  12549. document.exitPointerLock();
  12550. };
  12551. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12552. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12553. }
  12554. // Create Audio Engine if needed.
  12555. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12556. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12557. }
  12558. // Prepare buffer pointers
  12559. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12560. this._currentBufferPointers[i] = new BufferPointer();
  12561. }
  12562. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12563. // Load WebVR Devices
  12564. if (options.autoEnableWebVR) {
  12565. this.initWebVR();
  12566. }
  12567. // Detect if we are running on a faulty buggy OS.
  12568. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12569. // Detect if we are running on a faulty buggy desktop OS.
  12570. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12571. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12572. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12573. }
  12574. Object.defineProperty(Engine, "LastCreatedEngine", {
  12575. /**
  12576. * Gets the latest created engine
  12577. */
  12578. get: function () {
  12579. if (Engine.Instances.length === 0) {
  12580. return null;
  12581. }
  12582. return Engine.Instances[Engine.Instances.length - 1];
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. Object.defineProperty(Engine, "LastCreatedScene", {
  12588. /**
  12589. * Gets the latest created scene
  12590. */
  12591. get: function () {
  12592. var lastCreatedEngine = Engine.LastCreatedEngine;
  12593. if (!lastCreatedEngine) {
  12594. return null;
  12595. }
  12596. if (lastCreatedEngine.scenes.length === 0) {
  12597. return null;
  12598. }
  12599. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12600. },
  12601. enumerable: true,
  12602. configurable: true
  12603. });
  12604. /**
  12605. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12606. * @param flag defines which part of the materials must be marked as dirty
  12607. * @param predicate defines a predicate used to filter which materials should be affected
  12608. */
  12609. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12610. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12611. var engine = Engine.Instances[engineIndex];
  12612. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12613. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12614. }
  12615. }
  12616. };
  12617. Object.defineProperty(Engine, "Version", {
  12618. /**
  12619. * Returns the current version of the framework
  12620. */
  12621. get: function () {
  12622. return "4.0.0-alpha.2";
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. Object.defineProperty(Engine.prototype, "description", {
  12628. /**
  12629. * Returns a string describing the current engine
  12630. */
  12631. get: function () {
  12632. var description = "WebGL" + this.webGLVersion;
  12633. if (this._caps.parallelShaderCompile) {
  12634. description += " - Parallel shader compilation";
  12635. }
  12636. return description;
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12642. /**
  12643. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12644. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12645. */
  12646. get: function () {
  12647. return this._vrExclusivePointerMode;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12653. /**
  12654. * Gets a boolean indicating that the engine supports uniform buffers
  12655. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12656. */
  12657. get: function () {
  12658. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12659. },
  12660. enumerable: true,
  12661. configurable: true
  12662. });
  12663. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12664. /**
  12665. * Gets a boolean indicating that only power of 2 textures are supported
  12666. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12667. */
  12668. get: function () {
  12669. return this._webGLVersion < 2 || this.forcePOTTextures;
  12670. },
  12671. enumerable: true,
  12672. configurable: true
  12673. });
  12674. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12675. /**
  12676. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12677. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12678. */
  12679. get: function () {
  12680. return this._doNotHandleContextLost;
  12681. },
  12682. set: function (value) {
  12683. this._doNotHandleContextLost = value;
  12684. },
  12685. enumerable: true,
  12686. configurable: true
  12687. });
  12688. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12689. /**
  12690. * Gets the performance monitor attached to this engine
  12691. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12692. */
  12693. get: function () {
  12694. return this._performanceMonitor;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12700. /**
  12701. * Gets the list of texture formats supported
  12702. */
  12703. get: function () {
  12704. return this._texturesSupported;
  12705. },
  12706. enumerable: true,
  12707. configurable: true
  12708. });
  12709. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12710. /**
  12711. * Gets the list of texture formats in use
  12712. */
  12713. get: function () {
  12714. return this._textureFormatInUse;
  12715. },
  12716. enumerable: true,
  12717. configurable: true
  12718. });
  12719. Object.defineProperty(Engine.prototype, "currentViewport", {
  12720. /**
  12721. * Gets the current viewport
  12722. */
  12723. get: function () {
  12724. return this._cachedViewport;
  12725. },
  12726. enumerable: true,
  12727. configurable: true
  12728. });
  12729. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12730. /**
  12731. * Gets the default empty texture
  12732. */
  12733. get: function () {
  12734. if (!this._emptyTexture) {
  12735. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12736. }
  12737. return this._emptyTexture;
  12738. },
  12739. enumerable: true,
  12740. configurable: true
  12741. });
  12742. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12743. /**
  12744. * Gets the default empty 3D texture
  12745. */
  12746. get: function () {
  12747. if (!this._emptyTexture3D) {
  12748. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12749. }
  12750. return this._emptyTexture3D;
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12756. /**
  12757. * Gets the default empty cube texture
  12758. */
  12759. get: function () {
  12760. if (!this._emptyCubeTexture) {
  12761. var faceData = new Uint8Array(4);
  12762. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12763. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12764. }
  12765. return this._emptyCubeTexture;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Engine.prototype._rebuildInternalTextures = function () {
  12771. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12772. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12773. var internalTexture = currentState_1[_i];
  12774. internalTexture._rebuild();
  12775. }
  12776. };
  12777. Engine.prototype._rebuildEffects = function () {
  12778. for (var key in this._compiledEffects) {
  12779. var effect = this._compiledEffects[key];
  12780. effect._prepareEffect();
  12781. }
  12782. BABYLON.Effect.ResetCache();
  12783. };
  12784. /**
  12785. * Gets a boolean indicating if all created effects are ready
  12786. * @returns true if all effects are ready
  12787. */
  12788. Engine.prototype.areAllEffectsReady = function () {
  12789. for (var key in this._compiledEffects) {
  12790. var effect = this._compiledEffects[key];
  12791. if (!effect.isReady()) {
  12792. return false;
  12793. }
  12794. }
  12795. return true;
  12796. };
  12797. Engine.prototype._rebuildBuffers = function () {
  12798. // Index / Vertex
  12799. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12800. var scene = _a[_i];
  12801. scene.resetCachedMaterial();
  12802. scene._rebuildGeometries();
  12803. scene._rebuildTextures();
  12804. }
  12805. // Uniforms
  12806. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12807. var uniformBuffer = _c[_b];
  12808. uniformBuffer._rebuild();
  12809. }
  12810. };
  12811. Engine.prototype._initGLContext = function () {
  12812. // Caps
  12813. this._caps = new EngineCapabilities();
  12814. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12815. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12816. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12817. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12818. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12819. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12820. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12821. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12822. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12823. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12824. // Infos
  12825. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12826. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12827. if (rendererInfo != null) {
  12828. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12829. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12830. }
  12831. if (!this._glVendor) {
  12832. this._glVendor = "Unknown vendor";
  12833. }
  12834. if (!this._glRenderer) {
  12835. this._glRenderer = "Unknown renderer";
  12836. }
  12837. // Constants
  12838. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12839. if (this._gl.RGBA16F !== 0x881A) {
  12840. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12841. }
  12842. if (this._gl.RGBA32F !== 0x8814) {
  12843. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12844. }
  12845. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12846. this._gl.DEPTH24_STENCIL8 = 35056;
  12847. }
  12848. // Extensions
  12849. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12850. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12851. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12852. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12853. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12854. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12855. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12856. 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');
  12857. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12858. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12859. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12860. this._caps.highPrecisionShaderSupported = true;
  12861. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12862. if (this._caps.timerQuery) {
  12863. if (this._webGLVersion === 1) {
  12864. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12865. }
  12866. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12867. }
  12868. // Checks if some of the format renders first to allow the use of webgl inspector.
  12869. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12870. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12871. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12872. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12873. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12874. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12875. if (this._webGLVersion > 1) {
  12876. this._gl.HALF_FLOAT_OES = 0x140B;
  12877. }
  12878. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12879. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12880. // Draw buffers
  12881. if (this._webGLVersion > 1) {
  12882. this._caps.drawBuffersExtension = true;
  12883. }
  12884. else {
  12885. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12886. if (drawBuffersExtension !== null) {
  12887. this._caps.drawBuffersExtension = true;
  12888. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12889. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12890. for (var i = 0; i < 16; i++) {
  12891. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12892. }
  12893. }
  12894. else {
  12895. this._caps.drawBuffersExtension = false;
  12896. }
  12897. }
  12898. // Shader compiler threads
  12899. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  12900. if (this._caps.parallelShaderCompile) {
  12901. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  12902. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  12903. }
  12904. // Depth Texture
  12905. if (this._webGLVersion > 1) {
  12906. this._caps.depthTextureExtension = true;
  12907. }
  12908. else {
  12909. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12910. if (depthTextureExtension != null) {
  12911. this._caps.depthTextureExtension = true;
  12912. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12913. }
  12914. }
  12915. // Vertex array object
  12916. if (this._webGLVersion > 1) {
  12917. this._caps.vertexArrayObject = true;
  12918. }
  12919. else {
  12920. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12921. if (vertexArrayObjectExtension != null) {
  12922. this._caps.vertexArrayObject = true;
  12923. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12924. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12925. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12926. }
  12927. else {
  12928. this._caps.vertexArrayObject = false;
  12929. }
  12930. }
  12931. // Instances count
  12932. if (this._webGLVersion > 1) {
  12933. this._caps.instancedArrays = true;
  12934. }
  12935. else {
  12936. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12937. if (instanceExtension != null) {
  12938. this._caps.instancedArrays = true;
  12939. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12940. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12941. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12942. }
  12943. else {
  12944. this._caps.instancedArrays = false;
  12945. }
  12946. }
  12947. // Intelligently add supported compressed formats in order to check for.
  12948. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12949. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12950. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12951. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12952. if (this._caps.astc) {
  12953. this.texturesSupported.push('-astc.ktx');
  12954. }
  12955. if (this._caps.s3tc) {
  12956. this.texturesSupported.push('-dxt.ktx');
  12957. }
  12958. if (this._caps.pvrtc) {
  12959. this.texturesSupported.push('-pvrtc.ktx');
  12960. }
  12961. if (this._caps.etc2) {
  12962. this.texturesSupported.push('-etc2.ktx');
  12963. }
  12964. if (this._caps.etc1) {
  12965. this.texturesSupported.push('-etc1.ktx');
  12966. }
  12967. if (this._gl.getShaderPrecisionFormat) {
  12968. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12969. if (highp) {
  12970. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12971. }
  12972. }
  12973. // Depth buffer
  12974. this.setDepthBuffer(true);
  12975. this.setDepthFunctionToLessOrEqual();
  12976. this.setDepthWrite(true);
  12977. // Texture maps
  12978. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12979. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12980. this._nextFreeTextureSlots.push(slot);
  12981. }
  12982. };
  12983. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12984. /**
  12985. * Gets version of the current webGL context
  12986. */
  12987. get: function () {
  12988. return this._webGLVersion;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12994. /**
  12995. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12996. */
  12997. get: function () {
  12998. return this._isStencilEnable;
  12999. },
  13000. enumerable: true,
  13001. configurable: true
  13002. });
  13003. Engine.prototype._prepareWorkingCanvas = function () {
  13004. if (this._workingCanvas) {
  13005. return;
  13006. }
  13007. this._workingCanvas = document.createElement("canvas");
  13008. var context = this._workingCanvas.getContext("2d");
  13009. if (context) {
  13010. this._workingContext = context;
  13011. }
  13012. };
  13013. /**
  13014. * Reset the texture cache to empty state
  13015. */
  13016. Engine.prototype.resetTextureCache = function () {
  13017. for (var key in this._boundTexturesCache) {
  13018. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13019. continue;
  13020. }
  13021. var boundTexture = this._boundTexturesCache[key];
  13022. if (boundTexture) {
  13023. this._removeDesignatedSlot(boundTexture);
  13024. }
  13025. this._boundTexturesCache[key] = null;
  13026. }
  13027. if (!this.disableTextureBindingOptimization) {
  13028. this._nextFreeTextureSlots = [];
  13029. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13030. this._nextFreeTextureSlots.push(slot);
  13031. }
  13032. }
  13033. this._currentTextureChannel = -1;
  13034. };
  13035. /**
  13036. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13037. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13038. * @returns true if engine is in deterministic lock step mode
  13039. */
  13040. Engine.prototype.isDeterministicLockStep = function () {
  13041. return this._deterministicLockstep;
  13042. };
  13043. /**
  13044. * Gets the max steps when engine is running in deterministic lock step
  13045. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13046. * @returns the max steps
  13047. */
  13048. Engine.prototype.getLockstepMaxSteps = function () {
  13049. return this._lockstepMaxSteps;
  13050. };
  13051. /**
  13052. * Gets an object containing information about the current webGL context
  13053. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13054. */
  13055. Engine.prototype.getGlInfo = function () {
  13056. return {
  13057. vendor: this._glVendor,
  13058. renderer: this._glRenderer,
  13059. version: this._glVersion
  13060. };
  13061. };
  13062. /**
  13063. * Gets current aspect ratio
  13064. * @param camera defines the camera to use to get the aspect ratio
  13065. * @param useScreen defines if screen size must be used (or the current render target if any)
  13066. * @returns a number defining the aspect ratio
  13067. */
  13068. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13069. if (useScreen === void 0) { useScreen = false; }
  13070. var viewport = camera.viewport;
  13071. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13072. };
  13073. /**
  13074. * Gets current screen aspect ratio
  13075. * @returns a number defining the aspect ratio
  13076. */
  13077. Engine.prototype.getScreenAspectRatio = function () {
  13078. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13079. };
  13080. /**
  13081. * Gets the current render width
  13082. * @param useScreen defines if screen size must be used (or the current render target if any)
  13083. * @returns a number defining the current render width
  13084. */
  13085. Engine.prototype.getRenderWidth = function (useScreen) {
  13086. if (useScreen === void 0) { useScreen = false; }
  13087. if (!useScreen && this._currentRenderTarget) {
  13088. return this._currentRenderTarget.width;
  13089. }
  13090. return this._gl.drawingBufferWidth;
  13091. };
  13092. /**
  13093. * Gets the current render height
  13094. * @param useScreen defines if screen size must be used (or the current render target if any)
  13095. * @returns a number defining the current render height
  13096. */
  13097. Engine.prototype.getRenderHeight = function (useScreen) {
  13098. if (useScreen === void 0) { useScreen = false; }
  13099. if (!useScreen && this._currentRenderTarget) {
  13100. return this._currentRenderTarget.height;
  13101. }
  13102. return this._gl.drawingBufferHeight;
  13103. };
  13104. /**
  13105. * Gets the HTML canvas attached with the current webGL context
  13106. * @returns a HTML canvas
  13107. */
  13108. Engine.prototype.getRenderingCanvas = function () {
  13109. return this._renderingCanvas;
  13110. };
  13111. /**
  13112. * Gets the client rect of the HTML canvas attached with the current webGL context
  13113. * @returns a client rectanglee
  13114. */
  13115. Engine.prototype.getRenderingCanvasClientRect = function () {
  13116. if (!this._renderingCanvas) {
  13117. return null;
  13118. }
  13119. return this._renderingCanvas.getBoundingClientRect();
  13120. };
  13121. /**
  13122. * Defines the hardware scaling level.
  13123. * By default the hardware scaling level is computed from the window device ratio.
  13124. * 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.
  13125. * @param level defines the level to use
  13126. */
  13127. Engine.prototype.setHardwareScalingLevel = function (level) {
  13128. this._hardwareScalingLevel = level;
  13129. this.resize();
  13130. };
  13131. /**
  13132. * Gets the current hardware scaling level.
  13133. * By default the hardware scaling level is computed from the window device ratio.
  13134. * 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.
  13135. * @returns a number indicating the current hardware scaling level
  13136. */
  13137. Engine.prototype.getHardwareScalingLevel = function () {
  13138. return this._hardwareScalingLevel;
  13139. };
  13140. /**
  13141. * Gets the list of loaded textures
  13142. * @returns an array containing all loaded textures
  13143. */
  13144. Engine.prototype.getLoadedTexturesCache = function () {
  13145. return this._internalTexturesCache;
  13146. };
  13147. /**
  13148. * Gets the object containing all engine capabilities
  13149. * @returns the EngineCapabilities object
  13150. */
  13151. Engine.prototype.getCaps = function () {
  13152. return this._caps;
  13153. };
  13154. Object.defineProperty(Engine.prototype, "drawCalls", {
  13155. /** @hidden */
  13156. get: function () {
  13157. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13158. return 0;
  13159. },
  13160. enumerable: true,
  13161. configurable: true
  13162. });
  13163. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13164. /** @hidden */
  13165. get: function () {
  13166. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13167. return null;
  13168. },
  13169. enumerable: true,
  13170. configurable: true
  13171. });
  13172. /**
  13173. * Gets the current depth function
  13174. * @returns a number defining the depth function
  13175. */
  13176. Engine.prototype.getDepthFunction = function () {
  13177. return this._depthCullingState.depthFunc;
  13178. };
  13179. /**
  13180. * Sets the current depth function
  13181. * @param depthFunc defines the function to use
  13182. */
  13183. Engine.prototype.setDepthFunction = function (depthFunc) {
  13184. this._depthCullingState.depthFunc = depthFunc;
  13185. };
  13186. /**
  13187. * Sets the current depth function to GREATER
  13188. */
  13189. Engine.prototype.setDepthFunctionToGreater = function () {
  13190. this._depthCullingState.depthFunc = this._gl.GREATER;
  13191. };
  13192. /**
  13193. * Sets the current depth function to GEQUAL
  13194. */
  13195. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13196. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13197. };
  13198. /**
  13199. * Sets the current depth function to LESS
  13200. */
  13201. Engine.prototype.setDepthFunctionToLess = function () {
  13202. this._depthCullingState.depthFunc = this._gl.LESS;
  13203. };
  13204. /**
  13205. * Sets the current depth function to LEQUAL
  13206. */
  13207. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13208. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13209. };
  13210. /**
  13211. * Gets a boolean indicating if stencil buffer is enabled
  13212. * @returns the current stencil buffer state
  13213. */
  13214. Engine.prototype.getStencilBuffer = function () {
  13215. return this._stencilState.stencilTest;
  13216. };
  13217. /**
  13218. * Enable or disable the stencil buffer
  13219. * @param enable defines if the stencil buffer must be enabled or disabled
  13220. */
  13221. Engine.prototype.setStencilBuffer = function (enable) {
  13222. this._stencilState.stencilTest = enable;
  13223. };
  13224. /**
  13225. * Gets the current stencil mask
  13226. * @returns a number defining the new stencil mask to use
  13227. */
  13228. Engine.prototype.getStencilMask = function () {
  13229. return this._stencilState.stencilMask;
  13230. };
  13231. /**
  13232. * Sets the current stencil mask
  13233. * @param mask defines the new stencil mask to use
  13234. */
  13235. Engine.prototype.setStencilMask = function (mask) {
  13236. this._stencilState.stencilMask = mask;
  13237. };
  13238. /**
  13239. * Gets the current stencil function
  13240. * @returns a number defining the stencil function to use
  13241. */
  13242. Engine.prototype.getStencilFunction = function () {
  13243. return this._stencilState.stencilFunc;
  13244. };
  13245. /**
  13246. * Gets the current stencil reference value
  13247. * @returns a number defining the stencil reference value to use
  13248. */
  13249. Engine.prototype.getStencilFunctionReference = function () {
  13250. return this._stencilState.stencilFuncRef;
  13251. };
  13252. /**
  13253. * Gets the current stencil mask
  13254. * @returns a number defining the stencil mask to use
  13255. */
  13256. Engine.prototype.getStencilFunctionMask = function () {
  13257. return this._stencilState.stencilFuncMask;
  13258. };
  13259. /**
  13260. * Sets the current stencil function
  13261. * @param stencilFunc defines the new stencil function to use
  13262. */
  13263. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13264. this._stencilState.stencilFunc = stencilFunc;
  13265. };
  13266. /**
  13267. * Sets the current stencil reference
  13268. * @param reference defines the new stencil reference to use
  13269. */
  13270. Engine.prototype.setStencilFunctionReference = function (reference) {
  13271. this._stencilState.stencilFuncRef = reference;
  13272. };
  13273. /**
  13274. * Sets the current stencil mask
  13275. * @param mask defines the new stencil mask to use
  13276. */
  13277. Engine.prototype.setStencilFunctionMask = function (mask) {
  13278. this._stencilState.stencilFuncMask = mask;
  13279. };
  13280. /**
  13281. * Gets the current stencil operation when stencil fails
  13282. * @returns a number defining stencil operation to use when stencil fails
  13283. */
  13284. Engine.prototype.getStencilOperationFail = function () {
  13285. return this._stencilState.stencilOpStencilFail;
  13286. };
  13287. /**
  13288. * Gets the current stencil operation when depth fails
  13289. * @returns a number defining stencil operation to use when depth fails
  13290. */
  13291. Engine.prototype.getStencilOperationDepthFail = function () {
  13292. return this._stencilState.stencilOpDepthFail;
  13293. };
  13294. /**
  13295. * Gets the current stencil operation when stencil passes
  13296. * @returns a number defining stencil operation to use when stencil passes
  13297. */
  13298. Engine.prototype.getStencilOperationPass = function () {
  13299. return this._stencilState.stencilOpStencilDepthPass;
  13300. };
  13301. /**
  13302. * Sets the stencil operation to use when stencil fails
  13303. * @param operation defines the stencil operation to use when stencil fails
  13304. */
  13305. Engine.prototype.setStencilOperationFail = function (operation) {
  13306. this._stencilState.stencilOpStencilFail = operation;
  13307. };
  13308. /**
  13309. * Sets the stencil operation to use when depth fails
  13310. * @param operation defines the stencil operation to use when depth fails
  13311. */
  13312. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13313. this._stencilState.stencilOpDepthFail = operation;
  13314. };
  13315. /**
  13316. * Sets the stencil operation to use when stencil passes
  13317. * @param operation defines the stencil operation to use when stencil passes
  13318. */
  13319. Engine.prototype.setStencilOperationPass = function (operation) {
  13320. this._stencilState.stencilOpStencilDepthPass = operation;
  13321. };
  13322. /**
  13323. * Sets a boolean indicating if the dithering state is enabled or disabled
  13324. * @param value defines the dithering state
  13325. */
  13326. Engine.prototype.setDitheringState = function (value) {
  13327. if (value) {
  13328. this._gl.enable(this._gl.DITHER);
  13329. }
  13330. else {
  13331. this._gl.disable(this._gl.DITHER);
  13332. }
  13333. };
  13334. /**
  13335. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13336. * @param value defines the rasterizer state
  13337. */
  13338. Engine.prototype.setRasterizerState = function (value) {
  13339. if (value) {
  13340. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13341. }
  13342. else {
  13343. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13344. }
  13345. };
  13346. /**
  13347. * stop executing a render loop function and remove it from the execution array
  13348. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13349. */
  13350. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13351. if (!renderFunction) {
  13352. this._activeRenderLoops = [];
  13353. return;
  13354. }
  13355. var index = this._activeRenderLoops.indexOf(renderFunction);
  13356. if (index >= 0) {
  13357. this._activeRenderLoops.splice(index, 1);
  13358. }
  13359. };
  13360. /** @hidden */
  13361. Engine.prototype._renderLoop = function () {
  13362. if (!this._contextWasLost) {
  13363. var shouldRender = true;
  13364. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13365. shouldRender = false;
  13366. }
  13367. if (shouldRender) {
  13368. // Start new frame
  13369. this.beginFrame();
  13370. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13371. var renderFunction = this._activeRenderLoops[index];
  13372. renderFunction();
  13373. }
  13374. // Present
  13375. this.endFrame();
  13376. }
  13377. }
  13378. if (this._activeRenderLoops.length > 0) {
  13379. // Register new frame
  13380. if (this.customAnimationFrameRequester) {
  13381. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13382. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13383. }
  13384. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13385. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13386. }
  13387. else {
  13388. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13389. }
  13390. }
  13391. else {
  13392. this._renderingQueueLaunched = false;
  13393. }
  13394. };
  13395. /**
  13396. * Register and execute a render loop. The engine can have more than one render function
  13397. * @param renderFunction defines the function to continuously execute
  13398. */
  13399. Engine.prototype.runRenderLoop = function (renderFunction) {
  13400. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13401. return;
  13402. }
  13403. this._activeRenderLoops.push(renderFunction);
  13404. if (!this._renderingQueueLaunched) {
  13405. this._renderingQueueLaunched = true;
  13406. this._bindedRenderFunction = this._renderLoop.bind(this);
  13407. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13408. }
  13409. };
  13410. /**
  13411. * Toggle full screen mode
  13412. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13413. */
  13414. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13415. if (this.isFullscreen) {
  13416. BABYLON.Tools.ExitFullscreen();
  13417. }
  13418. else {
  13419. this._pointerLockRequested = requestPointerLock;
  13420. if (this._renderingCanvas) {
  13421. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13422. }
  13423. }
  13424. };
  13425. /**
  13426. * Clear the current render buffer or the current render target (if any is set up)
  13427. * @param color defines the color to use
  13428. * @param backBuffer defines if the back buffer must be cleared
  13429. * @param depth defines if the depth buffer must be cleared
  13430. * @param stencil defines if the stencil buffer must be cleared
  13431. */
  13432. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13433. if (stencil === void 0) { stencil = false; }
  13434. this.applyStates();
  13435. var mode = 0;
  13436. if (backBuffer && color) {
  13437. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13438. mode |= this._gl.COLOR_BUFFER_BIT;
  13439. }
  13440. if (depth) {
  13441. this._gl.clearDepth(1.0);
  13442. mode |= this._gl.DEPTH_BUFFER_BIT;
  13443. }
  13444. if (stencil) {
  13445. this._gl.clearStencil(0);
  13446. mode |= this._gl.STENCIL_BUFFER_BIT;
  13447. }
  13448. this._gl.clear(mode);
  13449. };
  13450. /**
  13451. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13452. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13453. * @param y defines the y-coordinate of the corner of the clear rectangle
  13454. * @param width defines the width of the clear rectangle
  13455. * @param height defines the height of the clear rectangle
  13456. * @param clearColor defines the clear color
  13457. */
  13458. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13459. var gl = this._gl;
  13460. // Save state
  13461. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13462. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13463. // Change state
  13464. gl.enable(gl.SCISSOR_TEST);
  13465. gl.scissor(x, y, width, height);
  13466. // Clear
  13467. this.clear(clearColor, true, true, true);
  13468. // Restore state
  13469. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13470. if (curScissor === true) {
  13471. gl.enable(gl.SCISSOR_TEST);
  13472. }
  13473. else {
  13474. gl.disable(gl.SCISSOR_TEST);
  13475. }
  13476. };
  13477. /** @hidden */
  13478. Engine.prototype._viewport = function (x, y, width, height) {
  13479. if (x !== this._viewportCached.x ||
  13480. y !== this._viewportCached.y ||
  13481. width !== this._viewportCached.z ||
  13482. height !== this._viewportCached.w) {
  13483. this._viewportCached.x = x;
  13484. this._viewportCached.y = y;
  13485. this._viewportCached.z = width;
  13486. this._viewportCached.w = height;
  13487. this._gl.viewport(x, y, width, height);
  13488. }
  13489. };
  13490. /**
  13491. * Set the WebGL's viewport
  13492. * @param viewport defines the viewport element to be used
  13493. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13494. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13495. */
  13496. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13497. var width = requiredWidth || this.getRenderWidth();
  13498. var height = requiredHeight || this.getRenderHeight();
  13499. var x = viewport.x || 0;
  13500. var y = viewport.y || 0;
  13501. this._cachedViewport = viewport;
  13502. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13503. };
  13504. /**
  13505. * Directly set the WebGL Viewport
  13506. * @param x defines the x coordinate of the viewport (in screen space)
  13507. * @param y defines the y coordinate of the viewport (in screen space)
  13508. * @param width defines the width of the viewport (in screen space)
  13509. * @param height defines the height of the viewport (in screen space)
  13510. * @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
  13511. */
  13512. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13513. var currentViewport = this._cachedViewport;
  13514. this._cachedViewport = null;
  13515. this._viewport(x, y, width, height);
  13516. return currentViewport;
  13517. };
  13518. /**
  13519. * Begin a new frame
  13520. */
  13521. Engine.prototype.beginFrame = function () {
  13522. this.onBeginFrameObservable.notifyObservers(this);
  13523. this._measureFps();
  13524. };
  13525. /**
  13526. * Enf the current frame
  13527. */
  13528. Engine.prototype.endFrame = function () {
  13529. // Force a flush in case we are using a bad OS.
  13530. if (this._badOS) {
  13531. this.flushFramebuffer();
  13532. }
  13533. // Submit frame to the vr device, if enabled
  13534. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13535. // TODO: We should only submit the frame if we read frameData successfully.
  13536. this._vrDisplay.submitFrame();
  13537. }
  13538. this.onEndFrameObservable.notifyObservers(this);
  13539. };
  13540. /**
  13541. * Resize the view according to the canvas' size
  13542. */
  13543. Engine.prototype.resize = function () {
  13544. // We're not resizing the size of the canvas while in VR mode & presenting
  13545. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13546. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13547. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13548. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13549. }
  13550. };
  13551. /**
  13552. * Force a specific size of the canvas
  13553. * @param width defines the new canvas' width
  13554. * @param height defines the new canvas' height
  13555. */
  13556. Engine.prototype.setSize = function (width, height) {
  13557. if (!this._renderingCanvas) {
  13558. return;
  13559. }
  13560. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13561. return;
  13562. }
  13563. this._renderingCanvas.width = width;
  13564. this._renderingCanvas.height = height;
  13565. for (var index = 0; index < this.scenes.length; index++) {
  13566. var scene = this.scenes[index];
  13567. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13568. var cam = scene.cameras[camIndex];
  13569. cam._currentRenderId = 0;
  13570. }
  13571. }
  13572. if (this.onResizeObservable.hasObservers) {
  13573. this.onResizeObservable.notifyObservers(this);
  13574. }
  13575. };
  13576. // WebVR functions
  13577. /**
  13578. * Gets a boolean indicating if a webVR device was detected
  13579. * @returns true if a webVR device was detected
  13580. */
  13581. Engine.prototype.isVRDevicePresent = function () {
  13582. return !!this._vrDisplay;
  13583. };
  13584. /**
  13585. * Gets the current webVR device
  13586. * @returns the current webVR device (or null)
  13587. */
  13588. Engine.prototype.getVRDevice = function () {
  13589. return this._vrDisplay;
  13590. };
  13591. /**
  13592. * Initializes a webVR display and starts listening to display change events
  13593. * The onVRDisplayChangedObservable will be notified upon these changes
  13594. * @returns The onVRDisplayChangedObservable
  13595. */
  13596. Engine.prototype.initWebVR = function () {
  13597. this.initWebVRAsync();
  13598. return this.onVRDisplayChangedObservable;
  13599. };
  13600. /**
  13601. * Initializes a webVR display and starts listening to display change events
  13602. * The onVRDisplayChangedObservable will be notified upon these changes
  13603. * @returns A promise containing a VRDisplay and if vr is supported
  13604. */
  13605. Engine.prototype.initWebVRAsync = function () {
  13606. var _this = this;
  13607. var notifyObservers = function () {
  13608. var eventArgs = {
  13609. vrDisplay: _this._vrDisplay,
  13610. vrSupported: _this._vrSupported
  13611. };
  13612. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13613. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13614. };
  13615. if (!this._onVrDisplayConnect) {
  13616. this._onVrDisplayConnect = function (event) {
  13617. _this._vrDisplay = event.display;
  13618. notifyObservers();
  13619. };
  13620. this._onVrDisplayDisconnect = function () {
  13621. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13622. _this._vrDisplay = undefined;
  13623. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13624. notifyObservers();
  13625. };
  13626. this._onVrDisplayPresentChange = function () {
  13627. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13628. };
  13629. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13630. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13631. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13632. }
  13633. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13634. this._webVRInitPromise.then(notifyObservers);
  13635. return this._webVRInitPromise;
  13636. };
  13637. /**
  13638. * Call this function to switch to webVR mode
  13639. * Will do nothing if webVR is not supported or if there is no webVR device
  13640. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13641. */
  13642. Engine.prototype.enableVR = function () {
  13643. var _this = this;
  13644. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13645. var onResolved = function () {
  13646. _this.onVRRequestPresentComplete.notifyObservers(true);
  13647. _this._onVRFullScreenTriggered();
  13648. };
  13649. var onRejected = function () {
  13650. _this.onVRRequestPresentComplete.notifyObservers(false);
  13651. };
  13652. this.onVRRequestPresentStart.notifyObservers(this);
  13653. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13654. }
  13655. };
  13656. /**
  13657. * Call this function to leave webVR mode
  13658. * Will do nothing if webVR is not supported or if there is no webVR device
  13659. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13660. */
  13661. Engine.prototype.disableVR = function () {
  13662. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13663. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13664. }
  13665. };
  13666. Engine.prototype._getVRDisplaysAsync = function () {
  13667. var _this = this;
  13668. return new Promise(function (res, rej) {
  13669. if (navigator.getVRDisplays) {
  13670. navigator.getVRDisplays().then(function (devices) {
  13671. _this._vrSupported = true;
  13672. // note that devices may actually be an empty array. This is fine;
  13673. // we expect this._vrDisplay to be undefined in this case.
  13674. _this._vrDisplay = devices[0];
  13675. res({
  13676. vrDisplay: _this._vrDisplay,
  13677. vrSupported: _this._vrSupported
  13678. });
  13679. });
  13680. }
  13681. else {
  13682. _this._vrDisplay = undefined;
  13683. _this._vrSupported = false;
  13684. res({
  13685. vrDisplay: _this._vrDisplay,
  13686. vrSupported: _this._vrSupported
  13687. });
  13688. }
  13689. });
  13690. };
  13691. /**
  13692. * Binds the frame buffer to the specified texture.
  13693. * @param texture The texture to render to or null for the default canvas
  13694. * @param faceIndex The face of the texture to render to in case of cube texture
  13695. * @param requiredWidth The width of the target to render to
  13696. * @param requiredHeight The height of the target to render to
  13697. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13698. * @param depthStencilTexture The depth stencil texture to use to render
  13699. * @param lodLevel defines le lod level to bind to the frame buffer
  13700. */
  13701. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13702. if (lodLevel === void 0) { lodLevel = 0; }
  13703. if (this._currentRenderTarget) {
  13704. this.unBindFramebuffer(this._currentRenderTarget);
  13705. }
  13706. this._currentRenderTarget = texture;
  13707. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13708. var gl = this._gl;
  13709. if (texture.isCube) {
  13710. if (faceIndex === undefined) {
  13711. faceIndex = 0;
  13712. }
  13713. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13714. if (depthStencilTexture) {
  13715. if (depthStencilTexture._generateStencilBuffer) {
  13716. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13717. }
  13718. else {
  13719. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13720. }
  13721. }
  13722. }
  13723. if (this._cachedViewport && !forceFullscreenViewport) {
  13724. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13725. }
  13726. else {
  13727. if (!requiredWidth) {
  13728. requiredWidth = texture.width;
  13729. if (lodLevel) {
  13730. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13731. }
  13732. }
  13733. if (!requiredHeight) {
  13734. requiredHeight = texture.height;
  13735. if (lodLevel) {
  13736. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13737. }
  13738. }
  13739. this._viewport(0, 0, requiredWidth, requiredHeight);
  13740. }
  13741. this.wipeCaches();
  13742. };
  13743. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13744. if (this._currentFramebuffer !== framebuffer) {
  13745. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13746. this._currentFramebuffer = framebuffer;
  13747. }
  13748. };
  13749. /**
  13750. * Unbind the current render target texture from the webGL context
  13751. * @param texture defines the render target texture to unbind
  13752. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13753. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13754. */
  13755. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13756. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13757. this._currentRenderTarget = null;
  13758. // If MSAA, we need to bitblt back to main texture
  13759. var gl = this._gl;
  13760. if (texture._MSAAFramebuffer) {
  13761. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13762. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13763. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13764. }
  13765. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13766. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13767. gl.generateMipmap(gl.TEXTURE_2D);
  13768. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13769. }
  13770. if (onBeforeUnbind) {
  13771. if (texture._MSAAFramebuffer) {
  13772. // Bind the correct framebuffer
  13773. this.bindUnboundFramebuffer(texture._framebuffer);
  13774. }
  13775. onBeforeUnbind();
  13776. }
  13777. this.bindUnboundFramebuffer(null);
  13778. };
  13779. /**
  13780. * Unbind a list of render target textures from the webGL context
  13781. * This is used only when drawBuffer extension or webGL2 are active
  13782. * @param textures defines the render target textures to unbind
  13783. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13784. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13785. */
  13786. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13787. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13788. this._currentRenderTarget = null;
  13789. // If MSAA, we need to bitblt back to main texture
  13790. var gl = this._gl;
  13791. if (textures[0]._MSAAFramebuffer) {
  13792. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13793. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13794. var attachments = textures[0]._attachments;
  13795. if (!attachments) {
  13796. attachments = new Array(textures.length);
  13797. textures[0]._attachments = attachments;
  13798. }
  13799. for (var i = 0; i < textures.length; i++) {
  13800. var texture = textures[i];
  13801. for (var j = 0; j < attachments.length; j++) {
  13802. attachments[j] = gl.NONE;
  13803. }
  13804. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13805. gl.readBuffer(attachments[i]);
  13806. gl.drawBuffers(attachments);
  13807. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13808. }
  13809. for (var i = 0; i < attachments.length; i++) {
  13810. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13811. }
  13812. gl.drawBuffers(attachments);
  13813. }
  13814. for (var i = 0; i < textures.length; i++) {
  13815. var texture = textures[i];
  13816. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13817. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13818. gl.generateMipmap(gl.TEXTURE_2D);
  13819. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13820. }
  13821. }
  13822. if (onBeforeUnbind) {
  13823. if (textures[0]._MSAAFramebuffer) {
  13824. // Bind the correct framebuffer
  13825. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13826. }
  13827. onBeforeUnbind();
  13828. }
  13829. this.bindUnboundFramebuffer(null);
  13830. };
  13831. /**
  13832. * Force the mipmap generation for the given render target texture
  13833. * @param texture defines the render target texture to use
  13834. */
  13835. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13836. if (texture.generateMipMaps) {
  13837. var gl = this._gl;
  13838. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13839. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13841. }
  13842. };
  13843. /**
  13844. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13845. */
  13846. Engine.prototype.flushFramebuffer = function () {
  13847. this._gl.flush();
  13848. };
  13849. /**
  13850. * Unbind the current render target and bind the default framebuffer
  13851. */
  13852. Engine.prototype.restoreDefaultFramebuffer = function () {
  13853. if (this._currentRenderTarget) {
  13854. this.unBindFramebuffer(this._currentRenderTarget);
  13855. }
  13856. else {
  13857. this.bindUnboundFramebuffer(null);
  13858. }
  13859. if (this._cachedViewport) {
  13860. this.setViewport(this._cachedViewport);
  13861. }
  13862. this.wipeCaches();
  13863. };
  13864. // UBOs
  13865. /**
  13866. * Create an uniform buffer
  13867. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13868. * @param elements defines the content of the uniform buffer
  13869. * @returns the webGL uniform buffer
  13870. */
  13871. Engine.prototype.createUniformBuffer = function (elements) {
  13872. var ubo = this._gl.createBuffer();
  13873. if (!ubo) {
  13874. throw new Error("Unable to create uniform buffer");
  13875. }
  13876. this.bindUniformBuffer(ubo);
  13877. if (elements instanceof Float32Array) {
  13878. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13879. }
  13880. else {
  13881. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13882. }
  13883. this.bindUniformBuffer(null);
  13884. ubo.references = 1;
  13885. return ubo;
  13886. };
  13887. /**
  13888. * Create a dynamic uniform buffer
  13889. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13890. * @param elements defines the content of the uniform buffer
  13891. * @returns the webGL uniform buffer
  13892. */
  13893. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13894. var ubo = this._gl.createBuffer();
  13895. if (!ubo) {
  13896. throw new Error("Unable to create dynamic uniform buffer");
  13897. }
  13898. this.bindUniformBuffer(ubo);
  13899. if (elements instanceof Float32Array) {
  13900. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13901. }
  13902. else {
  13903. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13904. }
  13905. this.bindUniformBuffer(null);
  13906. ubo.references = 1;
  13907. return ubo;
  13908. };
  13909. /**
  13910. * Update an existing uniform buffer
  13911. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13912. * @param uniformBuffer defines the target uniform buffer
  13913. * @param elements defines the content to update
  13914. * @param offset defines the offset in the uniform buffer where update should start
  13915. * @param count defines the size of the data to update
  13916. */
  13917. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13918. this.bindUniformBuffer(uniformBuffer);
  13919. if (offset === undefined) {
  13920. offset = 0;
  13921. }
  13922. if (count === undefined) {
  13923. if (elements instanceof Float32Array) {
  13924. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13925. }
  13926. else {
  13927. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13928. }
  13929. }
  13930. else {
  13931. if (elements instanceof Float32Array) {
  13932. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13933. }
  13934. else {
  13935. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13936. }
  13937. }
  13938. this.bindUniformBuffer(null);
  13939. };
  13940. // VBOs
  13941. Engine.prototype._resetVertexBufferBinding = function () {
  13942. this.bindArrayBuffer(null);
  13943. this._cachedVertexBuffers = null;
  13944. };
  13945. /**
  13946. * Creates a vertex buffer
  13947. * @param data the data for the vertex buffer
  13948. * @returns the new WebGL static buffer
  13949. */
  13950. Engine.prototype.createVertexBuffer = function (data) {
  13951. var vbo = this._gl.createBuffer();
  13952. if (!vbo) {
  13953. throw new Error("Unable to create vertex buffer");
  13954. }
  13955. this.bindArrayBuffer(vbo);
  13956. if (data instanceof Array) {
  13957. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13958. }
  13959. else {
  13960. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13961. }
  13962. this._resetVertexBufferBinding();
  13963. vbo.references = 1;
  13964. return vbo;
  13965. };
  13966. /**
  13967. * Creates a dynamic vertex buffer
  13968. * @param data the data for the dynamic vertex buffer
  13969. * @returns the new WebGL dynamic buffer
  13970. */
  13971. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13972. var vbo = this._gl.createBuffer();
  13973. if (!vbo) {
  13974. throw new Error("Unable to create dynamic vertex buffer");
  13975. }
  13976. this.bindArrayBuffer(vbo);
  13977. if (data instanceof Array) {
  13978. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13979. }
  13980. else {
  13981. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13982. }
  13983. this._resetVertexBufferBinding();
  13984. vbo.references = 1;
  13985. return vbo;
  13986. };
  13987. /**
  13988. * Update a dynamic index buffer
  13989. * @param indexBuffer defines the target index buffer
  13990. * @param indices defines the data to update
  13991. * @param offset defines the offset in the target index buffer where update should start
  13992. */
  13993. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13994. if (offset === void 0) { offset = 0; }
  13995. // Force cache update
  13996. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13997. this.bindIndexBuffer(indexBuffer);
  13998. var arrayBuffer;
  13999. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14000. arrayBuffer = indices;
  14001. }
  14002. else {
  14003. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14004. }
  14005. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14006. this._resetIndexBufferBinding();
  14007. };
  14008. /**
  14009. * Updates a dynamic vertex buffer.
  14010. * @param vertexBuffer the vertex buffer to update
  14011. * @param data the data used to update the vertex buffer
  14012. * @param byteOffset the byte offset of the data
  14013. * @param byteLength the byte length of the data
  14014. */
  14015. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14016. this.bindArrayBuffer(vertexBuffer);
  14017. if (byteOffset === undefined) {
  14018. byteOffset = 0;
  14019. }
  14020. if (byteLength === undefined) {
  14021. if (data instanceof Array) {
  14022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14023. }
  14024. else {
  14025. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14026. }
  14027. }
  14028. else {
  14029. if (data instanceof Array) {
  14030. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14031. }
  14032. else {
  14033. if (data instanceof ArrayBuffer) {
  14034. data = new Uint8Array(data, byteOffset, byteLength);
  14035. }
  14036. else {
  14037. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14038. }
  14039. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14040. }
  14041. }
  14042. this._resetVertexBufferBinding();
  14043. };
  14044. Engine.prototype._resetIndexBufferBinding = function () {
  14045. this.bindIndexBuffer(null);
  14046. this._cachedIndexBuffer = null;
  14047. };
  14048. /**
  14049. * Creates a new index buffer
  14050. * @param indices defines the content of the index buffer
  14051. * @param updatable defines if the index buffer must be updatable
  14052. * @returns a new webGL buffer
  14053. */
  14054. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14055. var vbo = this._gl.createBuffer();
  14056. if (!vbo) {
  14057. throw new Error("Unable to create index buffer");
  14058. }
  14059. this.bindIndexBuffer(vbo);
  14060. // Check for 32 bits indices
  14061. var arrayBuffer;
  14062. var need32Bits = false;
  14063. if (indices instanceof Uint16Array) {
  14064. arrayBuffer = indices;
  14065. }
  14066. else {
  14067. //check 32 bit support
  14068. if (this._caps.uintIndices) {
  14069. if (indices instanceof Uint32Array) {
  14070. arrayBuffer = indices;
  14071. need32Bits = true;
  14072. }
  14073. else {
  14074. //number[] or Int32Array, check if 32 bit is necessary
  14075. for (var index = 0; index < indices.length; index++) {
  14076. if (indices[index] > 65535) {
  14077. need32Bits = true;
  14078. break;
  14079. }
  14080. }
  14081. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14082. }
  14083. }
  14084. else {
  14085. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14086. arrayBuffer = new Uint16Array(indices);
  14087. }
  14088. }
  14089. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14090. this._resetIndexBufferBinding();
  14091. vbo.references = 1;
  14092. vbo.is32Bits = need32Bits;
  14093. return vbo;
  14094. };
  14095. /**
  14096. * Bind a webGL buffer to the webGL context
  14097. * @param buffer defines the buffer to bind
  14098. */
  14099. Engine.prototype.bindArrayBuffer = function (buffer) {
  14100. if (!this._vaoRecordInProgress) {
  14101. this._unbindVertexArrayObject();
  14102. }
  14103. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14104. };
  14105. /**
  14106. * Bind an uniform buffer to the current webGL context
  14107. * @param buffer defines the buffer to bind
  14108. */
  14109. Engine.prototype.bindUniformBuffer = function (buffer) {
  14110. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14111. };
  14112. /**
  14113. * Bind a buffer to the current webGL context at a given location
  14114. * @param buffer defines the buffer to bind
  14115. * @param location defines the index where to bind the buffer
  14116. */
  14117. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14118. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14119. };
  14120. /**
  14121. * Bind a specific block at a given index in a specific shader program
  14122. * @param shaderProgram defines the shader program
  14123. * @param blockName defines the block name
  14124. * @param index defines the index where to bind the block
  14125. */
  14126. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14127. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14128. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14129. };
  14130. Engine.prototype.bindIndexBuffer = function (buffer) {
  14131. if (!this._vaoRecordInProgress) {
  14132. this._unbindVertexArrayObject();
  14133. }
  14134. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14135. };
  14136. Engine.prototype.bindBuffer = function (buffer, target) {
  14137. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14138. this._gl.bindBuffer(target, buffer);
  14139. this._currentBoundBuffer[target] = buffer;
  14140. }
  14141. };
  14142. /**
  14143. * update the bound buffer with the given data
  14144. * @param data defines the data to update
  14145. */
  14146. Engine.prototype.updateArrayBuffer = function (data) {
  14147. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14148. };
  14149. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14150. var pointer = this._currentBufferPointers[indx];
  14151. var changed = false;
  14152. if (!pointer.active) {
  14153. changed = true;
  14154. pointer.active = true;
  14155. pointer.index = indx;
  14156. pointer.size = size;
  14157. pointer.type = type;
  14158. pointer.normalized = normalized;
  14159. pointer.stride = stride;
  14160. pointer.offset = offset;
  14161. pointer.buffer = buffer;
  14162. }
  14163. else {
  14164. if (pointer.buffer !== buffer) {
  14165. pointer.buffer = buffer;
  14166. changed = true;
  14167. }
  14168. if (pointer.size !== size) {
  14169. pointer.size = size;
  14170. changed = true;
  14171. }
  14172. if (pointer.type !== type) {
  14173. pointer.type = type;
  14174. changed = true;
  14175. }
  14176. if (pointer.normalized !== normalized) {
  14177. pointer.normalized = normalized;
  14178. changed = true;
  14179. }
  14180. if (pointer.stride !== stride) {
  14181. pointer.stride = stride;
  14182. changed = true;
  14183. }
  14184. if (pointer.offset !== offset) {
  14185. pointer.offset = offset;
  14186. changed = true;
  14187. }
  14188. }
  14189. if (changed || this._vaoRecordInProgress) {
  14190. this.bindArrayBuffer(buffer);
  14191. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14192. }
  14193. };
  14194. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14195. if (indexBuffer == null) {
  14196. return;
  14197. }
  14198. if (this._cachedIndexBuffer !== indexBuffer) {
  14199. this._cachedIndexBuffer = indexBuffer;
  14200. this.bindIndexBuffer(indexBuffer);
  14201. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14202. }
  14203. };
  14204. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14205. var attributes = effect.getAttributesNames();
  14206. if (!this._vaoRecordInProgress) {
  14207. this._unbindVertexArrayObject();
  14208. }
  14209. this.unbindAllAttributes();
  14210. for (var index = 0; index < attributes.length; index++) {
  14211. var order = effect.getAttributeLocation(index);
  14212. if (order >= 0) {
  14213. var vertexBuffer = vertexBuffers[attributes[index]];
  14214. if (!vertexBuffer) {
  14215. continue;
  14216. }
  14217. this._gl.enableVertexAttribArray(order);
  14218. if (!this._vaoRecordInProgress) {
  14219. this._vertexAttribArraysEnabled[order] = true;
  14220. }
  14221. var buffer = vertexBuffer.getBuffer();
  14222. if (buffer) {
  14223. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14224. if (vertexBuffer.getIsInstanced()) {
  14225. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14226. if (!this._vaoRecordInProgress) {
  14227. this._currentInstanceLocations.push(order);
  14228. this._currentInstanceBuffers.push(buffer);
  14229. }
  14230. }
  14231. }
  14232. }
  14233. }
  14234. };
  14235. /**
  14236. * Records a vertex array object
  14237. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14238. * @param vertexBuffers defines the list of vertex buffers to store
  14239. * @param indexBuffer defines the index buffer to store
  14240. * @param effect defines the effect to store
  14241. * @returns the new vertex array object
  14242. */
  14243. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14244. var vao = this._gl.createVertexArray();
  14245. this._vaoRecordInProgress = true;
  14246. this._gl.bindVertexArray(vao);
  14247. this._mustWipeVertexAttributes = true;
  14248. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14249. this.bindIndexBuffer(indexBuffer);
  14250. this._vaoRecordInProgress = false;
  14251. this._gl.bindVertexArray(null);
  14252. return vao;
  14253. };
  14254. /**
  14255. * Bind a specific vertex array object
  14256. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14257. * @param vertexArrayObject defines the vertex array object to bind
  14258. * @param indexBuffer defines the index buffer to bind
  14259. */
  14260. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14261. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14262. this._cachedVertexArrayObject = vertexArrayObject;
  14263. this._gl.bindVertexArray(vertexArrayObject);
  14264. this._cachedVertexBuffers = null;
  14265. this._cachedIndexBuffer = null;
  14266. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14267. this._mustWipeVertexAttributes = true;
  14268. }
  14269. };
  14270. /**
  14271. * Bind webGl buffers directly to the webGL context
  14272. * @param vertexBuffer defines the vertex buffer to bind
  14273. * @param indexBuffer defines the index buffer to bind
  14274. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14275. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14276. * @param effect defines the effect associated with the vertex buffer
  14277. */
  14278. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14279. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14280. this._cachedVertexBuffers = vertexBuffer;
  14281. this._cachedEffectForVertexBuffers = effect;
  14282. var attributesCount = effect.getAttributesCount();
  14283. this._unbindVertexArrayObject();
  14284. this.unbindAllAttributes();
  14285. var offset = 0;
  14286. for (var index = 0; index < attributesCount; index++) {
  14287. if (index < vertexDeclaration.length) {
  14288. var order = effect.getAttributeLocation(index);
  14289. if (order >= 0) {
  14290. this._gl.enableVertexAttribArray(order);
  14291. this._vertexAttribArraysEnabled[order] = true;
  14292. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14293. }
  14294. offset += vertexDeclaration[index] * 4;
  14295. }
  14296. }
  14297. }
  14298. this._bindIndexBufferWithCache(indexBuffer);
  14299. };
  14300. Engine.prototype._unbindVertexArrayObject = function () {
  14301. if (!this._cachedVertexArrayObject) {
  14302. return;
  14303. }
  14304. this._cachedVertexArrayObject = null;
  14305. this._gl.bindVertexArray(null);
  14306. };
  14307. /**
  14308. * Bind a list of vertex buffers to the webGL context
  14309. * @param vertexBuffers defines the list of vertex buffers to bind
  14310. * @param indexBuffer defines the index buffer to bind
  14311. * @param effect defines the effect associated with the vertex buffers
  14312. */
  14313. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14314. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14315. this._cachedVertexBuffers = vertexBuffers;
  14316. this._cachedEffectForVertexBuffers = effect;
  14317. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14318. }
  14319. this._bindIndexBufferWithCache(indexBuffer);
  14320. };
  14321. /**
  14322. * Unbind all instance attributes
  14323. */
  14324. Engine.prototype.unbindInstanceAttributes = function () {
  14325. var boundBuffer;
  14326. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14327. var instancesBuffer = this._currentInstanceBuffers[i];
  14328. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14329. boundBuffer = instancesBuffer;
  14330. this.bindArrayBuffer(instancesBuffer);
  14331. }
  14332. var offsetLocation = this._currentInstanceLocations[i];
  14333. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14334. }
  14335. this._currentInstanceBuffers.length = 0;
  14336. this._currentInstanceLocations.length = 0;
  14337. };
  14338. /**
  14339. * Release and free the memory of a vertex array object
  14340. * @param vao defines the vertex array object to delete
  14341. */
  14342. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14343. this._gl.deleteVertexArray(vao);
  14344. };
  14345. /** @hidden */
  14346. Engine.prototype._releaseBuffer = function (buffer) {
  14347. buffer.references--;
  14348. if (buffer.references === 0) {
  14349. this._gl.deleteBuffer(buffer);
  14350. return true;
  14351. }
  14352. return false;
  14353. };
  14354. /**
  14355. * Creates a webGL buffer to use with instanciation
  14356. * @param capacity defines the size of the buffer
  14357. * @returns the webGL buffer
  14358. */
  14359. Engine.prototype.createInstancesBuffer = function (capacity) {
  14360. var buffer = this._gl.createBuffer();
  14361. if (!buffer) {
  14362. throw new Error("Unable to create instance buffer");
  14363. }
  14364. buffer.capacity = capacity;
  14365. this.bindArrayBuffer(buffer);
  14366. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14367. return buffer;
  14368. };
  14369. /**
  14370. * Delete a webGL buffer used with instanciation
  14371. * @param buffer defines the webGL buffer to delete
  14372. */
  14373. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14374. this._gl.deleteBuffer(buffer);
  14375. };
  14376. /**
  14377. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14378. * @param instancesBuffer defines the webGL buffer to update and bind
  14379. * @param data defines the data to store in the buffer
  14380. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14381. */
  14382. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14383. this.bindArrayBuffer(instancesBuffer);
  14384. if (data) {
  14385. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14386. }
  14387. if (offsetLocations[0].index !== undefined) {
  14388. var stride = 0;
  14389. for (var i = 0; i < offsetLocations.length; i++) {
  14390. var ai = offsetLocations[i];
  14391. stride += ai.attributeSize * 4;
  14392. }
  14393. for (var i = 0; i < offsetLocations.length; i++) {
  14394. var ai = offsetLocations[i];
  14395. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14396. this._gl.enableVertexAttribArray(ai.index);
  14397. this._vertexAttribArraysEnabled[ai.index] = true;
  14398. }
  14399. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14400. this._gl.vertexAttribDivisor(ai.index, 1);
  14401. this._currentInstanceLocations.push(ai.index);
  14402. this._currentInstanceBuffers.push(instancesBuffer);
  14403. }
  14404. }
  14405. else {
  14406. for (var index = 0; index < 4; index++) {
  14407. var offsetLocation = offsetLocations[index];
  14408. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14409. this._gl.enableVertexAttribArray(offsetLocation);
  14410. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14411. }
  14412. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14413. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14414. this._currentInstanceLocations.push(offsetLocation);
  14415. this._currentInstanceBuffers.push(instancesBuffer);
  14416. }
  14417. }
  14418. };
  14419. /**
  14420. * Apply all cached states (depth, culling, stencil and alpha)
  14421. */
  14422. Engine.prototype.applyStates = function () {
  14423. this._depthCullingState.apply(this._gl);
  14424. this._stencilState.apply(this._gl);
  14425. this._alphaState.apply(this._gl);
  14426. };
  14427. /**
  14428. * Send a draw order
  14429. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14430. * @param indexStart defines the starting index
  14431. * @param indexCount defines the number of index to draw
  14432. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14433. */
  14434. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14435. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14436. };
  14437. /**
  14438. * Draw a list of points
  14439. * @param verticesStart defines the index of first vertex to draw
  14440. * @param verticesCount defines the count of vertices to draw
  14441. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14442. */
  14443. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14444. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14445. };
  14446. /**
  14447. * Draw a list of unindexed primitives
  14448. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14449. * @param verticesStart defines the index of first vertex to draw
  14450. * @param verticesCount defines the count of vertices to draw
  14451. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14452. */
  14453. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14454. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14455. };
  14456. /**
  14457. * Draw a list of indexed primitives
  14458. * @param fillMode defines the primitive to use
  14459. * @param indexStart defines the starting index
  14460. * @param indexCount defines the number of index to draw
  14461. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14462. */
  14463. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14464. // Apply states
  14465. this.applyStates();
  14466. this._drawCalls.addCount(1, false);
  14467. // Render
  14468. var drawMode = this._drawMode(fillMode);
  14469. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14470. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14471. if (instancesCount) {
  14472. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14473. }
  14474. else {
  14475. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14476. }
  14477. };
  14478. /**
  14479. * Draw a list of unindexed primitives
  14480. * @param fillMode defines the primitive to use
  14481. * @param verticesStart defines the index of first vertex to draw
  14482. * @param verticesCount defines the count of vertices to draw
  14483. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14484. */
  14485. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14486. // Apply states
  14487. this.applyStates();
  14488. this._drawCalls.addCount(1, false);
  14489. var drawMode = this._drawMode(fillMode);
  14490. if (instancesCount) {
  14491. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14492. }
  14493. else {
  14494. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14495. }
  14496. };
  14497. Engine.prototype._drawMode = function (fillMode) {
  14498. switch (fillMode) {
  14499. // Triangle views
  14500. case BABYLON.Material.TriangleFillMode:
  14501. return this._gl.TRIANGLES;
  14502. case BABYLON.Material.PointFillMode:
  14503. return this._gl.POINTS;
  14504. case BABYLON.Material.WireFrameFillMode:
  14505. return this._gl.LINES;
  14506. // Draw modes
  14507. case BABYLON.Material.PointListDrawMode:
  14508. return this._gl.POINTS;
  14509. case BABYLON.Material.LineListDrawMode:
  14510. return this._gl.LINES;
  14511. case BABYLON.Material.LineLoopDrawMode:
  14512. return this._gl.LINE_LOOP;
  14513. case BABYLON.Material.LineStripDrawMode:
  14514. return this._gl.LINE_STRIP;
  14515. case BABYLON.Material.TriangleStripDrawMode:
  14516. return this._gl.TRIANGLE_STRIP;
  14517. case BABYLON.Material.TriangleFanDrawMode:
  14518. return this._gl.TRIANGLE_FAN;
  14519. default:
  14520. return this._gl.TRIANGLES;
  14521. }
  14522. };
  14523. // Shaders
  14524. /** @hidden */
  14525. Engine.prototype._releaseEffect = function (effect) {
  14526. if (this._compiledEffects[effect._key]) {
  14527. delete this._compiledEffects[effect._key];
  14528. this._deleteProgram(effect.getProgram());
  14529. }
  14530. };
  14531. /** @hidden */
  14532. Engine.prototype._deleteProgram = function (program) {
  14533. if (program) {
  14534. program.__SPECTOR_rebuildProgram = null;
  14535. if (program.transformFeedback) {
  14536. this.deleteTransformFeedback(program.transformFeedback);
  14537. program.transformFeedback = null;
  14538. }
  14539. this._gl.deleteProgram(program);
  14540. }
  14541. };
  14542. /**
  14543. * Create a new effect (used to store vertex/fragment shaders)
  14544. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14545. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14546. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14547. * @param samplers defines an array of string used to represent textures
  14548. * @param defines defines the string containing the defines to use to compile the shaders
  14549. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14550. * @param onCompiled defines a function to call when the effect creation is successful
  14551. * @param onError defines a function to call when the effect creation has failed
  14552. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14553. * @returns the new Effect
  14554. */
  14555. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14556. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14557. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14558. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14559. if (this._compiledEffects[name]) {
  14560. var compiledEffect = this._compiledEffects[name];
  14561. if (onCompiled && compiledEffect.isReady()) {
  14562. onCompiled(compiledEffect);
  14563. }
  14564. return compiledEffect;
  14565. }
  14566. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14567. effect._key = name;
  14568. this._compiledEffects[name] = effect;
  14569. return effect;
  14570. };
  14571. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14572. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14573. };
  14574. Engine.prototype._compileRawShader = function (source, type) {
  14575. var gl = this._gl;
  14576. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14577. if (!shader) {
  14578. throw new Error("Something went wrong while compile the shader.");
  14579. }
  14580. gl.shaderSource(shader, source);
  14581. gl.compileShader(shader);
  14582. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14583. var log = gl.getShaderInfoLog(shader);
  14584. if (log) {
  14585. throw new Error(log);
  14586. }
  14587. }
  14588. return shader;
  14589. };
  14590. /**
  14591. * Directly creates a webGL program
  14592. * @param vertexCode defines the vertex shader code to use
  14593. * @param fragmentCode defines the fragment shader code to use
  14594. * @param context defines the webGL context to use (if not set, the current one will be used)
  14595. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14596. * @returns the new webGL program
  14597. */
  14598. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14599. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14600. context = context || this._gl;
  14601. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14602. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14603. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14604. };
  14605. /**
  14606. * Creates a webGL program
  14607. * @param vertexCode defines the vertex shader code to use
  14608. * @param fragmentCode defines the fragment shader code to use
  14609. * @param defines defines the string containing the defines to use to compile the shaders
  14610. * @param context defines the webGL context to use (if not set, the current one will be used)
  14611. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14612. * @returns the new webGL program
  14613. */
  14614. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14615. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14616. context = context || this._gl;
  14617. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14618. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14619. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14620. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14621. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14622. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14623. return program;
  14624. };
  14625. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14626. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14627. var shaderProgram = context.createProgram();
  14628. if (!shaderProgram) {
  14629. throw new Error("Unable to create program");
  14630. }
  14631. context.attachShader(shaderProgram, vertexShader);
  14632. context.attachShader(shaderProgram, fragmentShader);
  14633. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14634. var transformFeedback = this.createTransformFeedback();
  14635. this.bindTransformFeedback(transformFeedback);
  14636. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14637. shaderProgram.transformFeedback = transformFeedback;
  14638. }
  14639. context.linkProgram(shaderProgram);
  14640. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14641. this.bindTransformFeedback(null);
  14642. }
  14643. shaderProgram.context = context;
  14644. shaderProgram.vertexShader = vertexShader;
  14645. shaderProgram.fragmentShader = fragmentShader;
  14646. if (!this._caps.parallelShaderCompile) {
  14647. this._finalizeProgram(shaderProgram);
  14648. }
  14649. else {
  14650. shaderProgram.isParallelCompiled = true;
  14651. }
  14652. return shaderProgram;
  14653. };
  14654. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14655. var context = shaderProgram.context;
  14656. var vertexShader = shaderProgram.vertexShader;
  14657. var fragmentShader = shaderProgram.fragmentShader;
  14658. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14659. if (!linked) {
  14660. var error = context.getProgramInfoLog(shaderProgram);
  14661. if (error) {
  14662. throw new Error(error);
  14663. }
  14664. }
  14665. if (this.validateShaderPrograms) {
  14666. context.validateProgram(shaderProgram);
  14667. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14668. if (!validated) {
  14669. var error = context.getProgramInfoLog(shaderProgram);
  14670. if (error) {
  14671. throw new Error(error);
  14672. }
  14673. }
  14674. }
  14675. context.deleteShader(vertexShader);
  14676. context.deleteShader(fragmentShader);
  14677. shaderProgram.context = undefined;
  14678. shaderProgram.vertexShader = undefined;
  14679. shaderProgram.fragmentShader = undefined;
  14680. if (shaderProgram.onCompiled) {
  14681. shaderProgram.onCompiled();
  14682. shaderProgram.onCompiled = undefined;
  14683. }
  14684. };
  14685. /** @hidden */
  14686. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14687. if (!shaderProgram.isParallelCompiled) {
  14688. return true;
  14689. }
  14690. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14691. this._finalizeProgram(shaderProgram);
  14692. return true;
  14693. }
  14694. return false;
  14695. };
  14696. /** @hidden */
  14697. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14698. if (!shaderProgram.isParallelCompiled) {
  14699. action();
  14700. return;
  14701. }
  14702. shaderProgram.onCompiled = action;
  14703. };
  14704. /**
  14705. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14706. * @param shaderProgram defines the webGL program to use
  14707. * @param uniformsNames defines the list of uniform names
  14708. * @returns an array of webGL uniform locations
  14709. */
  14710. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14711. var results = new Array();
  14712. for (var index = 0; index < uniformsNames.length; index++) {
  14713. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14714. }
  14715. return results;
  14716. };
  14717. /**
  14718. * Gets the lsit of active attributes for a given webGL program
  14719. * @param shaderProgram defines the webGL program to use
  14720. * @param attributesNames defines the list of attribute names to get
  14721. * @returns an array of indices indicating the offset of each attribute
  14722. */
  14723. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14724. var results = [];
  14725. for (var index = 0; index < attributesNames.length; index++) {
  14726. try {
  14727. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14728. }
  14729. catch (e) {
  14730. results.push(-1);
  14731. }
  14732. }
  14733. return results;
  14734. };
  14735. /**
  14736. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14737. * @param effect defines the effect to activate
  14738. */
  14739. Engine.prototype.enableEffect = function (effect) {
  14740. if (!effect || effect === this._currentEffect) {
  14741. return;
  14742. }
  14743. // Use program
  14744. this.bindSamplers(effect);
  14745. this._currentEffect = effect;
  14746. if (effect.onBind) {
  14747. effect.onBind(effect);
  14748. }
  14749. if (effect._onBindObservable) {
  14750. effect._onBindObservable.notifyObservers(effect);
  14751. }
  14752. };
  14753. /**
  14754. * Set the value of an uniform to an array of int32
  14755. * @param uniform defines the webGL uniform location where to store the value
  14756. * @param array defines the array of int32 to store
  14757. */
  14758. Engine.prototype.setIntArray = function (uniform, array) {
  14759. if (!uniform) {
  14760. return;
  14761. }
  14762. this._gl.uniform1iv(uniform, array);
  14763. };
  14764. /**
  14765. * Set the value of an uniform to an array of int32 (stored as vec2)
  14766. * @param uniform defines the webGL uniform location where to store the value
  14767. * @param array defines the array of int32 to store
  14768. */
  14769. Engine.prototype.setIntArray2 = function (uniform, array) {
  14770. if (!uniform || array.length % 2 !== 0) {
  14771. return;
  14772. }
  14773. this._gl.uniform2iv(uniform, array);
  14774. };
  14775. /**
  14776. * Set the value of an uniform to an array of int32 (stored as vec3)
  14777. * @param uniform defines the webGL uniform location where to store the value
  14778. * @param array defines the array of int32 to store
  14779. */
  14780. Engine.prototype.setIntArray3 = function (uniform, array) {
  14781. if (!uniform || array.length % 3 !== 0) {
  14782. return;
  14783. }
  14784. this._gl.uniform3iv(uniform, array);
  14785. };
  14786. /**
  14787. * Set the value of an uniform to an array of int32 (stored as vec4)
  14788. * @param uniform defines the webGL uniform location where to store the value
  14789. * @param array defines the array of int32 to store
  14790. */
  14791. Engine.prototype.setIntArray4 = function (uniform, array) {
  14792. if (!uniform || array.length % 4 !== 0) {
  14793. return;
  14794. }
  14795. this._gl.uniform4iv(uniform, array);
  14796. };
  14797. /**
  14798. * Set the value of an uniform to an array of float32
  14799. * @param uniform defines the webGL uniform location where to store the value
  14800. * @param array defines the array of float32 to store
  14801. */
  14802. Engine.prototype.setFloatArray = function (uniform, array) {
  14803. if (!uniform) {
  14804. return;
  14805. }
  14806. this._gl.uniform1fv(uniform, array);
  14807. };
  14808. /**
  14809. * Set the value of an uniform to an array of float32 (stored as vec2)
  14810. * @param uniform defines the webGL uniform location where to store the value
  14811. * @param array defines the array of float32 to store
  14812. */
  14813. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14814. if (!uniform || array.length % 2 !== 0) {
  14815. return;
  14816. }
  14817. this._gl.uniform2fv(uniform, array);
  14818. };
  14819. /**
  14820. * Set the value of an uniform to an array of float32 (stored as vec3)
  14821. * @param uniform defines the webGL uniform location where to store the value
  14822. * @param array defines the array of float32 to store
  14823. */
  14824. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14825. if (!uniform || array.length % 3 !== 0) {
  14826. return;
  14827. }
  14828. this._gl.uniform3fv(uniform, array);
  14829. };
  14830. /**
  14831. * Set the value of an uniform to an array of float32 (stored as vec4)
  14832. * @param uniform defines the webGL uniform location where to store the value
  14833. * @param array defines the array of float32 to store
  14834. */
  14835. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14836. if (!uniform || array.length % 4 !== 0) {
  14837. return;
  14838. }
  14839. this._gl.uniform4fv(uniform, array);
  14840. };
  14841. /**
  14842. * Set the value of an uniform to an array of number
  14843. * @param uniform defines the webGL uniform location where to store the value
  14844. * @param array defines the array of number to store
  14845. */
  14846. Engine.prototype.setArray = function (uniform, array) {
  14847. if (!uniform) {
  14848. return;
  14849. }
  14850. this._gl.uniform1fv(uniform, array);
  14851. };
  14852. /**
  14853. * Set the value of an uniform to an array of number (stored as vec2)
  14854. * @param uniform defines the webGL uniform location where to store the value
  14855. * @param array defines the array of number to store
  14856. */
  14857. Engine.prototype.setArray2 = function (uniform, array) {
  14858. if (!uniform || array.length % 2 !== 0) {
  14859. return;
  14860. }
  14861. this._gl.uniform2fv(uniform, array);
  14862. };
  14863. /**
  14864. * Set the value of an uniform to an array of number (stored as vec3)
  14865. * @param uniform defines the webGL uniform location where to store the value
  14866. * @param array defines the array of number to store
  14867. */
  14868. Engine.prototype.setArray3 = function (uniform, array) {
  14869. if (!uniform || array.length % 3 !== 0) {
  14870. return;
  14871. }
  14872. this._gl.uniform3fv(uniform, array);
  14873. };
  14874. /**
  14875. * Set the value of an uniform to an array of number (stored as vec4)
  14876. * @param uniform defines the webGL uniform location where to store the value
  14877. * @param array defines the array of number to store
  14878. */
  14879. Engine.prototype.setArray4 = function (uniform, array) {
  14880. if (!uniform || array.length % 4 !== 0) {
  14881. return;
  14882. }
  14883. this._gl.uniform4fv(uniform, array);
  14884. };
  14885. /**
  14886. * Set the value of an uniform to an array of float32 (stored as matrices)
  14887. * @param uniform defines the webGL uniform location where to store the value
  14888. * @param matrices defines the array of float32 to store
  14889. */
  14890. Engine.prototype.setMatrices = function (uniform, matrices) {
  14891. if (!uniform) {
  14892. return;
  14893. }
  14894. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14895. };
  14896. /**
  14897. * Set the value of an uniform to a matrix
  14898. * @param uniform defines the webGL uniform location where to store the value
  14899. * @param matrix defines the matrix to store
  14900. */
  14901. Engine.prototype.setMatrix = function (uniform, matrix) {
  14902. if (!uniform) {
  14903. return;
  14904. }
  14905. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14906. };
  14907. /**
  14908. * Set the value of an uniform to a matrix (3x3)
  14909. * @param uniform defines the webGL uniform location where to store the value
  14910. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14911. */
  14912. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14913. if (!uniform) {
  14914. return;
  14915. }
  14916. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14917. };
  14918. /**
  14919. * Set the value of an uniform to a matrix (2x2)
  14920. * @param uniform defines the webGL uniform location where to store the value
  14921. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14922. */
  14923. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14924. if (!uniform) {
  14925. return;
  14926. }
  14927. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14928. };
  14929. /**
  14930. * Set the value of an uniform to a number (int)
  14931. * @param uniform defines the webGL uniform location where to store the value
  14932. * @param value defines the int number to store
  14933. */
  14934. Engine.prototype.setInt = function (uniform, value) {
  14935. if (!uniform) {
  14936. return;
  14937. }
  14938. this._gl.uniform1i(uniform, value);
  14939. };
  14940. /**
  14941. * Set the value of an uniform to a number (float)
  14942. * @param uniform defines the webGL uniform location where to store the value
  14943. * @param value defines the float number to store
  14944. */
  14945. Engine.prototype.setFloat = function (uniform, value) {
  14946. if (!uniform) {
  14947. return;
  14948. }
  14949. this._gl.uniform1f(uniform, value);
  14950. };
  14951. /**
  14952. * Set the value of an uniform to a vec2
  14953. * @param uniform defines the webGL uniform location where to store the value
  14954. * @param x defines the 1st component of the value
  14955. * @param y defines the 2nd component of the value
  14956. */
  14957. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14958. if (!uniform) {
  14959. return;
  14960. }
  14961. this._gl.uniform2f(uniform, x, y);
  14962. };
  14963. /**
  14964. * Set the value of an uniform to a vec3
  14965. * @param uniform defines the webGL uniform location where to store the value
  14966. * @param x defines the 1st component of the value
  14967. * @param y defines the 2nd component of the value
  14968. * @param z defines the 3rd component of the value
  14969. */
  14970. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14971. if (!uniform) {
  14972. return;
  14973. }
  14974. this._gl.uniform3f(uniform, x, y, z);
  14975. };
  14976. /**
  14977. * Set the value of an uniform to a boolean
  14978. * @param uniform defines the webGL uniform location where to store the value
  14979. * @param bool defines the boolean to store
  14980. */
  14981. Engine.prototype.setBool = function (uniform, bool) {
  14982. if (!uniform) {
  14983. return;
  14984. }
  14985. this._gl.uniform1i(uniform, bool);
  14986. };
  14987. /**
  14988. * Set the value of an uniform to a vec4
  14989. * @param uniform defines the webGL uniform location where to store the value
  14990. * @param x defines the 1st component of the value
  14991. * @param y defines the 2nd component of the value
  14992. * @param z defines the 3rd component of the value
  14993. * @param w defines the 4th component of the value
  14994. */
  14995. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14996. if (!uniform) {
  14997. return;
  14998. }
  14999. this._gl.uniform4f(uniform, x, y, z, w);
  15000. };
  15001. /**
  15002. * Set the value of an uniform to a Color3
  15003. * @param uniform defines the webGL uniform location where to store the value
  15004. * @param color3 defines the color to store
  15005. */
  15006. Engine.prototype.setColor3 = function (uniform, color3) {
  15007. if (!uniform) {
  15008. return;
  15009. }
  15010. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15011. };
  15012. /**
  15013. * Set the value of an uniform to a Color3 and an alpha value
  15014. * @param uniform defines the webGL uniform location where to store the value
  15015. * @param color3 defines the color to store
  15016. * @param alpha defines the alpha component to store
  15017. */
  15018. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15019. if (!uniform) {
  15020. return;
  15021. }
  15022. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15023. };
  15024. /**
  15025. * Sets a Color4 on a uniform variable
  15026. * @param uniform defines the uniform location
  15027. * @param color4 defines the value to be set
  15028. */
  15029. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15030. if (!uniform) {
  15031. return;
  15032. }
  15033. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15034. };
  15035. // States
  15036. /**
  15037. * Set various states to the webGL context
  15038. * @param culling defines backface culling state
  15039. * @param zOffset defines the value to apply to zOffset (0 by default)
  15040. * @param force defines if states must be applied even if cache is up to date
  15041. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15042. */
  15043. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15044. if (zOffset === void 0) { zOffset = 0; }
  15045. if (reverseSide === void 0) { reverseSide = false; }
  15046. // Culling
  15047. if (this._depthCullingState.cull !== culling || force) {
  15048. this._depthCullingState.cull = culling;
  15049. }
  15050. // Cull face
  15051. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15052. if (this._depthCullingState.cullFace !== cullFace || force) {
  15053. this._depthCullingState.cullFace = cullFace;
  15054. }
  15055. // Z offset
  15056. this.setZOffset(zOffset);
  15057. // Front face
  15058. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15059. if (this._depthCullingState.frontFace !== frontFace || force) {
  15060. this._depthCullingState.frontFace = frontFace;
  15061. }
  15062. };
  15063. /**
  15064. * Set the z offset to apply to current rendering
  15065. * @param value defines the offset to apply
  15066. */
  15067. Engine.prototype.setZOffset = function (value) {
  15068. this._depthCullingState.zOffset = value;
  15069. };
  15070. /**
  15071. * Gets the current value of the zOffset
  15072. * @returns the current zOffset state
  15073. */
  15074. Engine.prototype.getZOffset = function () {
  15075. return this._depthCullingState.zOffset;
  15076. };
  15077. /**
  15078. * Enable or disable depth buffering
  15079. * @param enable defines the state to set
  15080. */
  15081. Engine.prototype.setDepthBuffer = function (enable) {
  15082. this._depthCullingState.depthTest = enable;
  15083. };
  15084. /**
  15085. * Gets a boolean indicating if depth writing is enabled
  15086. * @returns the current depth writing state
  15087. */
  15088. Engine.prototype.getDepthWrite = function () {
  15089. return this._depthCullingState.depthMask;
  15090. };
  15091. /**
  15092. * Enable or disable depth writing
  15093. * @param enable defines the state to set
  15094. */
  15095. Engine.prototype.setDepthWrite = function (enable) {
  15096. this._depthCullingState.depthMask = enable;
  15097. };
  15098. /**
  15099. * Enable or disable color writing
  15100. * @param enable defines the state to set
  15101. */
  15102. Engine.prototype.setColorWrite = function (enable) {
  15103. this._gl.colorMask(enable, enable, enable, enable);
  15104. this._colorWrite = enable;
  15105. };
  15106. /**
  15107. * Gets a boolean indicating if color writing is enabled
  15108. * @returns the current color writing state
  15109. */
  15110. Engine.prototype.getColorWrite = function () {
  15111. return this._colorWrite;
  15112. };
  15113. /**
  15114. * Sets alpha constants used by some alpha blending modes
  15115. * @param r defines the red component
  15116. * @param g defines the green component
  15117. * @param b defines the blue component
  15118. * @param a defines the alpha component
  15119. */
  15120. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15121. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15122. };
  15123. /**
  15124. * Sets the current alpha mode
  15125. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15126. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15127. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15128. */
  15129. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15130. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15131. if (this._alphaMode === mode) {
  15132. return;
  15133. }
  15134. switch (mode) {
  15135. case Engine.ALPHA_DISABLE:
  15136. this._alphaState.alphaBlend = false;
  15137. break;
  15138. case Engine.ALPHA_PREMULTIPLIED:
  15139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15140. this._alphaState.alphaBlend = true;
  15141. break;
  15142. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15144. this._alphaState.alphaBlend = true;
  15145. break;
  15146. case Engine.ALPHA_COMBINE:
  15147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15148. this._alphaState.alphaBlend = true;
  15149. break;
  15150. case Engine.ALPHA_ONEONE:
  15151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15152. this._alphaState.alphaBlend = true;
  15153. break;
  15154. case Engine.ALPHA_ADD:
  15155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15156. this._alphaState.alphaBlend = true;
  15157. break;
  15158. case Engine.ALPHA_SUBTRACT:
  15159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15160. this._alphaState.alphaBlend = true;
  15161. break;
  15162. case Engine.ALPHA_MULTIPLY:
  15163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15164. this._alphaState.alphaBlend = true;
  15165. break;
  15166. case Engine.ALPHA_MAXIMIZED:
  15167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15168. this._alphaState.alphaBlend = true;
  15169. break;
  15170. case Engine.ALPHA_INTERPOLATE:
  15171. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15172. this._alphaState.alphaBlend = true;
  15173. break;
  15174. case Engine.ALPHA_SCREENMODE:
  15175. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15176. this._alphaState.alphaBlend = true;
  15177. break;
  15178. }
  15179. if (!noDepthWriteChange) {
  15180. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15181. }
  15182. this._alphaMode = mode;
  15183. };
  15184. /**
  15185. * Gets the current alpha mode
  15186. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15187. * @returns the current alpha mode
  15188. */
  15189. Engine.prototype.getAlphaMode = function () {
  15190. return this._alphaMode;
  15191. };
  15192. // Textures
  15193. /**
  15194. * Clears the list of texture accessible through engine.
  15195. * This can help preventing texture load conflict due to name collision.
  15196. */
  15197. Engine.prototype.clearInternalTexturesCache = function () {
  15198. this._internalTexturesCache = [];
  15199. };
  15200. /**
  15201. * Force the entire cache to be cleared
  15202. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15203. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15204. */
  15205. Engine.prototype.wipeCaches = function (bruteForce) {
  15206. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15207. return;
  15208. }
  15209. this._currentEffect = null;
  15210. this._viewportCached.x = 0;
  15211. this._viewportCached.y = 0;
  15212. this._viewportCached.z = 0;
  15213. this._viewportCached.w = 0;
  15214. if (bruteForce) {
  15215. this.resetTextureCache();
  15216. this._currentProgram = null;
  15217. this._stencilState.reset();
  15218. this._depthCullingState.reset();
  15219. this.setDepthFunctionToLessOrEqual();
  15220. this._alphaState.reset();
  15221. this._unpackFlipYCached = null;
  15222. }
  15223. this._resetVertexBufferBinding();
  15224. this._cachedIndexBuffer = null;
  15225. this._cachedEffectForVertexBuffers = null;
  15226. this._unbindVertexArrayObject();
  15227. this.bindIndexBuffer(null);
  15228. };
  15229. /**
  15230. * Set the compressed texture format to use, based on the formats you have, and the formats
  15231. * supported by the hardware / browser.
  15232. *
  15233. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15234. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15235. * to API arguments needed to compressed textures. This puts the burden on the container
  15236. * generator to house the arcane code for determining these for current & future formats.
  15237. *
  15238. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15239. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15240. *
  15241. * Note: The result of this call is not taken into account when a texture is base64.
  15242. *
  15243. * @param formatsAvailable defines the list of those format families you have created
  15244. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15245. *
  15246. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15247. * @returns The extension selected.
  15248. */
  15249. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15250. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15251. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15252. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15253. return this._textureFormatInUse = this._texturesSupported[i];
  15254. }
  15255. }
  15256. }
  15257. // actively set format to nothing, to allow this to be called more than once
  15258. // and possibly fail the 2nd time
  15259. this._textureFormatInUse = null;
  15260. return null;
  15261. };
  15262. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15263. var gl = this._gl;
  15264. var magFilter = gl.NEAREST;
  15265. var minFilter = gl.NEAREST;
  15266. switch (samplingMode) {
  15267. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15268. magFilter = gl.LINEAR;
  15269. if (generateMipMaps) {
  15270. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15271. }
  15272. else {
  15273. minFilter = gl.LINEAR;
  15274. }
  15275. break;
  15276. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15277. magFilter = gl.LINEAR;
  15278. if (generateMipMaps) {
  15279. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15280. }
  15281. else {
  15282. minFilter = gl.LINEAR;
  15283. }
  15284. break;
  15285. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15286. magFilter = gl.NEAREST;
  15287. if (generateMipMaps) {
  15288. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15289. }
  15290. else {
  15291. minFilter = gl.NEAREST;
  15292. }
  15293. break;
  15294. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15295. magFilter = gl.NEAREST;
  15296. if (generateMipMaps) {
  15297. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15298. }
  15299. else {
  15300. minFilter = gl.NEAREST;
  15301. }
  15302. break;
  15303. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15304. magFilter = gl.NEAREST;
  15305. if (generateMipMaps) {
  15306. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15307. }
  15308. else {
  15309. minFilter = gl.LINEAR;
  15310. }
  15311. break;
  15312. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15313. magFilter = gl.NEAREST;
  15314. if (generateMipMaps) {
  15315. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15316. }
  15317. else {
  15318. minFilter = gl.LINEAR;
  15319. }
  15320. break;
  15321. case Engine.TEXTURE_NEAREST_LINEAR:
  15322. magFilter = gl.NEAREST;
  15323. minFilter = gl.LINEAR;
  15324. break;
  15325. case Engine.TEXTURE_NEAREST_NEAREST:
  15326. magFilter = gl.NEAREST;
  15327. minFilter = gl.NEAREST;
  15328. break;
  15329. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15330. magFilter = gl.LINEAR;
  15331. if (generateMipMaps) {
  15332. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15333. }
  15334. else {
  15335. minFilter = gl.NEAREST;
  15336. }
  15337. break;
  15338. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15339. magFilter = gl.LINEAR;
  15340. if (generateMipMaps) {
  15341. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15342. }
  15343. else {
  15344. minFilter = gl.NEAREST;
  15345. }
  15346. break;
  15347. case Engine.TEXTURE_LINEAR_LINEAR:
  15348. magFilter = gl.LINEAR;
  15349. minFilter = gl.LINEAR;
  15350. break;
  15351. case Engine.TEXTURE_LINEAR_NEAREST:
  15352. magFilter = gl.LINEAR;
  15353. minFilter = gl.NEAREST;
  15354. break;
  15355. }
  15356. return {
  15357. min: minFilter,
  15358. mag: magFilter
  15359. };
  15360. };
  15361. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15362. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15363. var img;
  15364. var onload = function () {
  15365. loadedImages[index] = img;
  15366. loadedImages._internalCount++;
  15367. if (scene) {
  15368. scene._removePendingData(img);
  15369. }
  15370. if (loadedImages._internalCount === 6) {
  15371. onfinish(loadedImages);
  15372. }
  15373. };
  15374. var onerror = function (message, exception) {
  15375. if (scene) {
  15376. scene._removePendingData(img);
  15377. }
  15378. if (onErrorCallBack) {
  15379. onErrorCallBack(message, exception);
  15380. }
  15381. };
  15382. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15383. if (scene) {
  15384. scene._addPendingData(img);
  15385. }
  15386. };
  15387. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15388. if (onError === void 0) { onError = null; }
  15389. var loadedImages = [];
  15390. loadedImages._internalCount = 0;
  15391. for (var index = 0; index < 6; index++) {
  15392. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15393. }
  15394. };
  15395. /** @hidden */
  15396. Engine.prototype._createTexture = function () {
  15397. var texture = this._gl.createTexture();
  15398. if (!texture) {
  15399. throw new Error("Unable to create texture");
  15400. }
  15401. return texture;
  15402. };
  15403. /**
  15404. * Usually called from BABYLON.Texture.ts.
  15405. * Passed information to create a WebGLTexture
  15406. * @param urlArg defines a value which contains one of the following:
  15407. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15408. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15409. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15410. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15411. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15412. * @param scene needed for loading to the correct scene
  15413. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15414. * @param onLoad optional callback to be called upon successful completion
  15415. * @param onError optional callback to be called upon failure
  15416. * @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
  15417. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15418. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15419. * @param forcedExtension defines the extension to use to pick the right loader
  15420. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15421. */
  15422. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15423. var _this = this;
  15424. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15425. if (onLoad === void 0) { onLoad = null; }
  15426. if (onError === void 0) { onError = null; }
  15427. if (buffer === void 0) { buffer = null; }
  15428. if (fallback === void 0) { fallback = null; }
  15429. if (format === void 0) { format = null; }
  15430. if (forcedExtension === void 0) { forcedExtension = null; }
  15431. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15432. var fromData = url.substr(0, 5) === "data:";
  15433. var fromBlob = url.substr(0, 5) === "blob:";
  15434. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15435. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15436. // establish the file extension, if possible
  15437. var lastDot = url.lastIndexOf('.');
  15438. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15439. var loader = null;
  15440. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15441. var availableLoader = _a[_i];
  15442. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15443. loader = availableLoader;
  15444. break;
  15445. }
  15446. }
  15447. if (loader) {
  15448. url = loader.transformUrl(url, this._textureFormatInUse);
  15449. }
  15450. if (scene) {
  15451. scene._addPendingData(texture);
  15452. }
  15453. texture.url = url;
  15454. texture.generateMipMaps = !noMipmap;
  15455. texture.samplingMode = samplingMode;
  15456. texture.invertY = invertY;
  15457. if (!this._doNotHandleContextLost) {
  15458. // Keep a link to the buffer only if we plan to handle context lost
  15459. texture._buffer = buffer;
  15460. }
  15461. var onLoadObserver = null;
  15462. if (onLoad && !fallback) {
  15463. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15464. }
  15465. if (!fallback) {
  15466. this._internalTexturesCache.push(texture);
  15467. }
  15468. var onInternalError = function (message, exception) {
  15469. if (scene) {
  15470. scene._removePendingData(texture);
  15471. }
  15472. var customFallback = false;
  15473. if (loader) {
  15474. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15475. if (fallbackUrl) {
  15476. // Add Back
  15477. customFallback = true;
  15478. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15479. }
  15480. }
  15481. if (!customFallback) {
  15482. if (onLoadObserver) {
  15483. texture.onLoadedObservable.remove(onLoadObserver);
  15484. }
  15485. if (BABYLON.Tools.UseFallbackTexture) {
  15486. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15487. }
  15488. }
  15489. if (onError) {
  15490. onError(message || "Unknown error", exception);
  15491. }
  15492. };
  15493. // processing for non-image formats
  15494. if (loader) {
  15495. var callback = function (data) {
  15496. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15497. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15498. done();
  15499. return false;
  15500. }, samplingMode);
  15501. });
  15502. };
  15503. if (!buffer) {
  15504. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15505. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15506. });
  15507. }
  15508. else {
  15509. callback(buffer);
  15510. }
  15511. }
  15512. else {
  15513. var onload = function (img) {
  15514. if (fromBlob && !_this._doNotHandleContextLost) {
  15515. // We need to store the image if we need to rebuild the texture
  15516. // in case of a webgl context lost
  15517. texture._buffer = img;
  15518. }
  15519. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15520. var gl = _this._gl;
  15521. var isPot = (img.width === potWidth && img.height === potHeight);
  15522. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15523. if (isPot) {
  15524. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15525. return false;
  15526. }
  15527. var maxTextureSize = _this._caps.maxTextureSize;
  15528. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15529. _this._prepareWorkingCanvas();
  15530. if (!_this._workingCanvas || !_this._workingContext) {
  15531. return false;
  15532. }
  15533. _this._workingCanvas.width = potWidth;
  15534. _this._workingCanvas.height = potHeight;
  15535. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15536. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15537. texture.width = potWidth;
  15538. texture.height = potHeight;
  15539. return false;
  15540. }
  15541. else {
  15542. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15543. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15544. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15545. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15550. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15551. _this._releaseTexture(source_1);
  15552. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15553. continuationCallback();
  15554. });
  15555. }
  15556. return true;
  15557. }, samplingMode);
  15558. };
  15559. if (!fromData || isBase64) {
  15560. if (buffer instanceof HTMLImageElement) {
  15561. onload(buffer);
  15562. }
  15563. else {
  15564. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15565. }
  15566. }
  15567. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15568. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15569. }
  15570. else {
  15571. onload(buffer);
  15572. }
  15573. }
  15574. return texture;
  15575. };
  15576. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15577. var _this = this;
  15578. var rtt = this.createRenderTargetTexture({
  15579. width: destination.width,
  15580. height: destination.height,
  15581. }, {
  15582. generateMipMaps: false,
  15583. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15584. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15585. generateDepthBuffer: false,
  15586. generateStencilBuffer: false
  15587. });
  15588. if (!this._rescalePostProcess) {
  15589. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15590. }
  15591. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15592. _this._rescalePostProcess.onApply = function (effect) {
  15593. effect._bindTexture("textureSampler", source);
  15594. };
  15595. var hostingScene = scene;
  15596. if (!hostingScene) {
  15597. hostingScene = _this.scenes[_this.scenes.length - 1];
  15598. }
  15599. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15600. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15601. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15602. _this.unBindFramebuffer(rtt);
  15603. _this._releaseTexture(rtt);
  15604. if (onComplete) {
  15605. onComplete();
  15606. }
  15607. });
  15608. };
  15609. /**
  15610. * Update a raw texture
  15611. * @param texture defines the texture to update
  15612. * @param data defines the data to store in the texture
  15613. * @param format defines the format of the data
  15614. * @param invertY defines if data must be stored with Y axis inverted
  15615. * @param compression defines the compression used (null by default)
  15616. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15617. */
  15618. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15619. if (compression === void 0) { compression = null; }
  15620. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15621. if (!texture) {
  15622. return;
  15623. }
  15624. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15625. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15626. // babylon's internalFormat but gl's texImage2D format
  15627. var internalFormat = this._getInternalFormat(format);
  15628. var textureType = this._getWebGLTextureType(type);
  15629. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15630. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15631. if (!this._doNotHandleContextLost) {
  15632. texture._bufferView = data;
  15633. texture.format = format;
  15634. texture.type = type;
  15635. texture.invertY = invertY;
  15636. texture._compression = compression;
  15637. }
  15638. if (texture.width % 4 !== 0) {
  15639. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15640. }
  15641. if (compression && data) {
  15642. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15643. }
  15644. else {
  15645. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15646. }
  15647. if (texture.generateMipMaps) {
  15648. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15649. }
  15650. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15651. // this.resetTextureCache();
  15652. texture.isReady = true;
  15653. };
  15654. /**
  15655. * Creates a raw texture
  15656. * @param data defines the data to store in the texture
  15657. * @param width defines the width of the texture
  15658. * @param height defines the height of the texture
  15659. * @param format defines the format of the data
  15660. * @param generateMipMaps defines if the engine should generate the mip levels
  15661. * @param invertY defines if data must be stored with Y axis inverted
  15662. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15663. * @param compression defines the compression used (null by default)
  15664. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15665. * @returns the raw texture inside an InternalTexture
  15666. */
  15667. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15668. if (compression === void 0) { compression = null; }
  15669. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15670. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15671. texture.baseWidth = width;
  15672. texture.baseHeight = height;
  15673. texture.width = width;
  15674. texture.height = height;
  15675. texture.format = format;
  15676. texture.generateMipMaps = generateMipMaps;
  15677. texture.samplingMode = samplingMode;
  15678. texture.invertY = invertY;
  15679. texture._compression = compression;
  15680. texture.type = type;
  15681. if (!this._doNotHandleContextLost) {
  15682. texture._bufferView = data;
  15683. }
  15684. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15685. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15686. // Filters
  15687. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15689. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15690. if (generateMipMaps) {
  15691. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15692. }
  15693. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15694. this._internalTexturesCache.push(texture);
  15695. return texture;
  15696. };
  15697. /** @hidden */
  15698. Engine.prototype._unpackFlipY = function (value) {
  15699. if (this._unpackFlipYCached !== value) {
  15700. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15701. if (this.enableUnpackFlipYCached) {
  15702. this._unpackFlipYCached = value;
  15703. }
  15704. }
  15705. };
  15706. /** @hidden */
  15707. Engine.prototype._getUnpackAlignement = function () {
  15708. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15709. };
  15710. /**
  15711. * Creates a dynamic texture
  15712. * @param width defines the width of the texture
  15713. * @param height defines the height of the texture
  15714. * @param generateMipMaps defines if the engine should generate the mip levels
  15715. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15716. * @returns the dynamic texture inside an InternalTexture
  15717. */
  15718. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15719. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15720. texture.baseWidth = width;
  15721. texture.baseHeight = height;
  15722. if (generateMipMaps) {
  15723. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15724. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15725. }
  15726. // this.resetTextureCache();
  15727. texture.width = width;
  15728. texture.height = height;
  15729. texture.isReady = false;
  15730. texture.generateMipMaps = generateMipMaps;
  15731. texture.samplingMode = samplingMode;
  15732. this.updateTextureSamplingMode(samplingMode, texture);
  15733. this._internalTexturesCache.push(texture);
  15734. return texture;
  15735. };
  15736. /**
  15737. * Update the sampling mode of a given texture
  15738. * @param samplingMode defines the required sampling mode
  15739. * @param texture defines the texture to update
  15740. */
  15741. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15742. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15743. if (texture.isCube) {
  15744. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15745. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15746. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15747. }
  15748. else if (texture.is3D) {
  15749. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15750. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15751. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15752. }
  15753. else {
  15754. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15755. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15756. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15757. }
  15758. texture.samplingMode = samplingMode;
  15759. };
  15760. /**
  15761. * Update the content of a dynamic texture
  15762. * @param texture defines the texture to update
  15763. * @param canvas defines the canvas containing the source
  15764. * @param invertY defines if data must be stored with Y axis inverted
  15765. * @param premulAlpha defines if alpha is stored as premultiplied
  15766. * @param format defines the format of the data
  15767. */
  15768. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15769. if (premulAlpha === void 0) { premulAlpha = false; }
  15770. if (!texture) {
  15771. return;
  15772. }
  15773. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15774. this._unpackFlipY(invertY);
  15775. if (premulAlpha) {
  15776. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15777. }
  15778. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15779. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15780. if (texture.generateMipMaps) {
  15781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15782. }
  15783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15784. if (premulAlpha) {
  15785. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15786. }
  15787. texture.isReady = true;
  15788. };
  15789. /**
  15790. * Update a video texture
  15791. * @param texture defines the texture to update
  15792. * @param video defines the video element to use
  15793. * @param invertY defines if data must be stored with Y axis inverted
  15794. */
  15795. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15796. if (!texture || texture._isDisabled) {
  15797. return;
  15798. }
  15799. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15800. this._unpackFlipY(!invertY); // Video are upside down by default
  15801. try {
  15802. // Testing video texture support
  15803. if (this._videoTextureSupported === undefined) {
  15804. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15805. if (this._gl.getError() !== 0) {
  15806. this._videoTextureSupported = false;
  15807. }
  15808. else {
  15809. this._videoTextureSupported = true;
  15810. }
  15811. }
  15812. // Copy video through the current working canvas if video texture is not supported
  15813. if (!this._videoTextureSupported) {
  15814. if (!texture._workingCanvas) {
  15815. texture._workingCanvas = document.createElement("canvas");
  15816. var context = texture._workingCanvas.getContext("2d");
  15817. if (!context) {
  15818. throw new Error("Unable to get 2d context");
  15819. }
  15820. texture._workingContext = context;
  15821. texture._workingCanvas.width = texture.width;
  15822. texture._workingCanvas.height = texture.height;
  15823. }
  15824. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15825. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15826. }
  15827. else {
  15828. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15829. }
  15830. if (texture.generateMipMaps) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15832. }
  15833. if (!wasPreviouslyBound) {
  15834. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15835. }
  15836. // this.resetTextureCache();
  15837. texture.isReady = true;
  15838. }
  15839. catch (ex) {
  15840. // Something unexpected
  15841. // Let's disable the texture
  15842. texture._isDisabled = true;
  15843. }
  15844. };
  15845. /**
  15846. * Updates a depth texture Comparison Mode and Function.
  15847. * If the comparison Function is equal to 0, the mode will be set to none.
  15848. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15849. * @param texture The texture to set the comparison function for
  15850. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15851. */
  15852. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15853. if (this.webGLVersion === 1) {
  15854. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15855. return;
  15856. }
  15857. var gl = this._gl;
  15858. if (texture.isCube) {
  15859. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15860. if (comparisonFunction === 0) {
  15861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15863. }
  15864. else {
  15865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15867. }
  15868. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15869. }
  15870. else {
  15871. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15872. if (comparisonFunction === 0) {
  15873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15875. }
  15876. else {
  15877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15879. }
  15880. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15881. }
  15882. texture._comparisonFunction = comparisonFunction;
  15883. };
  15884. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15885. var width = size.width || size;
  15886. var height = size.height || size;
  15887. internalTexture.baseWidth = width;
  15888. internalTexture.baseHeight = height;
  15889. internalTexture.width = width;
  15890. internalTexture.height = height;
  15891. internalTexture.isReady = true;
  15892. internalTexture.samples = 1;
  15893. internalTexture.generateMipMaps = false;
  15894. internalTexture._generateDepthBuffer = true;
  15895. internalTexture._generateStencilBuffer = generateStencil;
  15896. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15897. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15898. internalTexture._comparisonFunction = comparisonFunction;
  15899. var gl = this._gl;
  15900. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15901. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15902. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15903. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15904. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15905. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15906. if (comparisonFunction === 0) {
  15907. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15908. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15909. }
  15910. else {
  15911. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15912. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15913. }
  15914. };
  15915. /**
  15916. * Creates a depth stencil texture.
  15917. * This is only available in WebGL 2 or with the depth texture extension available.
  15918. * @param size The size of face edge in the texture.
  15919. * @param options The options defining the texture.
  15920. * @returns The texture
  15921. */
  15922. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15923. if (options.isCube) {
  15924. var width = size.width || size;
  15925. return this._createDepthStencilCubeTexture(width, options);
  15926. }
  15927. else {
  15928. return this._createDepthStencilTexture(size, options);
  15929. }
  15930. };
  15931. /**
  15932. * Creates a depth stencil texture.
  15933. * This is only available in WebGL 2 or with the depth texture extension available.
  15934. * @param size The size of face edge in the texture.
  15935. * @param options The options defining the texture.
  15936. * @returns The texture
  15937. */
  15938. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15939. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15940. if (!this._caps.depthTextureExtension) {
  15941. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15942. return internalTexture;
  15943. }
  15944. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15945. var gl = this._gl;
  15946. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15947. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15948. if (this.webGLVersion > 1) {
  15949. if (internalOptions.generateStencil) {
  15950. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15951. }
  15952. else {
  15953. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15954. }
  15955. }
  15956. else {
  15957. if (internalOptions.generateStencil) {
  15958. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15959. }
  15960. else {
  15961. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15962. }
  15963. }
  15964. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15965. return internalTexture;
  15966. };
  15967. /**
  15968. * Creates a depth stencil cube texture.
  15969. * This is only available in WebGL 2.
  15970. * @param size The size of face edge in the cube texture.
  15971. * @param options The options defining the cube texture.
  15972. * @returns The cube texture
  15973. */
  15974. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15975. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15976. internalTexture.isCube = true;
  15977. if (this.webGLVersion === 1) {
  15978. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15979. return internalTexture;
  15980. }
  15981. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15982. var gl = this._gl;
  15983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15984. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15985. // Create the depth/stencil buffer
  15986. for (var face = 0; face < 6; face++) {
  15987. if (internalOptions.generateStencil) {
  15988. 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);
  15989. }
  15990. else {
  15991. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15992. }
  15993. }
  15994. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15995. return internalTexture;
  15996. };
  15997. /**
  15998. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15999. * @param renderTarget The render target to set the frame buffer for
  16000. */
  16001. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16002. // Create the framebuffer
  16003. var internalTexture = renderTarget.getInternalTexture();
  16004. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16005. return;
  16006. }
  16007. var gl = this._gl;
  16008. var depthStencilTexture = renderTarget.depthStencilTexture;
  16009. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16010. if (depthStencilTexture.isCube) {
  16011. if (depthStencilTexture._generateStencilBuffer) {
  16012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16013. }
  16014. else {
  16015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16016. }
  16017. }
  16018. else {
  16019. if (depthStencilTexture._generateStencilBuffer) {
  16020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16021. }
  16022. else {
  16023. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16024. }
  16025. }
  16026. this.bindUnboundFramebuffer(null);
  16027. };
  16028. /**
  16029. * Creates a new render target texture
  16030. * @param size defines the size of the texture
  16031. * @param options defines the options used to create the texture
  16032. * @returns a new render target texture stored in an InternalTexture
  16033. */
  16034. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16035. var fullOptions = new RenderTargetCreationOptions();
  16036. if (options !== undefined && typeof options === "object") {
  16037. fullOptions.generateMipMaps = options.generateMipMaps;
  16038. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16039. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16040. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16041. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16042. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16043. }
  16044. else {
  16045. fullOptions.generateMipMaps = options;
  16046. fullOptions.generateDepthBuffer = true;
  16047. fullOptions.generateStencilBuffer = false;
  16048. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16049. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16050. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16051. }
  16052. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16053. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16054. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16055. }
  16056. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16057. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16058. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16059. }
  16060. var gl = this._gl;
  16061. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16062. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16063. var width = size.width || size;
  16064. var height = size.height || size;
  16065. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16066. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16067. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16068. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16069. }
  16070. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16073. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16074. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16075. // Create the framebuffer
  16076. var currentFrameBuffer = this._currentFramebuffer;
  16077. var framebuffer = gl.createFramebuffer();
  16078. this.bindUnboundFramebuffer(framebuffer);
  16079. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16080. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16081. if (fullOptions.generateMipMaps) {
  16082. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16083. }
  16084. // Unbind
  16085. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16086. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16087. this.bindUnboundFramebuffer(currentFrameBuffer);
  16088. texture._framebuffer = framebuffer;
  16089. texture.baseWidth = width;
  16090. texture.baseHeight = height;
  16091. texture.width = width;
  16092. texture.height = height;
  16093. texture.isReady = true;
  16094. texture.samples = 1;
  16095. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16096. texture.samplingMode = fullOptions.samplingMode;
  16097. texture.type = fullOptions.type;
  16098. texture.format = fullOptions.format;
  16099. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16100. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16101. // this.resetTextureCache();
  16102. this._internalTexturesCache.push(texture);
  16103. return texture;
  16104. };
  16105. /**
  16106. * Create a multi render target texture
  16107. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16108. * @param size defines the size of the texture
  16109. * @param options defines the creation options
  16110. * @returns the cube texture as an InternalTexture
  16111. */
  16112. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16113. var generateMipMaps = false;
  16114. var generateDepthBuffer = true;
  16115. var generateStencilBuffer = false;
  16116. var generateDepthTexture = false;
  16117. var textureCount = 1;
  16118. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16119. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16120. var types = new Array();
  16121. var samplingModes = new Array();
  16122. if (options !== undefined) {
  16123. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16124. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16125. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16126. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16127. textureCount = options.textureCount || 1;
  16128. if (options.types) {
  16129. types = options.types;
  16130. }
  16131. if (options.samplingModes) {
  16132. samplingModes = options.samplingModes;
  16133. }
  16134. }
  16135. var gl = this._gl;
  16136. // Create the framebuffer
  16137. var framebuffer = gl.createFramebuffer();
  16138. this.bindUnboundFramebuffer(framebuffer);
  16139. var width = size.width || size;
  16140. var height = size.height || size;
  16141. var textures = [];
  16142. var attachments = [];
  16143. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16144. for (var i = 0; i < textureCount; i++) {
  16145. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16146. var type = types[i] || defaultType;
  16147. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16148. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16149. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16150. }
  16151. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16152. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16153. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16154. }
  16155. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16156. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16157. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16158. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16159. }
  16160. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16161. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16162. textures.push(texture);
  16163. attachments.push(attachment);
  16164. gl.activeTexture(gl["TEXTURE" + i]);
  16165. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16170. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16171. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16172. if (generateMipMaps) {
  16173. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16174. }
  16175. // Unbind
  16176. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16177. texture._framebuffer = framebuffer;
  16178. texture._depthStencilBuffer = depthStencilBuffer;
  16179. texture.baseWidth = width;
  16180. texture.baseHeight = height;
  16181. texture.width = width;
  16182. texture.height = height;
  16183. texture.isReady = true;
  16184. texture.samples = 1;
  16185. texture.generateMipMaps = generateMipMaps;
  16186. texture.samplingMode = samplingMode;
  16187. texture.type = type;
  16188. texture._generateDepthBuffer = generateDepthBuffer;
  16189. texture._generateStencilBuffer = generateStencilBuffer;
  16190. texture._attachments = attachments;
  16191. this._internalTexturesCache.push(texture);
  16192. }
  16193. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16194. // Depth texture
  16195. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16196. gl.activeTexture(gl.TEXTURE0);
  16197. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16202. 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);
  16203. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16204. depthTexture._framebuffer = framebuffer;
  16205. depthTexture.baseWidth = width;
  16206. depthTexture.baseHeight = height;
  16207. depthTexture.width = width;
  16208. depthTexture.height = height;
  16209. depthTexture.isReady = true;
  16210. depthTexture.samples = 1;
  16211. depthTexture.generateMipMaps = generateMipMaps;
  16212. depthTexture.samplingMode = gl.NEAREST;
  16213. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16214. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16215. textures.push(depthTexture);
  16216. this._internalTexturesCache.push(depthTexture);
  16217. }
  16218. gl.drawBuffers(attachments);
  16219. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16220. this.bindUnboundFramebuffer(null);
  16221. this.resetTextureCache();
  16222. return textures;
  16223. };
  16224. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16225. if (samples === void 0) { samples = 1; }
  16226. var depthStencilBuffer = null;
  16227. var gl = this._gl;
  16228. // Create the depth/stencil buffer
  16229. if (generateStencilBuffer) {
  16230. depthStencilBuffer = gl.createRenderbuffer();
  16231. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16232. if (samples > 1) {
  16233. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16234. }
  16235. else {
  16236. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16237. }
  16238. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16239. }
  16240. else if (generateDepthBuffer) {
  16241. depthStencilBuffer = gl.createRenderbuffer();
  16242. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16243. if (samples > 1) {
  16244. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16245. }
  16246. else {
  16247. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16248. }
  16249. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16250. }
  16251. return depthStencilBuffer;
  16252. };
  16253. /**
  16254. * Updates the sample count of a render target texture
  16255. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16256. * @param texture defines the texture to update
  16257. * @param samples defines the sample count to set
  16258. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16259. */
  16260. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16261. if (this.webGLVersion < 2 || !texture) {
  16262. return 1;
  16263. }
  16264. if (texture.samples === samples) {
  16265. return samples;
  16266. }
  16267. var gl = this._gl;
  16268. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16269. // Dispose previous render buffers
  16270. if (texture._depthStencilBuffer) {
  16271. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16272. texture._depthStencilBuffer = null;
  16273. }
  16274. if (texture._MSAAFramebuffer) {
  16275. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16276. texture._MSAAFramebuffer = null;
  16277. }
  16278. if (texture._MSAARenderBuffer) {
  16279. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16280. texture._MSAARenderBuffer = null;
  16281. }
  16282. if (samples > 1) {
  16283. var framebuffer = gl.createFramebuffer();
  16284. if (!framebuffer) {
  16285. throw new Error("Unable to create multi sampled framebuffer");
  16286. }
  16287. texture._MSAAFramebuffer = framebuffer;
  16288. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16289. var colorRenderbuffer = gl.createRenderbuffer();
  16290. if (!colorRenderbuffer) {
  16291. throw new Error("Unable to create multi sampled framebuffer");
  16292. }
  16293. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16294. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16295. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16296. texture._MSAARenderBuffer = colorRenderbuffer;
  16297. }
  16298. else {
  16299. this.bindUnboundFramebuffer(texture._framebuffer);
  16300. }
  16301. texture.samples = samples;
  16302. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16303. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16304. this.bindUnboundFramebuffer(null);
  16305. return samples;
  16306. };
  16307. /**
  16308. * Update the sample count for a given multiple render target texture
  16309. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16310. * @param textures defines the textures to update
  16311. * @param samples defines the sample count to set
  16312. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16313. */
  16314. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16315. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16316. return 1;
  16317. }
  16318. if (textures[0].samples === samples) {
  16319. return samples;
  16320. }
  16321. var gl = this._gl;
  16322. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16323. // Dispose previous render buffers
  16324. if (textures[0]._depthStencilBuffer) {
  16325. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16326. textures[0]._depthStencilBuffer = null;
  16327. }
  16328. if (textures[0]._MSAAFramebuffer) {
  16329. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16330. textures[0]._MSAAFramebuffer = null;
  16331. }
  16332. for (var i = 0; i < textures.length; i++) {
  16333. if (textures[i]._MSAARenderBuffer) {
  16334. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16335. textures[i]._MSAARenderBuffer = null;
  16336. }
  16337. }
  16338. if (samples > 1) {
  16339. var framebuffer = gl.createFramebuffer();
  16340. if (!framebuffer) {
  16341. throw new Error("Unable to create multi sampled framebuffer");
  16342. }
  16343. this.bindUnboundFramebuffer(framebuffer);
  16344. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16345. var attachments = [];
  16346. for (var i = 0; i < textures.length; i++) {
  16347. var texture = textures[i];
  16348. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16349. var colorRenderbuffer = gl.createRenderbuffer();
  16350. if (!colorRenderbuffer) {
  16351. throw new Error("Unable to create multi sampled framebuffer");
  16352. }
  16353. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16354. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16355. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16356. texture._MSAAFramebuffer = framebuffer;
  16357. texture._MSAARenderBuffer = colorRenderbuffer;
  16358. texture.samples = samples;
  16359. texture._depthStencilBuffer = depthStencilBuffer;
  16360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16361. attachments.push(attachment);
  16362. }
  16363. gl.drawBuffers(attachments);
  16364. }
  16365. else {
  16366. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16367. }
  16368. this.bindUnboundFramebuffer(null);
  16369. return samples;
  16370. };
  16371. /** @hidden */
  16372. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16373. if (faceIndex === void 0) { faceIndex = 0; }
  16374. if (lod === void 0) { lod = 0; }
  16375. var gl = this._gl;
  16376. var target = gl.TEXTURE_2D;
  16377. if (texture.isCube) {
  16378. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16379. }
  16380. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16381. };
  16382. /** @hidden */
  16383. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16384. if (faceIndex === void 0) { faceIndex = 0; }
  16385. if (lod === void 0) { lod = 0; }
  16386. var gl = this._gl;
  16387. var textureType = this._getWebGLTextureType(texture.type);
  16388. var format = this._getInternalFormat(texture.format);
  16389. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16390. this._unpackFlipY(texture.invertY);
  16391. var target = gl.TEXTURE_2D;
  16392. if (texture.isCube) {
  16393. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16394. }
  16395. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16396. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16397. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16398. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16399. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16400. };
  16401. /** @hidden */
  16402. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16403. if (faceIndex === void 0) { faceIndex = 0; }
  16404. if (lod === void 0) { lod = 0; }
  16405. var gl = this._gl;
  16406. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16407. this._bindTextureDirectly(bindTarget, texture, true);
  16408. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16409. this._bindTextureDirectly(bindTarget, null, true);
  16410. };
  16411. /** @hidden */
  16412. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16413. if (faceIndex === void 0) { faceIndex = 0; }
  16414. if (lod === void 0) { lod = 0; }
  16415. var gl = this._gl;
  16416. var textureType = this._getWebGLTextureType(texture.type);
  16417. var format = this._getInternalFormat(texture.format);
  16418. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16419. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16420. this._bindTextureDirectly(bindTarget, texture, true);
  16421. this._unpackFlipY(texture.invertY);
  16422. var target = gl.TEXTURE_2D;
  16423. if (texture.isCube) {
  16424. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16425. }
  16426. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16427. this._bindTextureDirectly(bindTarget, null, true);
  16428. };
  16429. /**
  16430. * Creates a new render target cube texture
  16431. * @param size defines the size of the texture
  16432. * @param options defines the options used to create the texture
  16433. * @returns a new render target cube texture stored in an InternalTexture
  16434. */
  16435. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16436. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16437. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16438. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16439. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16440. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16441. }
  16442. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16443. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16444. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16445. }
  16446. var gl = this._gl;
  16447. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16448. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16449. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16450. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16451. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16452. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16453. }
  16454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16458. for (var face = 0; face < 6; face++) {
  16459. 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);
  16460. }
  16461. // Create the framebuffer
  16462. var framebuffer = gl.createFramebuffer();
  16463. this.bindUnboundFramebuffer(framebuffer);
  16464. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16465. // MipMaps
  16466. if (fullOptions.generateMipMaps) {
  16467. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16468. }
  16469. // Unbind
  16470. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16471. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16472. this.bindUnboundFramebuffer(null);
  16473. texture._framebuffer = framebuffer;
  16474. texture.width = size;
  16475. texture.height = size;
  16476. texture.isReady = true;
  16477. texture.isCube = true;
  16478. texture.samples = 1;
  16479. texture.generateMipMaps = fullOptions.generateMipMaps;
  16480. texture.samplingMode = fullOptions.samplingMode;
  16481. texture.type = fullOptions.type;
  16482. texture.format = fullOptions.format;
  16483. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16484. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16485. this._internalTexturesCache.push(texture);
  16486. return texture;
  16487. };
  16488. /**
  16489. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16490. * @param rootUrl defines the url where the file to load is located
  16491. * @param scene defines the current scene
  16492. * @param lodScale defines scale to apply to the mip map selection
  16493. * @param lodOffset defines offset to apply to the mip map selection
  16494. * @param onLoad defines an optional callback raised when the texture is loaded
  16495. * @param onError defines an optional callback raised if there is an issue to load the texture
  16496. * @param format defines the format of the data
  16497. * @param forcedExtension defines the extension to use to pick the right loader
  16498. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16499. * @returns the cube texture as an InternalTexture
  16500. */
  16501. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16502. var _this = this;
  16503. if (onLoad === void 0) { onLoad = null; }
  16504. if (onError === void 0) { onError = null; }
  16505. if (forcedExtension === void 0) { forcedExtension = null; }
  16506. if (createPolynomials === void 0) { createPolynomials = true; }
  16507. var callback = function (loadData) {
  16508. if (!loadData) {
  16509. if (onLoad) {
  16510. onLoad(null);
  16511. }
  16512. return;
  16513. }
  16514. var texture = loadData.texture;
  16515. if (!createPolynomials) {
  16516. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16517. }
  16518. else if (loadData.info.sphericalPolynomial) {
  16519. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16520. }
  16521. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16522. if (_this._caps.textureLOD) {
  16523. // Do not add extra process if texture lod is supported.
  16524. if (onLoad) {
  16525. onLoad(texture);
  16526. }
  16527. return;
  16528. }
  16529. var mipSlices = 3;
  16530. var gl = _this._gl;
  16531. var width = loadData.width;
  16532. if (!width) {
  16533. return;
  16534. }
  16535. var textures = [];
  16536. for (var i = 0; i < mipSlices; i++) {
  16537. //compute LOD from even spacing in smoothness (matching shader calculation)
  16538. var smoothness = i / (mipSlices - 1);
  16539. var roughness = 1 - smoothness;
  16540. var minLODIndex = lodOffset; // roughness = 0
  16541. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16542. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16543. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16544. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16545. glTextureFromLod.type = texture.type;
  16546. glTextureFromLod.format = texture.format;
  16547. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16548. glTextureFromLod.height = glTextureFromLod.width;
  16549. glTextureFromLod.isCube = true;
  16550. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16555. if (loadData.isDDS) {
  16556. var info = loadData.info;
  16557. var data = loadData.data;
  16558. _this._unpackFlipY(info.isCompressed);
  16559. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16560. }
  16561. else {
  16562. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16563. }
  16564. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16565. // Wrap in a base texture for easy binding.
  16566. var lodTexture = new BABYLON.BaseTexture(scene);
  16567. lodTexture.isCube = true;
  16568. lodTexture._texture = glTextureFromLod;
  16569. glTextureFromLod.isReady = true;
  16570. textures.push(lodTexture);
  16571. }
  16572. texture._lodTextureHigh = textures[2];
  16573. texture._lodTextureMid = textures[1];
  16574. texture._lodTextureLow = textures[0];
  16575. if (onLoad) {
  16576. onLoad(texture);
  16577. }
  16578. };
  16579. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16580. };
  16581. /**
  16582. * Creates a cube texture
  16583. * @param rootUrl defines the url where the files to load is located
  16584. * @param scene defines the current scene
  16585. * @param files defines the list of files to load (1 per face)
  16586. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16587. * @param onLoad defines an optional callback raised when the texture is loaded
  16588. * @param onError defines an optional callback raised if there is an issue to load the texture
  16589. * @param format defines the format of the data
  16590. * @param forcedExtension defines the extension to use to pick the right loader
  16591. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16592. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16593. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16594. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16595. * @returns the cube texture as an InternalTexture
  16596. */
  16597. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16598. var _this = this;
  16599. if (onLoad === void 0) { onLoad = null; }
  16600. if (onError === void 0) { onError = null; }
  16601. if (forcedExtension === void 0) { forcedExtension = null; }
  16602. if (createPolynomials === void 0) { createPolynomials = false; }
  16603. if (lodScale === void 0) { lodScale = 0; }
  16604. if (lodOffset === void 0) { lodOffset = 0; }
  16605. if (fallback === void 0) { fallback = null; }
  16606. var gl = this._gl;
  16607. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16608. texture.isCube = true;
  16609. texture.url = rootUrl;
  16610. texture.generateMipMaps = !noMipmap;
  16611. texture._lodGenerationScale = lodScale;
  16612. texture._lodGenerationOffset = lodOffset;
  16613. if (!this._doNotHandleContextLost) {
  16614. texture._extension = forcedExtension;
  16615. texture._files = files;
  16616. }
  16617. var lastDot = rootUrl.lastIndexOf('.');
  16618. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16619. var loader = null;
  16620. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16621. var availableLoader = _a[_i];
  16622. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16623. loader = availableLoader;
  16624. break;
  16625. }
  16626. }
  16627. var onInternalError = function (request, exception) {
  16628. if (loader) {
  16629. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16630. if (fallbackUrl) {
  16631. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16632. }
  16633. }
  16634. if (onError && request) {
  16635. onError(request.status + " " + request.statusText, exception);
  16636. }
  16637. };
  16638. if (loader) {
  16639. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16640. var onloaddata = function (data) {
  16641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16642. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16643. };
  16644. if (files && files.length === 6) {
  16645. if (loader.supportCascades) {
  16646. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16647. }
  16648. else if (onError) {
  16649. onError("Textures type does not support cascades.");
  16650. }
  16651. }
  16652. else {
  16653. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16654. }
  16655. }
  16656. else {
  16657. if (!files) {
  16658. throw new Error("Cannot load cubemap because files were not defined");
  16659. }
  16660. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16661. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16662. var height = width;
  16663. _this._prepareWorkingCanvas();
  16664. if (!_this._workingCanvas || !_this._workingContext) {
  16665. return;
  16666. }
  16667. _this._workingCanvas.width = width;
  16668. _this._workingCanvas.height = height;
  16669. var faces = [
  16670. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16671. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16672. ];
  16673. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16674. _this._unpackFlipY(false);
  16675. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16676. for (var index = 0; index < faces.length; index++) {
  16677. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16678. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16679. }
  16680. if (!noMipmap) {
  16681. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16682. }
  16683. _this._setCubeMapTextureParams(!noMipmap);
  16684. texture.width = width;
  16685. texture.height = height;
  16686. texture.isReady = true;
  16687. if (format) {
  16688. texture.format = format;
  16689. }
  16690. texture.onLoadedObservable.notifyObservers(texture);
  16691. texture.onLoadedObservable.clear();
  16692. if (onLoad) {
  16693. onLoad();
  16694. }
  16695. }, files, onError);
  16696. }
  16697. this._internalTexturesCache.push(texture);
  16698. return texture;
  16699. };
  16700. /**
  16701. * @hidden
  16702. */
  16703. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16704. var gl = this._gl;
  16705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16710. // this.resetTextureCache();
  16711. };
  16712. /**
  16713. * Update a raw cube texture
  16714. * @param texture defines the texture to udpdate
  16715. * @param data defines the data to store
  16716. * @param format defines the data format
  16717. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16718. * @param invertY defines if data must be stored with Y axis inverted
  16719. * @param compression defines the compression used (null by default)
  16720. * @param level defines which level of the texture to update
  16721. */
  16722. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16723. if (compression === void 0) { compression = null; }
  16724. if (level === void 0) { level = 0; }
  16725. texture._bufferViewArray = data;
  16726. texture.format = format;
  16727. texture.type = type;
  16728. texture.invertY = invertY;
  16729. texture._compression = compression;
  16730. var gl = this._gl;
  16731. var textureType = this._getWebGLTextureType(type);
  16732. var internalFormat = this._getInternalFormat(format);
  16733. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16734. var needConversion = false;
  16735. if (internalFormat === gl.RGB) {
  16736. internalFormat = gl.RGBA;
  16737. needConversion = true;
  16738. }
  16739. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16740. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16741. if (texture.width % 4 !== 0) {
  16742. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16743. }
  16744. // Data are known to be in +X +Y +Z -X -Y -Z
  16745. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16746. var faceData = data[faceIndex];
  16747. if (compression) {
  16748. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16749. }
  16750. else {
  16751. if (needConversion) {
  16752. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16753. }
  16754. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16755. }
  16756. }
  16757. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16758. if (isPot && texture.generateMipMaps && level === 0) {
  16759. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16760. }
  16761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16762. // this.resetTextureCache();
  16763. texture.isReady = true;
  16764. };
  16765. /**
  16766. * Creates a new raw cube texture
  16767. * @param data defines the array of data to use to create each face
  16768. * @param size defines the size of the textures
  16769. * @param format defines the format of the data
  16770. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16771. * @param generateMipMaps defines if the engine should generate the mip levels
  16772. * @param invertY defines if data must be stored with Y axis inverted
  16773. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16774. * @param compression defines the compression used (null by default)
  16775. * @returns the cube texture as an InternalTexture
  16776. */
  16777. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16778. if (compression === void 0) { compression = null; }
  16779. var gl = this._gl;
  16780. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16781. texture.isCube = true;
  16782. texture.format = format;
  16783. texture.type = type;
  16784. if (!this._doNotHandleContextLost) {
  16785. texture._bufferViewArray = data;
  16786. }
  16787. var textureType = this._getWebGLTextureType(type);
  16788. var internalFormat = this._getInternalFormat(format);
  16789. if (internalFormat === gl.RGB) {
  16790. internalFormat = gl.RGBA;
  16791. }
  16792. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16793. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16794. generateMipMaps = false;
  16795. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16796. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16797. }
  16798. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16799. generateMipMaps = false;
  16800. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16801. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16802. }
  16803. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16804. generateMipMaps = false;
  16805. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16806. }
  16807. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16808. generateMipMaps = false;
  16809. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16810. }
  16811. var width = size;
  16812. var height = width;
  16813. texture.width = width;
  16814. texture.height = height;
  16815. // Double check on POT to generate Mips.
  16816. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16817. if (!isPot) {
  16818. generateMipMaps = false;
  16819. }
  16820. // Upload data if needed. The texture won't be ready until then.
  16821. if (data) {
  16822. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16823. }
  16824. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16825. // Filters
  16826. if (data && generateMipMaps) {
  16827. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16828. }
  16829. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16834. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16835. texture.generateMipMaps = generateMipMaps;
  16836. return texture;
  16837. };
  16838. /**
  16839. * Creates a new raw cube texture from a specified url
  16840. * @param url defines the url where the data is located
  16841. * @param scene defines the current scene
  16842. * @param size defines the size of the textures
  16843. * @param format defines the format of the data
  16844. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16845. * @param noMipmap defines if the engine should avoid generating the mip levels
  16846. * @param callback defines a callback used to extract texture data from loaded data
  16847. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16848. * @param onLoad defines a callback called when texture is loaded
  16849. * @param onError defines a callback called if there is an error
  16850. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16851. * @param invertY defines if data must be stored with Y axis inverted
  16852. * @returns the cube texture as an InternalTexture
  16853. */
  16854. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16855. var _this = this;
  16856. if (onLoad === void 0) { onLoad = null; }
  16857. if (onError === void 0) { onError = null; }
  16858. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16859. if (invertY === void 0) { invertY = false; }
  16860. var gl = this._gl;
  16861. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16862. scene._addPendingData(texture);
  16863. texture.url = url;
  16864. this._internalTexturesCache.push(texture);
  16865. var onerror = function (request, exception) {
  16866. scene._removePendingData(texture);
  16867. if (onError && request) {
  16868. onError(request.status + " " + request.statusText, exception);
  16869. }
  16870. };
  16871. var internalCallback = function (data) {
  16872. var width = texture.width;
  16873. var faceDataArrays = callback(data);
  16874. if (!faceDataArrays) {
  16875. return;
  16876. }
  16877. if (mipmapGenerator) {
  16878. var textureType = _this._getWebGLTextureType(type);
  16879. var internalFormat = _this._getInternalFormat(format);
  16880. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16881. var needConversion = false;
  16882. if (internalFormat === gl.RGB) {
  16883. internalFormat = gl.RGBA;
  16884. needConversion = true;
  16885. }
  16886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16887. _this._unpackFlipY(false);
  16888. var mipData = mipmapGenerator(faceDataArrays);
  16889. for (var level = 0; level < mipData.length; level++) {
  16890. var mipSize = width >> level;
  16891. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16892. var mipFaceData = mipData[level][faceIndex];
  16893. if (needConversion) {
  16894. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16895. }
  16896. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16897. }
  16898. }
  16899. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16900. }
  16901. else {
  16902. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16903. }
  16904. texture.isReady = true;
  16905. // this.resetTextureCache();
  16906. scene._removePendingData(texture);
  16907. if (onLoad) {
  16908. onLoad();
  16909. }
  16910. };
  16911. this._loadFile(url, function (data) {
  16912. internalCallback(data);
  16913. }, undefined, scene.offlineProvider, true, onerror);
  16914. return texture;
  16915. };
  16916. /**
  16917. * Update a raw 3D texture
  16918. * @param texture defines the texture to update
  16919. * @param data defines the data to store
  16920. * @param format defines the data format
  16921. * @param invertY defines if data must be stored with Y axis inverted
  16922. * @param compression defines the used compression (can be null)
  16923. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16924. */
  16925. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16926. if (compression === void 0) { compression = null; }
  16927. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16928. var internalType = this._getWebGLTextureType(textureType);
  16929. var internalFormat = this._getInternalFormat(format);
  16930. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16931. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16932. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16933. if (!this._doNotHandleContextLost) {
  16934. texture._bufferView = data;
  16935. texture.format = format;
  16936. texture.invertY = invertY;
  16937. texture._compression = compression;
  16938. }
  16939. if (texture.width % 4 !== 0) {
  16940. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16941. }
  16942. if (compression && data) {
  16943. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16944. }
  16945. else {
  16946. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16947. }
  16948. if (texture.generateMipMaps) {
  16949. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16950. }
  16951. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16952. // this.resetTextureCache();
  16953. texture.isReady = true;
  16954. };
  16955. /**
  16956. * Creates a new raw 3D texture
  16957. * @param data defines the data used to create the texture
  16958. * @param width defines the width of the texture
  16959. * @param height defines the height of the texture
  16960. * @param depth defines the depth of the texture
  16961. * @param format defines the format of the texture
  16962. * @param generateMipMaps defines if the engine must generate mip levels
  16963. * @param invertY defines if data must be stored with Y axis inverted
  16964. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16965. * @param compression defines the compressed used (can be null)
  16966. * @param textureType defines the compressed used (can be null)
  16967. * @returns a new raw 3D texture (stored in an InternalTexture)
  16968. */
  16969. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16970. if (compression === void 0) { compression = null; }
  16971. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16972. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16973. texture.baseWidth = width;
  16974. texture.baseHeight = height;
  16975. texture.baseDepth = depth;
  16976. texture.width = width;
  16977. texture.height = height;
  16978. texture.depth = depth;
  16979. texture.format = format;
  16980. texture.type = textureType;
  16981. texture.generateMipMaps = generateMipMaps;
  16982. texture.samplingMode = samplingMode;
  16983. texture.is3D = true;
  16984. if (!this._doNotHandleContextLost) {
  16985. texture._bufferView = data;
  16986. }
  16987. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16988. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16989. // Filters
  16990. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16991. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16992. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16993. if (generateMipMaps) {
  16994. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16995. }
  16996. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16997. this._internalTexturesCache.push(texture);
  16998. return texture;
  16999. };
  17000. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17001. var gl = this._gl;
  17002. if (!gl) {
  17003. return;
  17004. }
  17005. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17008. if (!noMipmap && !isCompressed) {
  17009. gl.generateMipmap(gl.TEXTURE_2D);
  17010. }
  17011. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17012. // this.resetTextureCache();
  17013. if (scene) {
  17014. scene._removePendingData(texture);
  17015. }
  17016. texture.onLoadedObservable.notifyObservers(texture);
  17017. texture.onLoadedObservable.clear();
  17018. };
  17019. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17020. var _this = this;
  17021. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17022. var maxTextureSize = this.getCaps().maxTextureSize;
  17023. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17024. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17025. var gl = this._gl;
  17026. if (!gl) {
  17027. return;
  17028. }
  17029. if (!texture._webGLTexture) {
  17030. // this.resetTextureCache();
  17031. if (scene) {
  17032. scene._removePendingData(texture);
  17033. }
  17034. return;
  17035. }
  17036. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17037. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17038. texture.baseWidth = width;
  17039. texture.baseHeight = height;
  17040. texture.width = potWidth;
  17041. texture.height = potHeight;
  17042. texture.isReady = true;
  17043. if (processFunction(potWidth, potHeight, function () {
  17044. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17045. })) {
  17046. // Returning as texture needs extra async steps
  17047. return;
  17048. }
  17049. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17050. };
  17051. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17052. // Create new RGBA data container.
  17053. var rgbaData;
  17054. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17055. rgbaData = new Float32Array(width * height * 4);
  17056. }
  17057. else {
  17058. rgbaData = new Uint32Array(width * height * 4);
  17059. }
  17060. // Convert each pixel.
  17061. for (var x = 0; x < width; x++) {
  17062. for (var y = 0; y < height; y++) {
  17063. var index = (y * width + x) * 3;
  17064. var newIndex = (y * width + x) * 4;
  17065. // Map Old Value to new value.
  17066. rgbaData[newIndex + 0] = rgbData[index + 0];
  17067. rgbaData[newIndex + 1] = rgbData[index + 1];
  17068. rgbaData[newIndex + 2] = rgbData[index + 2];
  17069. // Add fully opaque alpha channel.
  17070. rgbaData[newIndex + 3] = 1;
  17071. }
  17072. }
  17073. return rgbaData;
  17074. };
  17075. /** @hidden */
  17076. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17077. var gl = this._gl;
  17078. if (texture._framebuffer) {
  17079. gl.deleteFramebuffer(texture._framebuffer);
  17080. texture._framebuffer = null;
  17081. }
  17082. if (texture._depthStencilBuffer) {
  17083. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17084. texture._depthStencilBuffer = null;
  17085. }
  17086. if (texture._MSAAFramebuffer) {
  17087. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17088. texture._MSAAFramebuffer = null;
  17089. }
  17090. if (texture._MSAARenderBuffer) {
  17091. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17092. texture._MSAARenderBuffer = null;
  17093. }
  17094. };
  17095. /** @hidden */
  17096. Engine.prototype._releaseTexture = function (texture) {
  17097. var gl = this._gl;
  17098. this._releaseFramebufferObjects(texture);
  17099. gl.deleteTexture(texture._webGLTexture);
  17100. // Unbind channels
  17101. this.unbindAllTextures();
  17102. var index = this._internalTexturesCache.indexOf(texture);
  17103. if (index !== -1) {
  17104. this._internalTexturesCache.splice(index, 1);
  17105. }
  17106. // Integrated fixed lod samplers.
  17107. if (texture._lodTextureHigh) {
  17108. texture._lodTextureHigh.dispose();
  17109. }
  17110. if (texture._lodTextureMid) {
  17111. texture._lodTextureMid.dispose();
  17112. }
  17113. if (texture._lodTextureLow) {
  17114. texture._lodTextureLow.dispose();
  17115. }
  17116. // Set output texture of post process to null if the texture has been released/disposed
  17117. this.scenes.forEach(function (scene) {
  17118. scene.postProcesses.forEach(function (postProcess) {
  17119. if (postProcess._outputTexture == texture) {
  17120. postProcess._outputTexture = null;
  17121. }
  17122. });
  17123. scene.cameras.forEach(function (camera) {
  17124. camera._postProcesses.forEach(function (postProcess) {
  17125. if (postProcess) {
  17126. if (postProcess._outputTexture == texture) {
  17127. postProcess._outputTexture = null;
  17128. }
  17129. }
  17130. });
  17131. });
  17132. });
  17133. };
  17134. Engine.prototype.setProgram = function (program) {
  17135. if (this._currentProgram !== program) {
  17136. this._gl.useProgram(program);
  17137. this._currentProgram = program;
  17138. }
  17139. };
  17140. /**
  17141. * Binds an effect to the webGL context
  17142. * @param effect defines the effect to bind
  17143. */
  17144. Engine.prototype.bindSamplers = function (effect) {
  17145. this.setProgram(effect.getProgram());
  17146. var samplers = effect.getSamplers();
  17147. for (var index = 0; index < samplers.length; index++) {
  17148. var uniform = effect.getUniform(samplers[index]);
  17149. if (uniform) {
  17150. this._boundUniforms[index] = uniform;
  17151. }
  17152. }
  17153. this._currentEffect = null;
  17154. };
  17155. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17156. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17157. return;
  17158. }
  17159. // Remove
  17160. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17161. // Bind last to it
  17162. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17163. // Bind to dummy
  17164. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17165. };
  17166. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17167. if (!internalTexture) {
  17168. return -1;
  17169. }
  17170. internalTexture._initialSlot = channel;
  17171. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17172. if (channel !== internalTexture._designatedSlot) {
  17173. this._textureCollisions.addCount(1, false);
  17174. }
  17175. }
  17176. else {
  17177. if (channel !== internalTexture._designatedSlot) {
  17178. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17179. return internalTexture._designatedSlot;
  17180. }
  17181. else {
  17182. // No slot for this texture, let's pick a new one (if we find a free slot)
  17183. if (this._nextFreeTextureSlots.length) {
  17184. return this._nextFreeTextureSlots[0];
  17185. }
  17186. // We need to recycle the oldest bound texture, sorry.
  17187. this._textureCollisions.addCount(1, false);
  17188. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17189. }
  17190. }
  17191. }
  17192. return channel;
  17193. };
  17194. Engine.prototype._linkTrackers = function (previous, next) {
  17195. previous.next = next;
  17196. next.previous = previous;
  17197. };
  17198. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17199. var currentSlot = internalTexture._designatedSlot;
  17200. if (currentSlot === -1) {
  17201. return -1;
  17202. }
  17203. internalTexture._designatedSlot = -1;
  17204. if (this.disableTextureBindingOptimization) {
  17205. return -1;
  17206. }
  17207. // Remove from bound list
  17208. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17209. // Free the slot
  17210. this._boundTexturesCache[currentSlot] = null;
  17211. this._nextFreeTextureSlots.push(currentSlot);
  17212. return currentSlot;
  17213. };
  17214. Engine.prototype._activateCurrentTexture = function () {
  17215. if (this._currentTextureChannel !== this._activeChannel) {
  17216. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17217. this._currentTextureChannel = this._activeChannel;
  17218. }
  17219. };
  17220. /** @hidden */
  17221. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17222. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17223. if (force === void 0) { force = false; }
  17224. var wasPreviouslyBound = false;
  17225. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17226. this._activeChannel = texture._designatedSlot;
  17227. }
  17228. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17229. var isTextureForRendering = texture && texture._initialSlot > -1;
  17230. if (currentTextureBound !== texture || force) {
  17231. if (currentTextureBound) {
  17232. this._removeDesignatedSlot(currentTextureBound);
  17233. }
  17234. this._activateCurrentTexture();
  17235. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17236. this._boundTexturesCache[this._activeChannel] = texture;
  17237. if (texture) {
  17238. if (!this.disableTextureBindingOptimization) {
  17239. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17240. if (slotIndex > -1) {
  17241. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17242. }
  17243. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17244. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17245. }
  17246. texture._designatedSlot = this._activeChannel;
  17247. }
  17248. }
  17249. else if (forTextureDataUpdate) {
  17250. wasPreviouslyBound = true;
  17251. this._activateCurrentTexture();
  17252. }
  17253. if (isTextureForRendering && !forTextureDataUpdate) {
  17254. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17255. }
  17256. return wasPreviouslyBound;
  17257. };
  17258. /** @hidden */
  17259. Engine.prototype._bindTexture = function (channel, texture) {
  17260. if (channel < 0) {
  17261. return;
  17262. }
  17263. if (texture) {
  17264. channel = this._getCorrectTextureChannel(channel, texture);
  17265. }
  17266. this._activeChannel = channel;
  17267. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17268. };
  17269. /**
  17270. * Sets a texture to the webGL context from a postprocess
  17271. * @param channel defines the channel to use
  17272. * @param postProcess defines the source postprocess
  17273. */
  17274. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17275. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17276. };
  17277. /**
  17278. * Binds the output of the passed in post process to the texture channel specified
  17279. * @param channel The channel the texture should be bound to
  17280. * @param postProcess The post process which's output should be bound
  17281. */
  17282. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17283. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17284. };
  17285. /**
  17286. * Unbind all textures from the webGL context
  17287. */
  17288. Engine.prototype.unbindAllTextures = function () {
  17289. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17290. this._activeChannel = channel;
  17291. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17292. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17293. if (this.webGLVersion > 1) {
  17294. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17295. }
  17296. }
  17297. };
  17298. /**
  17299. * Sets a texture to the according uniform.
  17300. * @param channel The texture channel
  17301. * @param uniform The uniform to set
  17302. * @param texture The texture to apply
  17303. */
  17304. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17305. if (channel < 0) {
  17306. return;
  17307. }
  17308. if (uniform) {
  17309. this._boundUniforms[channel] = uniform;
  17310. }
  17311. this._setTexture(channel, texture);
  17312. };
  17313. /**
  17314. * Sets a depth stencil texture from a render target to the according uniform.
  17315. * @param channel The texture channel
  17316. * @param uniform The uniform to set
  17317. * @param texture The render target texture containing the depth stencil texture to apply
  17318. */
  17319. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17320. if (channel < 0) {
  17321. return;
  17322. }
  17323. if (uniform) {
  17324. this._boundUniforms[channel] = uniform;
  17325. }
  17326. if (!texture || !texture.depthStencilTexture) {
  17327. this._setTexture(channel, null);
  17328. }
  17329. else {
  17330. this._setTexture(channel, texture, false, true);
  17331. }
  17332. };
  17333. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17334. var uniform = this._boundUniforms[sourceSlot];
  17335. if (uniform._currentState === destination) {
  17336. return;
  17337. }
  17338. this._gl.uniform1i(uniform, destination);
  17339. uniform._currentState = destination;
  17340. };
  17341. Engine.prototype._getTextureWrapMode = function (mode) {
  17342. switch (mode) {
  17343. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17344. return this._gl.REPEAT;
  17345. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17346. return this._gl.CLAMP_TO_EDGE;
  17347. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17348. return this._gl.MIRRORED_REPEAT;
  17349. }
  17350. return this._gl.REPEAT;
  17351. };
  17352. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17353. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17354. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17355. // Not ready?
  17356. if (!texture) {
  17357. if (this._boundTexturesCache[channel] != null) {
  17358. this._activeChannel = channel;
  17359. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17360. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17361. if (this.webGLVersion > 1) {
  17362. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17363. }
  17364. }
  17365. return false;
  17366. }
  17367. // Video
  17368. if (texture.video) {
  17369. this._activeChannel = channel;
  17370. texture.update();
  17371. }
  17372. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17373. texture.delayLoad();
  17374. return false;
  17375. }
  17376. var internalTexture;
  17377. if (depthStencilTexture) {
  17378. internalTexture = texture.depthStencilTexture;
  17379. }
  17380. else if (texture.isReady()) {
  17381. internalTexture = texture.getInternalTexture();
  17382. }
  17383. else if (texture.isCube) {
  17384. internalTexture = this.emptyCubeTexture;
  17385. }
  17386. else if (texture.is3D) {
  17387. internalTexture = this.emptyTexture3D;
  17388. }
  17389. else {
  17390. internalTexture = this.emptyTexture;
  17391. }
  17392. if (!isPartOfTextureArray) {
  17393. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17394. }
  17395. var needToBind = true;
  17396. if (this._boundTexturesCache[channel] === internalTexture) {
  17397. this._moveBoundTextureOnTop(internalTexture);
  17398. if (!isPartOfTextureArray) {
  17399. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17400. }
  17401. needToBind = false;
  17402. }
  17403. this._activeChannel = channel;
  17404. if (internalTexture && internalTexture.is3D) {
  17405. if (needToBind) {
  17406. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17407. }
  17408. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17409. internalTexture._cachedWrapU = texture.wrapU;
  17410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17411. }
  17412. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17413. internalTexture._cachedWrapV = texture.wrapV;
  17414. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17415. }
  17416. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17417. internalTexture._cachedWrapR = texture.wrapR;
  17418. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17419. }
  17420. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17421. }
  17422. else if (internalTexture && internalTexture.isCube) {
  17423. if (needToBind) {
  17424. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17425. }
  17426. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17427. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17428. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17429. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17430. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17431. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17432. }
  17433. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17434. }
  17435. else {
  17436. if (needToBind) {
  17437. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17438. }
  17439. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17440. internalTexture._cachedWrapU = texture.wrapU;
  17441. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17442. }
  17443. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17444. internalTexture._cachedWrapV = texture.wrapV;
  17445. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17446. }
  17447. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17448. }
  17449. return true;
  17450. };
  17451. /**
  17452. * Sets an array of texture to the webGL context
  17453. * @param channel defines the channel where the texture array must be set
  17454. * @param uniform defines the associated uniform location
  17455. * @param textures defines the array of textures to bind
  17456. */
  17457. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17458. if (channel < 0 || !uniform) {
  17459. return;
  17460. }
  17461. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17462. this._textureUnits = new Int32Array(textures.length);
  17463. }
  17464. for (var i = 0; i < textures.length; i++) {
  17465. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17466. }
  17467. this._gl.uniform1iv(uniform, this._textureUnits);
  17468. for (var index = 0; index < textures.length; index++) {
  17469. this._setTexture(this._textureUnits[index], textures[index], true);
  17470. }
  17471. };
  17472. /** @hidden */
  17473. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17474. var internalTexture = texture.getInternalTexture();
  17475. if (!internalTexture) {
  17476. return;
  17477. }
  17478. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17479. var value = texture.anisotropicFilteringLevel;
  17480. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17481. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17482. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17483. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17484. }
  17485. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17486. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17487. internalTexture._cachedAnisotropicFilteringLevel = value;
  17488. }
  17489. };
  17490. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17491. this._bindTextureDirectly(target, texture, true, true);
  17492. this._gl.texParameterf(target, parameter, value);
  17493. };
  17494. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17495. if (texture) {
  17496. this._bindTextureDirectly(target, texture, true, true);
  17497. }
  17498. this._gl.texParameteri(target, parameter, value);
  17499. };
  17500. /**
  17501. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17502. * @param x defines the x coordinate of the rectangle where pixels must be read
  17503. * @param y defines the y coordinate of the rectangle where pixels must be read
  17504. * @param width defines the width of the rectangle where pixels must be read
  17505. * @param height defines the height of the rectangle where pixels must be read
  17506. * @returns a Uint8Array containing RGBA colors
  17507. */
  17508. Engine.prototype.readPixels = function (x, y, width, height) {
  17509. var data = new Uint8Array(height * width * 4);
  17510. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17511. return data;
  17512. };
  17513. /**
  17514. * Add an externaly attached data from its key.
  17515. * This method call will fail and return false, if such key already exists.
  17516. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17517. * @param key the unique key that identifies the data
  17518. * @param data the data object to associate to the key for this Engine instance
  17519. * @return true if no such key were already present and the data was added successfully, false otherwise
  17520. */
  17521. Engine.prototype.addExternalData = function (key, data) {
  17522. if (!this._externalData) {
  17523. this._externalData = new BABYLON.StringDictionary();
  17524. }
  17525. return this._externalData.add(key, data);
  17526. };
  17527. /**
  17528. * Get an externaly attached data from its key
  17529. * @param key the unique key that identifies the data
  17530. * @return the associated data, if present (can be null), or undefined if not present
  17531. */
  17532. Engine.prototype.getExternalData = function (key) {
  17533. if (!this._externalData) {
  17534. this._externalData = new BABYLON.StringDictionary();
  17535. }
  17536. return this._externalData.get(key);
  17537. };
  17538. /**
  17539. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17540. * @param key the unique key that identifies the data
  17541. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17542. * @return the associated data, can be null if the factory returned null.
  17543. */
  17544. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17545. if (!this._externalData) {
  17546. this._externalData = new BABYLON.StringDictionary();
  17547. }
  17548. return this._externalData.getOrAddWithFactory(key, factory);
  17549. };
  17550. /**
  17551. * Remove an externaly attached data from the Engine instance
  17552. * @param key the unique key that identifies the data
  17553. * @return true if the data was successfully removed, false if it doesn't exist
  17554. */
  17555. Engine.prototype.removeExternalData = function (key) {
  17556. if (!this._externalData) {
  17557. this._externalData = new BABYLON.StringDictionary();
  17558. }
  17559. return this._externalData.remove(key);
  17560. };
  17561. /**
  17562. * Unbind all vertex attributes from the webGL context
  17563. */
  17564. Engine.prototype.unbindAllAttributes = function () {
  17565. if (this._mustWipeVertexAttributes) {
  17566. this._mustWipeVertexAttributes = false;
  17567. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17568. this._gl.disableVertexAttribArray(i);
  17569. this._vertexAttribArraysEnabled[i] = false;
  17570. this._currentBufferPointers[i].active = false;
  17571. }
  17572. return;
  17573. }
  17574. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17575. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17576. continue;
  17577. }
  17578. this._gl.disableVertexAttribArray(i);
  17579. this._vertexAttribArraysEnabled[i] = false;
  17580. this._currentBufferPointers[i].active = false;
  17581. }
  17582. };
  17583. /**
  17584. * 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
  17585. */
  17586. Engine.prototype.releaseEffects = function () {
  17587. for (var name in this._compiledEffects) {
  17588. this._deleteProgram(this._compiledEffects[name]._program);
  17589. }
  17590. this._compiledEffects = {};
  17591. };
  17592. /**
  17593. * Dispose and release all associated resources
  17594. */
  17595. Engine.prototype.dispose = function () {
  17596. this.hideLoadingUI();
  17597. this.stopRenderLoop();
  17598. // Release postProcesses
  17599. while (this.postProcesses.length) {
  17600. this.postProcesses[0].dispose();
  17601. }
  17602. // Empty texture
  17603. if (this._emptyTexture) {
  17604. this._releaseTexture(this._emptyTexture);
  17605. this._emptyTexture = null;
  17606. }
  17607. if (this._emptyCubeTexture) {
  17608. this._releaseTexture(this._emptyCubeTexture);
  17609. this._emptyCubeTexture = null;
  17610. }
  17611. // Rescale PP
  17612. if (this._rescalePostProcess) {
  17613. this._rescalePostProcess.dispose();
  17614. }
  17615. // Release scenes
  17616. while (this.scenes.length) {
  17617. this.scenes[0].dispose();
  17618. }
  17619. // Release audio engine
  17620. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17621. Engine.audioEngine.dispose();
  17622. }
  17623. // Release effects
  17624. this.releaseEffects();
  17625. // Unbind
  17626. this.unbindAllAttributes();
  17627. this._boundUniforms = [];
  17628. if (this._dummyFramebuffer) {
  17629. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17630. }
  17631. //WebVR
  17632. this.disableVR();
  17633. // Events
  17634. if (BABYLON.Tools.IsWindowObjectExist()) {
  17635. window.removeEventListener("blur", this._onBlur);
  17636. window.removeEventListener("focus", this._onFocus);
  17637. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17638. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17639. if (this._renderingCanvas) {
  17640. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17641. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17642. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17643. if (!this._doNotHandleContextLost) {
  17644. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17645. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17646. }
  17647. }
  17648. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17649. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17650. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17651. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17652. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17653. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17654. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17655. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17656. if (this._onVrDisplayConnect) {
  17657. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17658. if (this._onVrDisplayDisconnect) {
  17659. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17660. }
  17661. if (this._onVrDisplayPresentChange) {
  17662. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17663. }
  17664. this._onVrDisplayConnect = null;
  17665. this._onVrDisplayDisconnect = null;
  17666. }
  17667. }
  17668. // Remove from Instances
  17669. var index = Engine.Instances.indexOf(this);
  17670. if (index >= 0) {
  17671. Engine.Instances.splice(index, 1);
  17672. }
  17673. this._workingCanvas = null;
  17674. this._workingContext = null;
  17675. this._currentBufferPointers = [];
  17676. this._renderingCanvas = null;
  17677. this._currentProgram = null;
  17678. this._bindedRenderFunction = null;
  17679. this.onResizeObservable.clear();
  17680. this.onCanvasBlurObservable.clear();
  17681. this.onCanvasFocusObservable.clear();
  17682. this.onCanvasPointerOutObservable.clear();
  17683. this.onBeginFrameObservable.clear();
  17684. this.onEndFrameObservable.clear();
  17685. BABYLON.Effect.ResetCache();
  17686. // Abort active requests
  17687. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17688. var request = _a[_i];
  17689. request.abort();
  17690. }
  17691. };
  17692. // Loading screen
  17693. /**
  17694. * Display the loading screen
  17695. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17696. */
  17697. Engine.prototype.displayLoadingUI = function () {
  17698. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17699. return;
  17700. }
  17701. var loadingScreen = this.loadingScreen;
  17702. if (loadingScreen) {
  17703. loadingScreen.displayLoadingUI();
  17704. }
  17705. };
  17706. /**
  17707. * Hide the loading screen
  17708. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17709. */
  17710. Engine.prototype.hideLoadingUI = function () {
  17711. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17712. return;
  17713. }
  17714. var loadingScreen = this.loadingScreen;
  17715. if (loadingScreen) {
  17716. loadingScreen.hideLoadingUI();
  17717. }
  17718. };
  17719. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17720. /**
  17721. * Gets the current loading screen object
  17722. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17723. */
  17724. get: function () {
  17725. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17726. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17727. }
  17728. return this._loadingScreen;
  17729. },
  17730. /**
  17731. * Sets the current loading screen object
  17732. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17733. */
  17734. set: function (loadingScreen) {
  17735. this._loadingScreen = loadingScreen;
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17741. /**
  17742. * Sets the current loading screen text
  17743. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17744. */
  17745. set: function (text) {
  17746. this.loadingScreen.loadingUIText = text;
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17752. /**
  17753. * Sets the current loading screen background color
  17754. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17755. */
  17756. set: function (color) {
  17757. this.loadingScreen.loadingUIBackgroundColor = color;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. /**
  17763. * Attach a new callback raised when context lost event is fired
  17764. * @param callback defines the callback to call
  17765. */
  17766. Engine.prototype.attachContextLostEvent = function (callback) {
  17767. if (this._renderingCanvas) {
  17768. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17769. }
  17770. };
  17771. /**
  17772. * Attach a new callback raised when context restored event is fired
  17773. * @param callback defines the callback to call
  17774. */
  17775. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17776. if (this._renderingCanvas) {
  17777. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17778. }
  17779. };
  17780. /**
  17781. * Gets the source code of the vertex shader associated with a specific webGL program
  17782. * @param program defines the program to use
  17783. * @returns a string containing the source code of the vertex shader associated with the program
  17784. */
  17785. Engine.prototype.getVertexShaderSource = function (program) {
  17786. var shaders = this._gl.getAttachedShaders(program);
  17787. if (!shaders) {
  17788. return null;
  17789. }
  17790. return this._gl.getShaderSource(shaders[0]);
  17791. };
  17792. /**
  17793. * Gets the source code of the fragment shader associated with a specific webGL program
  17794. * @param program defines the program to use
  17795. * @returns a string containing the source code of the fragment shader associated with the program
  17796. */
  17797. Engine.prototype.getFragmentShaderSource = function (program) {
  17798. var shaders = this._gl.getAttachedShaders(program);
  17799. if (!shaders) {
  17800. return null;
  17801. }
  17802. return this._gl.getShaderSource(shaders[1]);
  17803. };
  17804. /**
  17805. * Get the current error code of the webGL context
  17806. * @returns the error code
  17807. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17808. */
  17809. Engine.prototype.getError = function () {
  17810. return this._gl.getError();
  17811. };
  17812. // FPS
  17813. /**
  17814. * Gets the current framerate
  17815. * @returns a number representing the framerate
  17816. */
  17817. Engine.prototype.getFps = function () {
  17818. return this._fps;
  17819. };
  17820. /**
  17821. * Gets the time spent between current and previous frame
  17822. * @returns a number representing the delta time in ms
  17823. */
  17824. Engine.prototype.getDeltaTime = function () {
  17825. return this._deltaTime;
  17826. };
  17827. Engine.prototype._measureFps = function () {
  17828. this._performanceMonitor.sampleFrame();
  17829. this._fps = this._performanceMonitor.averageFPS;
  17830. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17831. };
  17832. /** @hidden */
  17833. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17834. if (faceIndex === void 0) { faceIndex = -1; }
  17835. if (level === void 0) { level = 0; }
  17836. if (buffer === void 0) { buffer = null; }
  17837. var gl = this._gl;
  17838. if (!this._dummyFramebuffer) {
  17839. var dummy = gl.createFramebuffer();
  17840. if (!dummy) {
  17841. throw new Error("Unable to create dummy framebuffer");
  17842. }
  17843. this._dummyFramebuffer = dummy;
  17844. }
  17845. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17846. if (faceIndex > -1) {
  17847. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17848. }
  17849. else {
  17850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17851. }
  17852. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17853. switch (readType) {
  17854. case gl.UNSIGNED_BYTE:
  17855. if (!buffer) {
  17856. buffer = new Uint8Array(4 * width * height);
  17857. }
  17858. readType = gl.UNSIGNED_BYTE;
  17859. break;
  17860. default:
  17861. if (!buffer) {
  17862. buffer = new Float32Array(4 * width * height);
  17863. }
  17864. readType = gl.FLOAT;
  17865. break;
  17866. }
  17867. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17868. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17869. return buffer;
  17870. };
  17871. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17872. if (this._webGLVersion > 1) {
  17873. return this._caps.colorBufferFloat;
  17874. }
  17875. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17876. };
  17877. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17878. if (this._webGLVersion > 1) {
  17879. return this._caps.colorBufferFloat;
  17880. }
  17881. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17882. };
  17883. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17884. Engine.prototype._canRenderToFramebuffer = function (type) {
  17885. var gl = this._gl;
  17886. //clear existing errors
  17887. while (gl.getError() !== gl.NO_ERROR) { }
  17888. var successful = true;
  17889. var texture = gl.createTexture();
  17890. gl.bindTexture(gl.TEXTURE_2D, texture);
  17891. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17894. var fb = gl.createFramebuffer();
  17895. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17897. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17898. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17899. successful = successful && (gl.getError() === gl.NO_ERROR);
  17900. //try render by clearing frame buffer's color buffer
  17901. if (successful) {
  17902. gl.clear(gl.COLOR_BUFFER_BIT);
  17903. successful = successful && (gl.getError() === gl.NO_ERROR);
  17904. }
  17905. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17906. if (successful) {
  17907. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17908. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17909. var readFormat = gl.RGBA;
  17910. var readType = gl.UNSIGNED_BYTE;
  17911. var buffer = new Uint8Array(4);
  17912. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17913. successful = successful && (gl.getError() === gl.NO_ERROR);
  17914. }
  17915. //clean up
  17916. gl.deleteTexture(texture);
  17917. gl.deleteFramebuffer(fb);
  17918. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17919. //clear accumulated errors
  17920. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17921. return successful;
  17922. };
  17923. /** @hidden */
  17924. Engine.prototype._getWebGLTextureType = function (type) {
  17925. if (this._webGLVersion === 1) {
  17926. switch (type) {
  17927. case Engine.TEXTURETYPE_FLOAT:
  17928. return this._gl.FLOAT;
  17929. case Engine.TEXTURETYPE_HALF_FLOAT:
  17930. return this._gl.HALF_FLOAT_OES;
  17931. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17932. return this._gl.UNSIGNED_BYTE;
  17933. }
  17934. return this._gl.UNSIGNED_BYTE;
  17935. }
  17936. switch (type) {
  17937. case Engine.TEXTURETYPE_BYTE:
  17938. return this._gl.BYTE;
  17939. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17940. return this._gl.UNSIGNED_BYTE;
  17941. case Engine.TEXTURETYPE_SHORT:
  17942. return this._gl.SHORT;
  17943. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17944. return this._gl.UNSIGNED_SHORT;
  17945. case Engine.TEXTURETYPE_INT:
  17946. return this._gl.INT;
  17947. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17948. return this._gl.UNSIGNED_INT;
  17949. case Engine.TEXTURETYPE_FLOAT:
  17950. return this._gl.FLOAT;
  17951. case Engine.TEXTURETYPE_HALF_FLOAT:
  17952. return this._gl.HALF_FLOAT;
  17953. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17954. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17955. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17956. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17957. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17958. return this._gl.UNSIGNED_SHORT_5_6_5;
  17959. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17960. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17961. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17962. return this._gl.UNSIGNED_INT_24_8;
  17963. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17964. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17965. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17966. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17967. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17968. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17969. }
  17970. return this._gl.UNSIGNED_BYTE;
  17971. };
  17972. Engine.prototype._getInternalFormat = function (format) {
  17973. var internalFormat = this._gl.RGBA;
  17974. switch (format) {
  17975. case Engine.TEXTUREFORMAT_ALPHA:
  17976. internalFormat = this._gl.ALPHA;
  17977. break;
  17978. case Engine.TEXTUREFORMAT_LUMINANCE:
  17979. internalFormat = this._gl.LUMINANCE;
  17980. break;
  17981. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17982. internalFormat = this._gl.LUMINANCE_ALPHA;
  17983. break;
  17984. case Engine.TEXTUREFORMAT_RED:
  17985. internalFormat = this._gl.RED;
  17986. break;
  17987. case Engine.TEXTUREFORMAT_RG:
  17988. internalFormat = this._gl.RG;
  17989. break;
  17990. case Engine.TEXTUREFORMAT_RGB:
  17991. internalFormat = this._gl.RGB;
  17992. break;
  17993. case Engine.TEXTUREFORMAT_RGBA:
  17994. internalFormat = this._gl.RGBA;
  17995. break;
  17996. }
  17997. if (this._webGLVersion > 1) {
  17998. switch (format) {
  17999. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18000. internalFormat = this._gl.RED_INTEGER;
  18001. break;
  18002. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18003. internalFormat = this._gl.RG_INTEGER;
  18004. break;
  18005. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18006. internalFormat = this._gl.RGB_INTEGER;
  18007. break;
  18008. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18009. internalFormat = this._gl.RGBA_INTEGER;
  18010. break;
  18011. }
  18012. }
  18013. return internalFormat;
  18014. };
  18015. /** @hidden */
  18016. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18017. if (this._webGLVersion === 1) {
  18018. if (format !== undefined) {
  18019. switch (format) {
  18020. case Engine.TEXTUREFORMAT_ALPHA:
  18021. return this._gl.ALPHA;
  18022. case Engine.TEXTUREFORMAT_LUMINANCE:
  18023. return this._gl.LUMINANCE;
  18024. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18025. return this._gl.LUMINANCE_ALPHA;
  18026. }
  18027. }
  18028. return this._gl.RGBA;
  18029. }
  18030. switch (type) {
  18031. case Engine.TEXTURETYPE_BYTE:
  18032. switch (format) {
  18033. case Engine.TEXTUREFORMAT_RED:
  18034. return this._gl.R8_SNORM;
  18035. case Engine.TEXTUREFORMAT_RG:
  18036. return this._gl.RG8_SNORM;
  18037. case Engine.TEXTUREFORMAT_RGB:
  18038. return this._gl.RGB8_SNORM;
  18039. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18040. return this._gl.R8I;
  18041. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18042. return this._gl.RG8I;
  18043. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18044. return this._gl.RGB8I;
  18045. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18046. return this._gl.RGBA8I;
  18047. default:
  18048. return this._gl.RGBA8_SNORM;
  18049. }
  18050. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18051. switch (format) {
  18052. case Engine.TEXTUREFORMAT_RED:
  18053. return this._gl.R8;
  18054. case Engine.TEXTUREFORMAT_RG:
  18055. return this._gl.RG8;
  18056. case Engine.TEXTUREFORMAT_RGB:
  18057. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18058. case Engine.TEXTUREFORMAT_RGBA:
  18059. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18060. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18061. return this._gl.R8UI;
  18062. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18063. return this._gl.RG8UI;
  18064. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18065. return this._gl.RGB8UI;
  18066. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18067. return this._gl.RGBA8UI;
  18068. default:
  18069. return this._gl.RGBA8;
  18070. }
  18071. case Engine.TEXTURETYPE_SHORT:
  18072. switch (format) {
  18073. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18074. return this._gl.R16I;
  18075. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18076. return this._gl.RG16I;
  18077. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18078. return this._gl.RGB16I;
  18079. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18080. return this._gl.RGBA16I;
  18081. default:
  18082. return this._gl.RGBA16I;
  18083. }
  18084. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18085. switch (format) {
  18086. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18087. return this._gl.R16UI;
  18088. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18089. return this._gl.RG16UI;
  18090. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18091. return this._gl.RGB16UI;
  18092. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18093. return this._gl.RGBA16UI;
  18094. default:
  18095. return this._gl.RGBA16UI;
  18096. }
  18097. case Engine.TEXTURETYPE_INT:
  18098. switch (format) {
  18099. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18100. return this._gl.R32I;
  18101. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18102. return this._gl.RG32I;
  18103. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18104. return this._gl.RGB32I;
  18105. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18106. return this._gl.RGBA32I;
  18107. default:
  18108. return this._gl.RGBA32I;
  18109. }
  18110. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18111. switch (format) {
  18112. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18113. return this._gl.R32UI;
  18114. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18115. return this._gl.RG32UI;
  18116. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18117. return this._gl.RGB32UI;
  18118. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18119. return this._gl.RGBA32UI;
  18120. default:
  18121. return this._gl.RGBA32UI;
  18122. }
  18123. case Engine.TEXTURETYPE_FLOAT:
  18124. switch (format) {
  18125. case Engine.TEXTUREFORMAT_RED:
  18126. return this._gl.R32F; // By default. Other possibility is R16F.
  18127. case Engine.TEXTUREFORMAT_RG:
  18128. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18129. case Engine.TEXTUREFORMAT_RGB:
  18130. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18131. case Engine.TEXTUREFORMAT_RGBA:
  18132. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18133. default:
  18134. return this._gl.RGBA32F;
  18135. }
  18136. case Engine.TEXTURETYPE_HALF_FLOAT:
  18137. switch (format) {
  18138. case Engine.TEXTUREFORMAT_RED:
  18139. return this._gl.R16F;
  18140. case Engine.TEXTUREFORMAT_RG:
  18141. return this._gl.RG16F;
  18142. case Engine.TEXTUREFORMAT_RGB:
  18143. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18144. case Engine.TEXTUREFORMAT_RGBA:
  18145. return this._gl.RGBA16F;
  18146. default:
  18147. return this._gl.RGBA16F;
  18148. }
  18149. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18150. return this._gl.RGB565;
  18151. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18152. return this._gl.R11F_G11F_B10F;
  18153. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18154. return this._gl.RGB9_E5;
  18155. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18156. return this._gl.RGBA4;
  18157. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18158. return this._gl.RGB5_A1;
  18159. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18160. switch (format) {
  18161. case Engine.TEXTUREFORMAT_RGBA:
  18162. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18163. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18164. return this._gl.RGB10_A2UI;
  18165. default:
  18166. return this._gl.RGB10_A2;
  18167. }
  18168. }
  18169. return this._gl.RGBA8;
  18170. };
  18171. /** @hidden */
  18172. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18173. if (type === Engine.TEXTURETYPE_FLOAT) {
  18174. return this._gl.RGBA32F;
  18175. }
  18176. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18177. return this._gl.RGBA16F;
  18178. }
  18179. return this._gl.RGBA8;
  18180. };
  18181. /** @hidden */
  18182. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18183. var _this = this;
  18184. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18185. this._activeRequests.push(request);
  18186. request.onCompleteObservable.add(function (request) {
  18187. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18188. });
  18189. return request;
  18190. };
  18191. /** @hidden */
  18192. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18193. var _this = this;
  18194. return new Promise(function (resolve, reject) {
  18195. _this._loadFile(url, function (data) {
  18196. resolve(data);
  18197. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18198. reject(exception);
  18199. });
  18200. });
  18201. };
  18202. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18203. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18204. var onload = function (data) {
  18205. loadedFiles[index] = data;
  18206. loadedFiles._internalCount++;
  18207. if (loadedFiles._internalCount === 6) {
  18208. onfinish(loadedFiles);
  18209. }
  18210. };
  18211. var onerror = function (request, exception) {
  18212. if (onErrorCallBack && request) {
  18213. onErrorCallBack(request.status + " " + request.statusText, exception);
  18214. }
  18215. };
  18216. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18217. };
  18218. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18219. if (onError === void 0) { onError = null; }
  18220. var loadedFiles = [];
  18221. loadedFiles._internalCount = 0;
  18222. for (var index = 0; index < 6; index++) {
  18223. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18224. }
  18225. };
  18226. // Statics
  18227. /**
  18228. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18229. * @returns true if the engine can be created
  18230. * @ignorenaming
  18231. */
  18232. Engine.isSupported = function () {
  18233. try {
  18234. var tempcanvas = document.createElement("canvas");
  18235. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18236. return gl != null && !!window.WebGLRenderingContext;
  18237. }
  18238. catch (e) {
  18239. return false;
  18240. }
  18241. };
  18242. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18243. Engine.ExceptionList = [
  18244. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18245. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18246. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18247. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18248. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18249. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18250. ];
  18251. /** Gets the list of created engines */
  18252. Engine.Instances = new Array();
  18253. /**
  18254. * Hidden
  18255. */
  18256. Engine._TextureLoaders = [];
  18257. // Const statics
  18258. /** Defines that alpha blending is disabled */
  18259. Engine.ALPHA_DISABLE = 0;
  18260. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18261. Engine.ALPHA_ADD = 1;
  18262. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18263. Engine.ALPHA_COMBINE = 2;
  18264. /** Defines that alpha blending to DEST - SRC * DEST */
  18265. Engine.ALPHA_SUBTRACT = 3;
  18266. /** Defines that alpha blending to SRC * DEST */
  18267. Engine.ALPHA_MULTIPLY = 4;
  18268. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18269. Engine.ALPHA_MAXIMIZED = 5;
  18270. /** Defines that alpha blending to SRC + DEST */
  18271. Engine.ALPHA_ONEONE = 6;
  18272. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18273. Engine.ALPHA_PREMULTIPLIED = 7;
  18274. /**
  18275. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18276. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18277. */
  18278. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18279. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18280. Engine.ALPHA_INTERPOLATE = 9;
  18281. /**
  18282. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18283. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18284. */
  18285. Engine.ALPHA_SCREENMODE = 10;
  18286. /** Defines that the ressource is not delayed*/
  18287. Engine.DELAYLOADSTATE_NONE = 0;
  18288. /** Defines that the ressource was successfully delay loaded */
  18289. Engine.DELAYLOADSTATE_LOADED = 1;
  18290. /** Defines that the ressource is currently delay loading */
  18291. Engine.DELAYLOADSTATE_LOADING = 2;
  18292. /** Defines that the ressource is delayed and has not started loading */
  18293. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18294. // Depht or Stencil test Constants.
  18295. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18296. Engine.NEVER = 0x0200;
  18297. /** 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 */
  18298. Engine.ALWAYS = 0x0207;
  18299. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18300. Engine.LESS = 0x0201;
  18301. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18302. Engine.EQUAL = 0x0202;
  18303. /** 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 */
  18304. Engine.LEQUAL = 0x0203;
  18305. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18306. Engine.GREATER = 0x0204;
  18307. /** 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 */
  18308. Engine.GEQUAL = 0x0206;
  18309. /** 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 */
  18310. Engine.NOTEQUAL = 0x0205;
  18311. // Stencil Actions Constants.
  18312. /** Passed to stencilOperation to specify that stencil value must be kept */
  18313. Engine.KEEP = 0x1E00;
  18314. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18315. Engine.REPLACE = 0x1E01;
  18316. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18317. Engine.INCR = 0x1E02;
  18318. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18319. Engine.DECR = 0x1E03;
  18320. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18321. Engine.INVERT = 0x150A;
  18322. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18323. Engine.INCR_WRAP = 0x8507;
  18324. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18325. Engine.DECR_WRAP = 0x8508;
  18326. /** Texture is not repeating outside of 0..1 UVs */
  18327. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18328. /** Texture is repeating outside of 0..1 UVs */
  18329. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18330. /** Texture is repeating and mirrored */
  18331. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18332. /** ALPHA */
  18333. Engine.TEXTUREFORMAT_ALPHA = 0;
  18334. /** LUMINANCE */
  18335. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18336. /** LUMINANCE_ALPHA */
  18337. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18338. /** RGB */
  18339. Engine.TEXTUREFORMAT_RGB = 4;
  18340. /** RGBA */
  18341. Engine.TEXTUREFORMAT_RGBA = 5;
  18342. /** RED */
  18343. Engine.TEXTUREFORMAT_RED = 6;
  18344. /** RED (2nd reference) */
  18345. Engine.TEXTUREFORMAT_R = 6;
  18346. /** RG */
  18347. Engine.TEXTUREFORMAT_RG = 7;
  18348. /** RED_INTEGER */
  18349. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18350. /** RED_INTEGER (2nd reference) */
  18351. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18352. /** RG_INTEGER */
  18353. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18354. /** RGB_INTEGER */
  18355. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18356. /** RGBA_INTEGER */
  18357. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18358. /** UNSIGNED_BYTE */
  18359. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18360. /** UNSIGNED_BYTE (2nd reference) */
  18361. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18362. /** FLOAT */
  18363. Engine.TEXTURETYPE_FLOAT = 1;
  18364. /** HALF_FLOAT */
  18365. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18366. /** BYTE */
  18367. Engine.TEXTURETYPE_BYTE = 3;
  18368. /** SHORT */
  18369. Engine.TEXTURETYPE_SHORT = 4;
  18370. /** UNSIGNED_SHORT */
  18371. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18372. /** INT */
  18373. Engine.TEXTURETYPE_INT = 6;
  18374. /** UNSIGNED_INT */
  18375. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18376. /** UNSIGNED_SHORT_4_4_4_4 */
  18377. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18378. /** UNSIGNED_SHORT_5_5_5_1 */
  18379. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18380. /** UNSIGNED_SHORT_5_6_5 */
  18381. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18382. /** UNSIGNED_INT_2_10_10_10_REV */
  18383. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18384. /** UNSIGNED_INT_24_8 */
  18385. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18386. /** UNSIGNED_INT_10F_11F_11F_REV */
  18387. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18388. /** UNSIGNED_INT_5_9_9_9_REV */
  18389. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18390. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18391. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18392. /** nearest is mag = nearest and min = nearest and mip = linear */
  18393. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18394. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18395. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18396. /** Trilinear is mag = linear and min = linear and mip = linear */
  18397. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18398. /** nearest is mag = nearest and min = nearest and mip = linear */
  18399. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18400. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18401. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18402. /** Trilinear is mag = linear and min = linear and mip = linear */
  18403. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18404. /** mag = nearest and min = nearest and mip = nearest */
  18405. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18406. /** mag = nearest and min = linear and mip = nearest */
  18407. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18408. /** mag = nearest and min = linear and mip = linear */
  18409. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18410. /** mag = nearest and min = linear and mip = none */
  18411. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18412. /** mag = nearest and min = nearest and mip = none */
  18413. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18414. /** mag = linear and min = nearest and mip = nearest */
  18415. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18416. /** mag = linear and min = nearest and mip = linear */
  18417. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18418. /** mag = linear and min = linear and mip = none */
  18419. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18420. /** mag = linear and min = nearest and mip = none */
  18421. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18422. /** Explicit coordinates mode */
  18423. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18424. /** Spherical coordinates mode */
  18425. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18426. /** Planar coordinates mode */
  18427. Engine.TEXTURE_PLANAR_MODE = 2;
  18428. /** Cubic coordinates mode */
  18429. Engine.TEXTURE_CUBIC_MODE = 3;
  18430. /** Projection coordinates mode */
  18431. Engine.TEXTURE_PROJECTION_MODE = 4;
  18432. /** Skybox coordinates mode */
  18433. Engine.TEXTURE_SKYBOX_MODE = 5;
  18434. /** Inverse Cubic coordinates mode */
  18435. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18436. /** Equirectangular coordinates mode */
  18437. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18438. /** Equirectangular Fixed coordinates mode */
  18439. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18440. /** Equirectangular Fixed Mirrored coordinates mode */
  18441. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18442. // Texture rescaling mode
  18443. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18444. Engine.SCALEMODE_FLOOR = 1;
  18445. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18446. Engine.SCALEMODE_NEAREST = 2;
  18447. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18448. Engine.SCALEMODE_CEILING = 3;
  18449. // Updatable statics so stick with vars here
  18450. /**
  18451. * Gets or sets the epsilon value used by collision engine
  18452. */
  18453. Engine.CollisionsEpsilon = 0.001;
  18454. /**
  18455. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18456. */
  18457. Engine.CodeRepository = "src/";
  18458. /**
  18459. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18460. */
  18461. Engine.ShadersRepository = "src/Shaders/";
  18462. return Engine;
  18463. }());
  18464. BABYLON.Engine = Engine;
  18465. })(BABYLON || (BABYLON = {}));
  18466. //# sourceMappingURL=babylon.engine.js.map
  18467. var BABYLON;
  18468. (function (BABYLON) {
  18469. /**
  18470. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18471. */
  18472. var Node = /** @class */ (function () {
  18473. /**
  18474. * Creates a new Node
  18475. * @param name the name and id to be given to this node
  18476. * @param scene the scene this node will be added to
  18477. */
  18478. function Node(name, scene) {
  18479. if (scene === void 0) { scene = null; }
  18480. /**
  18481. * Gets or sets a string used to store user defined state for the node
  18482. */
  18483. this.state = "";
  18484. /**
  18485. * Gets or sets an object used to store user defined information for the node
  18486. */
  18487. this.metadata = null;
  18488. /**
  18489. * Gets or sets a boolean used to define if the node must be serialized
  18490. */
  18491. this.doNotSerialize = false;
  18492. /** @hidden */
  18493. this._isDisposed = false;
  18494. /**
  18495. * Gets a list of Animations associated with the node
  18496. */
  18497. this.animations = new Array();
  18498. this._ranges = {};
  18499. this._isEnabled = true;
  18500. this._isParentEnabled = true;
  18501. this._isReady = true;
  18502. /** @hidden */
  18503. this._currentRenderId = -1;
  18504. this._parentRenderId = -1;
  18505. this._childRenderId = -1;
  18506. /** @hidden */
  18507. this._worldMatrix = BABYLON.Matrix.Identity();
  18508. /** @hidden */
  18509. this._worldMatrixDeterminant = 0;
  18510. /** @hidden */
  18511. this._sceneRootNodesIndex = -1;
  18512. this._animationPropertiesOverride = null;
  18513. /**
  18514. * An event triggered when the mesh is disposed
  18515. */
  18516. this.onDisposeObservable = new BABYLON.Observable();
  18517. // Behaviors
  18518. this._behaviors = new Array();
  18519. this.name = name;
  18520. this.id = name;
  18521. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18522. this.uniqueId = this._scene.getUniqueId();
  18523. this._initCache();
  18524. this.addToSceneRootNodes();
  18525. }
  18526. /**
  18527. * Add a new node constructor
  18528. * @param type defines the type name of the node to construct
  18529. * @param constructorFunc defines the constructor function
  18530. */
  18531. Node.AddNodeConstructor = function (type, constructorFunc) {
  18532. this._NodeConstructors[type] = constructorFunc;
  18533. };
  18534. /**
  18535. * Returns a node constructor based on type name
  18536. * @param type defines the type name
  18537. * @param name defines the new node name
  18538. * @param scene defines the hosting scene
  18539. * @param options defines optional options to transmit to constructors
  18540. * @returns the new constructor or null
  18541. */
  18542. Node.Construct = function (type, name, scene, options) {
  18543. var constructorFunc = this._NodeConstructors[type];
  18544. if (!constructorFunc) {
  18545. return null;
  18546. }
  18547. return constructorFunc(name, scene, options);
  18548. };
  18549. /**
  18550. * Gets a boolean indicating if the node has been disposed
  18551. * @returns true if the node was disposed
  18552. */
  18553. Node.prototype.isDisposed = function () {
  18554. return this._isDisposed;
  18555. };
  18556. Object.defineProperty(Node.prototype, "parent", {
  18557. get: function () {
  18558. return this._parentNode;
  18559. },
  18560. /**
  18561. * Gets or sets the parent of the node
  18562. */
  18563. set: function (parent) {
  18564. if (this._parentNode === parent) {
  18565. return;
  18566. }
  18567. var previousParentNode = this._parentNode;
  18568. // Remove self from list of children of parent
  18569. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18570. var index = this._parentNode._children.indexOf(this);
  18571. if (index !== -1) {
  18572. this._parentNode._children.splice(index, 1);
  18573. }
  18574. if (!parent) {
  18575. this.addToSceneRootNodes();
  18576. }
  18577. }
  18578. // Store new parent
  18579. this._parentNode = parent;
  18580. // Add as child to new parent
  18581. if (this._parentNode) {
  18582. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18583. this._parentNode._children = new Array();
  18584. }
  18585. this._parentNode._children.push(this);
  18586. if (!previousParentNode) {
  18587. this.removeFromSceneRootNodes();
  18588. }
  18589. }
  18590. // Enabled state
  18591. this._syncParentEnabledState();
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. Node.prototype.addToSceneRootNodes = function () {
  18597. if (this._sceneRootNodesIndex === -1) {
  18598. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18599. this._scene.rootNodes.push(this);
  18600. }
  18601. };
  18602. Node.prototype.removeFromSceneRootNodes = function () {
  18603. if (this._sceneRootNodesIndex !== -1) {
  18604. var rootNodes = this._scene.rootNodes;
  18605. var lastIdx = rootNodes.length - 1;
  18606. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18607. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18608. this._scene.rootNodes.pop();
  18609. this._sceneRootNodesIndex = -1;
  18610. }
  18611. };
  18612. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18613. /**
  18614. * Gets or sets the animation properties override
  18615. */
  18616. get: function () {
  18617. if (!this._animationPropertiesOverride) {
  18618. return this._scene.animationPropertiesOverride;
  18619. }
  18620. return this._animationPropertiesOverride;
  18621. },
  18622. set: function (value) {
  18623. this._animationPropertiesOverride = value;
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. /**
  18629. * Gets a string idenfifying the name of the class
  18630. * @returns "Node" string
  18631. */
  18632. Node.prototype.getClassName = function () {
  18633. return "Node";
  18634. };
  18635. Object.defineProperty(Node.prototype, "onDispose", {
  18636. /**
  18637. * Sets a callback that will be raised when the node will be disposed
  18638. */
  18639. set: function (callback) {
  18640. if (this._onDisposeObserver) {
  18641. this.onDisposeObservable.remove(this._onDisposeObserver);
  18642. }
  18643. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18644. },
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. /**
  18649. * Gets the scene of the node
  18650. * @returns a scene
  18651. */
  18652. Node.prototype.getScene = function () {
  18653. return this._scene;
  18654. };
  18655. /**
  18656. * Gets the engine of the node
  18657. * @returns a Engine
  18658. */
  18659. Node.prototype.getEngine = function () {
  18660. return this._scene.getEngine();
  18661. };
  18662. /**
  18663. * Attach a behavior to the node
  18664. * @see http://doc.babylonjs.com/features/behaviour
  18665. * @param behavior defines the behavior to attach
  18666. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18667. * @returns the current Node
  18668. */
  18669. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18670. var _this = this;
  18671. if (attachImmediately === void 0) { attachImmediately = false; }
  18672. var index = this._behaviors.indexOf(behavior);
  18673. if (index !== -1) {
  18674. return this;
  18675. }
  18676. behavior.init();
  18677. if (this._scene.isLoading && !attachImmediately) {
  18678. // We defer the attach when the scene will be loaded
  18679. this._scene.onDataLoadedObservable.addOnce(function () {
  18680. behavior.attach(_this);
  18681. });
  18682. }
  18683. else {
  18684. behavior.attach(this);
  18685. }
  18686. this._behaviors.push(behavior);
  18687. return this;
  18688. };
  18689. /**
  18690. * Remove an attached behavior
  18691. * @see http://doc.babylonjs.com/features/behaviour
  18692. * @param behavior defines the behavior to attach
  18693. * @returns the current Node
  18694. */
  18695. Node.prototype.removeBehavior = function (behavior) {
  18696. var index = this._behaviors.indexOf(behavior);
  18697. if (index === -1) {
  18698. return this;
  18699. }
  18700. this._behaviors[index].detach();
  18701. this._behaviors.splice(index, 1);
  18702. return this;
  18703. };
  18704. Object.defineProperty(Node.prototype, "behaviors", {
  18705. /**
  18706. * Gets the list of attached behaviors
  18707. * @see http://doc.babylonjs.com/features/behaviour
  18708. */
  18709. get: function () {
  18710. return this._behaviors;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. /**
  18716. * Gets an attached behavior by name
  18717. * @param name defines the name of the behavior to look for
  18718. * @see http://doc.babylonjs.com/features/behaviour
  18719. * @returns null if behavior was not found else the requested behavior
  18720. */
  18721. Node.prototype.getBehaviorByName = function (name) {
  18722. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18723. var behavior = _a[_i];
  18724. if (behavior.name === name) {
  18725. return behavior;
  18726. }
  18727. }
  18728. return null;
  18729. };
  18730. /**
  18731. * Returns the latest update of the World matrix
  18732. * @returns a Matrix
  18733. */
  18734. Node.prototype.getWorldMatrix = function () {
  18735. if (this._currentRenderId !== this._scene.getRenderId()) {
  18736. this.computeWorldMatrix();
  18737. }
  18738. return this._worldMatrix;
  18739. };
  18740. /** @hidden */
  18741. Node.prototype._getWorldMatrixDeterminant = function () {
  18742. return this._worldMatrixDeterminant;
  18743. };
  18744. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18745. /**
  18746. * Returns directly the latest state of the mesh World matrix.
  18747. * A Matrix is returned.
  18748. */
  18749. get: function () {
  18750. return this._worldMatrix;
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. // override it in derived class if you add new variables to the cache
  18756. // and call the parent class method
  18757. /** @hidden */
  18758. Node.prototype._initCache = function () {
  18759. this._cache = {};
  18760. this._cache.parent = undefined;
  18761. };
  18762. /** @hidden */
  18763. Node.prototype.updateCache = function (force) {
  18764. if (!force && this.isSynchronized()) {
  18765. return;
  18766. }
  18767. this._cache.parent = this.parent;
  18768. this._updateCache();
  18769. };
  18770. // override it in derived class if you add new variables to the cache
  18771. // and call the parent class method if !ignoreParentClass
  18772. /** @hidden */
  18773. Node.prototype._updateCache = function (ignoreParentClass) {
  18774. };
  18775. // override it in derived class if you add new variables to the cache
  18776. /** @hidden */
  18777. Node.prototype._isSynchronized = function () {
  18778. return true;
  18779. };
  18780. /** @hidden */
  18781. Node.prototype._markSyncedWithParent = function () {
  18782. if (this._parentNode) {
  18783. this._parentRenderId = this._parentNode._childRenderId;
  18784. }
  18785. };
  18786. /** @hidden */
  18787. Node.prototype.isSynchronizedWithParent = function () {
  18788. if (!this._parentNode) {
  18789. return true;
  18790. }
  18791. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18792. return false;
  18793. }
  18794. return this._parentNode.isSynchronized();
  18795. };
  18796. /** @hidden */
  18797. Node.prototype.isSynchronized = function () {
  18798. if (this._cache.parent != this._parentNode) {
  18799. this._cache.parent = this._parentNode;
  18800. return false;
  18801. }
  18802. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18803. return false;
  18804. }
  18805. return this._isSynchronized();
  18806. };
  18807. /**
  18808. * Is this node ready to be used/rendered
  18809. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18810. * @return true if the node is ready
  18811. */
  18812. Node.prototype.isReady = function (completeCheck) {
  18813. if (completeCheck === void 0) { completeCheck = false; }
  18814. return this._isReady;
  18815. };
  18816. /**
  18817. * Is this node enabled?
  18818. * 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
  18819. * @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
  18820. * @return whether this node (and its parent) is enabled
  18821. */
  18822. Node.prototype.isEnabled = function (checkAncestors) {
  18823. if (checkAncestors === void 0) { checkAncestors = true; }
  18824. if (checkAncestors === false) {
  18825. return this._isEnabled;
  18826. }
  18827. if (!this._isEnabled) {
  18828. return false;
  18829. }
  18830. return this._isParentEnabled;
  18831. };
  18832. /** @hidden */
  18833. Node.prototype._syncParentEnabledState = function () {
  18834. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18835. if (this._children) {
  18836. this._children.forEach(function (c) {
  18837. c._syncParentEnabledState(); // Force children to update accordingly
  18838. });
  18839. }
  18840. };
  18841. /**
  18842. * Set the enabled state of this node
  18843. * @param value defines the new enabled state
  18844. */
  18845. Node.prototype.setEnabled = function (value) {
  18846. this._isEnabled = value;
  18847. this._syncParentEnabledState();
  18848. };
  18849. /**
  18850. * Is this node a descendant of the given node?
  18851. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18852. * @param ancestor defines the parent node to inspect
  18853. * @returns a boolean indicating if this node is a descendant of the given node
  18854. */
  18855. Node.prototype.isDescendantOf = function (ancestor) {
  18856. if (this.parent) {
  18857. if (this.parent === ancestor) {
  18858. return true;
  18859. }
  18860. return this.parent.isDescendantOf(ancestor);
  18861. }
  18862. return false;
  18863. };
  18864. /** @hidden */
  18865. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18866. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18867. if (!this._children) {
  18868. return;
  18869. }
  18870. for (var index = 0; index < this._children.length; index++) {
  18871. var item = this._children[index];
  18872. if (!predicate || predicate(item)) {
  18873. results.push(item);
  18874. }
  18875. if (!directDescendantsOnly) {
  18876. item._getDescendants(results, false, predicate);
  18877. }
  18878. }
  18879. };
  18880. /**
  18881. * Will return all nodes that have this node as ascendant
  18882. * @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
  18883. * @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
  18884. * @return all children nodes of all types
  18885. */
  18886. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18887. var results = new Array();
  18888. this._getDescendants(results, directDescendantsOnly, predicate);
  18889. return results;
  18890. };
  18891. /**
  18892. * Get all child-meshes of this node
  18893. * @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
  18894. * @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
  18895. * @returns an array of AbstractMesh
  18896. */
  18897. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18898. var results = [];
  18899. this._getDescendants(results, directDescendantsOnly, function (node) {
  18900. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18901. });
  18902. return results;
  18903. };
  18904. /**
  18905. * Get all child-transformNodes of this node
  18906. * @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
  18907. * @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
  18908. * @returns an array of TransformNode
  18909. */
  18910. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18911. var results = [];
  18912. this._getDescendants(results, directDescendantsOnly, function (node) {
  18913. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18914. });
  18915. return results;
  18916. };
  18917. /**
  18918. * Get all direct children of this node
  18919. * @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
  18920. * @returns an array of Node
  18921. */
  18922. Node.prototype.getChildren = function (predicate) {
  18923. return this.getDescendants(true, predicate);
  18924. };
  18925. /** @hidden */
  18926. Node.prototype._setReady = function (state) {
  18927. if (state === this._isReady) {
  18928. return;
  18929. }
  18930. if (!state) {
  18931. this._isReady = false;
  18932. return;
  18933. }
  18934. if (this.onReady) {
  18935. this.onReady(this);
  18936. }
  18937. this._isReady = true;
  18938. };
  18939. /**
  18940. * Get an animation by name
  18941. * @param name defines the name of the animation to look for
  18942. * @returns null if not found else the requested animation
  18943. */
  18944. Node.prototype.getAnimationByName = function (name) {
  18945. for (var i = 0; i < this.animations.length; i++) {
  18946. var animation = this.animations[i];
  18947. if (animation.name === name) {
  18948. return animation;
  18949. }
  18950. }
  18951. return null;
  18952. };
  18953. /**
  18954. * Creates an animation range for this node
  18955. * @param name defines the name of the range
  18956. * @param from defines the starting key
  18957. * @param to defines the end key
  18958. */
  18959. Node.prototype.createAnimationRange = function (name, from, to) {
  18960. // check name not already in use
  18961. if (!this._ranges[name]) {
  18962. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18963. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18964. if (this.animations[i]) {
  18965. this.animations[i].createRange(name, from, to);
  18966. }
  18967. }
  18968. }
  18969. };
  18970. /**
  18971. * Delete a specific animation range
  18972. * @param name defines the name of the range to delete
  18973. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18974. */
  18975. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18976. if (deleteFrames === void 0) { deleteFrames = true; }
  18977. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18978. if (this.animations[i]) {
  18979. this.animations[i].deleteRange(name, deleteFrames);
  18980. }
  18981. }
  18982. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18983. };
  18984. /**
  18985. * Get an animation range by name
  18986. * @param name defines the name of the animation range to look for
  18987. * @returns null if not found else the requested animation range
  18988. */
  18989. Node.prototype.getAnimationRange = function (name) {
  18990. return this._ranges[name];
  18991. };
  18992. /**
  18993. * Will start the animation sequence
  18994. * @param name defines the range frames for animation sequence
  18995. * @param loop defines if the animation should loop (false by default)
  18996. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18997. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18998. * @returns the object created for this animation. If range does not exist, it will return null
  18999. */
  19000. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19001. var range = this.getAnimationRange(name);
  19002. if (!range) {
  19003. return null;
  19004. }
  19005. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19006. };
  19007. /**
  19008. * Serialize animation ranges into a JSON compatible object
  19009. * @returns serialization object
  19010. */
  19011. Node.prototype.serializeAnimationRanges = function () {
  19012. var serializationRanges = [];
  19013. for (var name in this._ranges) {
  19014. var localRange = this._ranges[name];
  19015. if (!localRange) {
  19016. continue;
  19017. }
  19018. var range = {};
  19019. range.name = name;
  19020. range.from = localRange.from;
  19021. range.to = localRange.to;
  19022. serializationRanges.push(range);
  19023. }
  19024. return serializationRanges;
  19025. };
  19026. /**
  19027. * Computes the world matrix of the node
  19028. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19029. * @returns the world matrix
  19030. */
  19031. Node.prototype.computeWorldMatrix = function (force) {
  19032. if (!this._worldMatrix) {
  19033. this._worldMatrix = BABYLON.Matrix.Identity();
  19034. }
  19035. return this._worldMatrix;
  19036. };
  19037. /**
  19038. * Releases resources associated with this node.
  19039. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19040. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19041. */
  19042. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19043. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19044. if (!doNotRecurse) {
  19045. var nodes = this.getDescendants(true);
  19046. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19047. var node = nodes_1[_i];
  19048. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19049. }
  19050. }
  19051. else {
  19052. var transformNodes = this.getChildTransformNodes(true);
  19053. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19054. var transformNode = transformNodes_1[_a];
  19055. transformNode.parent = null;
  19056. transformNode.computeWorldMatrix(true);
  19057. }
  19058. }
  19059. if (!this.parent) {
  19060. this.removeFromSceneRootNodes();
  19061. }
  19062. else {
  19063. this.parent = null;
  19064. }
  19065. // Callback
  19066. this.onDisposeObservable.notifyObservers(this);
  19067. this.onDisposeObservable.clear();
  19068. // Behaviors
  19069. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19070. var behavior = _c[_b];
  19071. behavior.detach();
  19072. }
  19073. this._behaviors = [];
  19074. this._isDisposed = true;
  19075. };
  19076. /**
  19077. * Parse animation range data from a serialization object and store them into a given node
  19078. * @param node defines where to store the animation ranges
  19079. * @param parsedNode defines the serialization object to read data from
  19080. * @param scene defines the hosting scene
  19081. */
  19082. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19083. if (parsedNode.ranges) {
  19084. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19085. var data = parsedNode.ranges[index];
  19086. node.createAnimationRange(data.name, data.from, data.to);
  19087. }
  19088. }
  19089. };
  19090. Node._NodeConstructors = {};
  19091. __decorate([
  19092. BABYLON.serialize()
  19093. ], Node.prototype, "name", void 0);
  19094. __decorate([
  19095. BABYLON.serialize()
  19096. ], Node.prototype, "id", void 0);
  19097. __decorate([
  19098. BABYLON.serialize()
  19099. ], Node.prototype, "uniqueId", void 0);
  19100. __decorate([
  19101. BABYLON.serialize()
  19102. ], Node.prototype, "state", void 0);
  19103. __decorate([
  19104. BABYLON.serialize()
  19105. ], Node.prototype, "metadata", void 0);
  19106. return Node;
  19107. }());
  19108. BABYLON.Node = Node;
  19109. })(BABYLON || (BABYLON = {}));
  19110. //# sourceMappingURL=babylon.node.js.map
  19111. var BABYLON;
  19112. (function (BABYLON) {
  19113. // This matrix is used as a value to reset the bounding box.
  19114. var _identityMatrix = BABYLON.Matrix.Identity();
  19115. /**
  19116. * Class used to store bounding sphere information
  19117. */
  19118. var BoundingSphere = /** @class */ (function () {
  19119. /**
  19120. * Creates a new bounding sphere
  19121. * @param min defines the minimum vector (in local space)
  19122. * @param max defines the maximum vector (in local space)
  19123. * @param worldMatrix defines the new world matrix
  19124. */
  19125. function BoundingSphere(min, max, worldMatrix) {
  19126. /**
  19127. * Gets the center of the bounding sphere in local space
  19128. */
  19129. this.center = BABYLON.Vector3.Zero();
  19130. /**
  19131. * Gets the center of the bounding sphere in world space
  19132. */
  19133. this.centerWorld = BABYLON.Vector3.Zero();
  19134. /**
  19135. * Gets the minimum vector in local space
  19136. */
  19137. this.minimum = BABYLON.Vector3.Zero();
  19138. /**
  19139. * Gets the maximum vector in local space
  19140. */
  19141. this.maximum = BABYLON.Vector3.Zero();
  19142. this.reConstruct(min, max, worldMatrix);
  19143. }
  19144. /**
  19145. * Recreates the entire bounding sphere from scratch
  19146. * @param min defines the new minimum vector (in local space)
  19147. * @param max defines the new maximum vector (in local space)
  19148. * @param worldMatrix defines the new world matrix
  19149. */
  19150. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19151. this.minimum.copyFrom(min);
  19152. this.maximum.copyFrom(max);
  19153. var distance = BABYLON.Vector3.Distance(min, max);
  19154. max.addToRef(min, this.center).scaleInPlace(0.5);
  19155. this.radius = distance * 0.5;
  19156. this._update(worldMatrix || _identityMatrix);
  19157. };
  19158. /**
  19159. * Scale the current bounding sphere by applying a scale factor
  19160. * @param factor defines the scale factor to apply
  19161. * @returns the current bounding box
  19162. */
  19163. BoundingSphere.prototype.scale = function (factor) {
  19164. var newRadius = this.radius * factor;
  19165. var tmpVectors = BoundingSphere.TmpVector3;
  19166. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19167. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19168. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19169. this.reConstruct(min, max);
  19170. return this;
  19171. };
  19172. // Methods
  19173. /** @hidden */
  19174. BoundingSphere.prototype._update = function (world) {
  19175. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19176. var tempVector = BoundingSphere.TmpVector3[0];
  19177. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19178. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19179. };
  19180. /**
  19181. * Tests if the bounding sphere is intersecting the frustum planes
  19182. * @param frustumPlanes defines the frustum planes to test
  19183. * @returns true if there is an intersection
  19184. */
  19185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19186. for (var i = 0; i < 6; i++) {
  19187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19188. return false;
  19189. }
  19190. }
  19191. return true;
  19192. };
  19193. /**
  19194. * Tests if a point is inside the bounding sphere
  19195. * @param point defines the point to test
  19196. * @returns true if the point is inside the bounding sphere
  19197. */
  19198. BoundingSphere.prototype.intersectsPoint = function (point) {
  19199. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19200. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19201. return false;
  19202. }
  19203. return true;
  19204. };
  19205. // Statics
  19206. /**
  19207. * Checks if two sphere intersct
  19208. * @param sphere0 sphere 0
  19209. * @param sphere1 sphere 1
  19210. * @returns true if the speres intersect
  19211. */
  19212. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19213. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19214. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19215. if (radiusSum * radiusSum < squareDistance) {
  19216. return false;
  19217. }
  19218. return true;
  19219. };
  19220. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19221. return BoundingSphere;
  19222. }());
  19223. BABYLON.BoundingSphere = BoundingSphere;
  19224. })(BABYLON || (BABYLON = {}));
  19225. //# sourceMappingURL=babylon.boundingSphere.js.map
  19226. var BABYLON;
  19227. (function (BABYLON) {
  19228. /**
  19229. * Class used to store bounding box information
  19230. */
  19231. var BoundingBox = /** @class */ (function () {
  19232. /**
  19233. * Creates a new bounding box
  19234. * @param min defines the minimum vector (in local space)
  19235. * @param max defines the maximum vector (in local space)
  19236. * @param worldMatrix defines the new world matrix
  19237. */
  19238. function BoundingBox(min, max, worldMatrix) {
  19239. /**
  19240. * Gets the 8 vectors representing the bounding box in local space
  19241. */
  19242. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19243. /**
  19244. * Gets the center of the bounding box in local space
  19245. */
  19246. this.center = BABYLON.Vector3.Zero();
  19247. /**
  19248. * Gets the center of the bounding box in world space
  19249. */
  19250. this.centerWorld = BABYLON.Vector3.Zero();
  19251. /**
  19252. * Gets the extend size in local space
  19253. */
  19254. this.extendSize = BABYLON.Vector3.Zero();
  19255. /**
  19256. * Gets the extend size in world space
  19257. */
  19258. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19259. /**
  19260. * Gets the OBB (object bounding box) directions
  19261. */
  19262. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19263. /**
  19264. * Gets the 8 vectors representing the bounding box in world space
  19265. */
  19266. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19267. /**
  19268. * Gets the minimum vector in world space
  19269. */
  19270. this.minimumWorld = BABYLON.Vector3.Zero();
  19271. /**
  19272. * Gets the maximum vector in world space
  19273. */
  19274. this.maximumWorld = BABYLON.Vector3.Zero();
  19275. /**
  19276. * Gets the minimum vector in local space
  19277. */
  19278. this.minimum = BABYLON.Vector3.Zero();
  19279. /**
  19280. * Gets the maximum vector in local space
  19281. */
  19282. this.maximum = BABYLON.Vector3.Zero();
  19283. this.reConstruct(min, max, worldMatrix);
  19284. }
  19285. // Methods
  19286. /**
  19287. * Recreates the entire bounding box from scratch
  19288. * @param min defines the new minimum vector (in local space)
  19289. * @param max defines the new maximum vector (in local space)
  19290. * @param worldMatrix defines the new world matrix
  19291. */
  19292. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19293. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19294. var vectors = this.vectors;
  19295. this.minimum.copyFromFloats(minX, minY, minZ);
  19296. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19297. vectors[0].copyFromFloats(minX, minY, minZ);
  19298. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19299. vectors[2].copyFromFloats(maxX, minY, minZ);
  19300. vectors[3].copyFromFloats(minX, maxY, minZ);
  19301. vectors[4].copyFromFloats(minX, minY, maxZ);
  19302. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19303. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19304. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19305. // OBB
  19306. max.addToRef(min, this.center).scaleInPlace(0.5);
  19307. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19308. this._update(worldMatrix || this._worldMatrix || BABYLON.Matrix.Identity());
  19309. };
  19310. /**
  19311. * Scale the current bounding box by applying a scale factor
  19312. * @param factor defines the scale factor to apply
  19313. * @returns the current bounding box
  19314. */
  19315. BoundingBox.prototype.scale = function (factor) {
  19316. var tmpVectors = BoundingBox.TmpVector3;
  19317. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19318. var len = diff.length();
  19319. diff.normalizeFromLength(len);
  19320. var distance = len * factor;
  19321. var newRadius = diff.scaleInPlace(distance * 0.5);
  19322. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19323. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19324. this.reConstruct(min, max);
  19325. return this;
  19326. };
  19327. /**
  19328. * Gets the world matrix of the bounding box
  19329. * @returns a matrix
  19330. */
  19331. BoundingBox.prototype.getWorldMatrix = function () {
  19332. return this._worldMatrix;
  19333. };
  19334. /**
  19335. * Sets the world matrix stored in the bounding box
  19336. * @param matrix defines the matrix to store
  19337. * @returns current bounding box
  19338. */
  19339. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19340. this._worldMatrix.copyFrom(matrix);
  19341. return this;
  19342. };
  19343. /** @hidden */
  19344. BoundingBox.prototype._update = function (world) {
  19345. var minWorld = this.minimumWorld;
  19346. var maxWorld = this.maximumWorld;
  19347. var directions = this.directions;
  19348. minWorld.setAll(Number.MAX_VALUE);
  19349. maxWorld.setAll(-Number.MAX_VALUE);
  19350. var vectorsWorld = this.vectorsWorld;
  19351. var vectors = this.vectors;
  19352. for (var index = 0; index < 8; ++index) {
  19353. var v = vectorsWorld[index];
  19354. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19355. minWorld.minimizeInPlace(v);
  19356. maxWorld.maximizeInPlace(v);
  19357. }
  19358. // Extend
  19359. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19360. // OOBB
  19361. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19362. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19363. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19364. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19365. this._worldMatrix = world;
  19366. };
  19367. /**
  19368. * Tests if the bounding box is intersecting the frustum planes
  19369. * @param frustumPlanes defines the frustum planes to test
  19370. * @returns true if there is an intersection
  19371. */
  19372. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19373. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19374. };
  19375. /**
  19376. * Tests if the bounding box is entirely inside the frustum planes
  19377. * @param frustumPlanes defines the frustum planes to test
  19378. * @returns true if there is an inclusion
  19379. */
  19380. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19381. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19382. };
  19383. /**
  19384. * Tests if a point is inside the bounding box
  19385. * @param point defines the point to test
  19386. * @returns true if the point is inside the bounding box
  19387. */
  19388. BoundingBox.prototype.intersectsPoint = function (point) {
  19389. var min = this.minimumWorld;
  19390. var max = this.maximumWorld;
  19391. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19392. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19393. var delta = -BABYLON.Epsilon;
  19394. if (maxX - pointX < delta || delta > pointX - minX) {
  19395. return false;
  19396. }
  19397. if (maxY - pointY < delta || delta > pointY - minY) {
  19398. return false;
  19399. }
  19400. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19401. return false;
  19402. }
  19403. return true;
  19404. };
  19405. /**
  19406. * Tests if the bounding box intersects with a bounding sphere
  19407. * @param sphere defines the sphere to test
  19408. * @returns true if there is an intersection
  19409. */
  19410. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19411. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19412. };
  19413. /**
  19414. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19415. * @param min defines the min vector to use
  19416. * @param max defines the max vector to use
  19417. * @returns true if there is an intersection
  19418. */
  19419. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19420. var myMin = this.minimumWorld;
  19421. var myMax = this.maximumWorld;
  19422. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19423. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19424. if (myMaxX < minX || myMinX > maxX) {
  19425. return false;
  19426. }
  19427. if (myMaxY < minY || myMinY > maxY) {
  19428. return false;
  19429. }
  19430. if (myMaxZ < minZ || myMinZ > maxZ) {
  19431. return false;
  19432. }
  19433. return true;
  19434. };
  19435. // Statics
  19436. /**
  19437. * Tests if two bounding boxes are intersections
  19438. * @param box0 defines the first box to test
  19439. * @param box1 defines the second box to test
  19440. * @returns true if there is an intersection
  19441. */
  19442. BoundingBox.Intersects = function (box0, box1) {
  19443. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19444. };
  19445. /**
  19446. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19447. * @param minPoint defines the minimum vector of the bounding box
  19448. * @param maxPoint defines the maximum vector of the bounding box
  19449. * @param sphereCenter defines the sphere center
  19450. * @param sphereRadius defines the sphere radius
  19451. * @returns true if there is an intersection
  19452. */
  19453. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19454. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19455. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19456. return (num <= (sphereRadius * sphereRadius));
  19457. };
  19458. /**
  19459. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19460. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19461. * @param frustumPlanes defines the frustum planes to test
  19462. * @return true if there is an inclusion
  19463. */
  19464. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19465. for (var p = 0; p < 6; ++p) {
  19466. var frustumPlane = frustumPlanes[p];
  19467. for (var i = 0; i < 8; ++i) {
  19468. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19469. return false;
  19470. }
  19471. }
  19472. }
  19473. return true;
  19474. };
  19475. /**
  19476. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19477. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19478. * @param frustumPlanes defines the frustum planes to test
  19479. * @return true if there is an intersection
  19480. */
  19481. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19482. for (var p = 0; p < 6; ++p) {
  19483. var canReturnFalse = true;
  19484. var frustumPlane = frustumPlanes[p];
  19485. for (var i = 0; i < 8; ++i) {
  19486. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19487. canReturnFalse = false;
  19488. break;
  19489. }
  19490. }
  19491. if (canReturnFalse) {
  19492. return false;
  19493. }
  19494. }
  19495. return true;
  19496. };
  19497. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19498. return BoundingBox;
  19499. }());
  19500. BABYLON.BoundingBox = BoundingBox;
  19501. })(BABYLON || (BABYLON = {}));
  19502. //# sourceMappingURL=babylon.boundingBox.js.map
  19503. var BABYLON;
  19504. (function (BABYLON) {
  19505. var computeBoxExtents = function (axis, box) {
  19506. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19507. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19508. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19509. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19510. var r = r0 + r1 + r2;
  19511. return {
  19512. min: p - r,
  19513. max: p + r
  19514. };
  19515. };
  19516. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19517. var axisOverlap = function (axis, box0, box1) {
  19518. var result0 = computeBoxExtents(axis, box0);
  19519. var result1 = computeBoxExtents(axis, box1);
  19520. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19521. };
  19522. /**
  19523. * Info for a bounding data of a mesh
  19524. */
  19525. var BoundingInfo = /** @class */ (function () {
  19526. /**
  19527. * Constructs bounding info
  19528. * @param minimum min vector of the bounding box/sphere
  19529. * @param maximum max vector of the bounding box/sphere
  19530. * @param worldMatrix defines the new world matrix
  19531. */
  19532. function BoundingInfo(minimum, maximum, worldMatrix) {
  19533. this._isLocked = false;
  19534. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19535. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19536. }
  19537. /**
  19538. * Recreates the entire bounding info from scratch
  19539. * @param min defines the new minimum vector (in local space)
  19540. * @param max defines the new maximum vector (in local space)
  19541. * @param worldMatrix defines the new world matrix
  19542. */
  19543. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19544. this.boundingBox.reConstruct(min, max, worldMatrix);
  19545. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19546. };
  19547. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19548. /**
  19549. * min vector of the bounding box/sphere
  19550. */
  19551. get: function () {
  19552. return this.boundingBox.minimum;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19558. /**
  19559. * max vector of the bounding box/sphere
  19560. */
  19561. get: function () {
  19562. return this.boundingBox.maximum;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19568. /**
  19569. * If the info is locked and won't be updated to avoid perf overhead
  19570. */
  19571. get: function () {
  19572. return this._isLocked;
  19573. },
  19574. set: function (value) {
  19575. this._isLocked = value;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. // Methods
  19581. /**
  19582. * Updates the boudning sphere and box
  19583. * @param world world matrix to be used to update
  19584. */
  19585. BoundingInfo.prototype.update = function (world) {
  19586. if (this._isLocked) {
  19587. return;
  19588. }
  19589. this.boundingBox._update(world);
  19590. this.boundingSphere._update(world);
  19591. };
  19592. /**
  19593. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19594. * @param center New center of the bounding info
  19595. * @param extend New extend of the bounding info
  19596. * @returns the current bounding info
  19597. */
  19598. BoundingInfo.prototype.centerOn = function (center, extend) {
  19599. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19600. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19601. this.boundingBox.reConstruct(minimum, maximum);
  19602. this.boundingSphere.reConstruct(minimum, maximum);
  19603. return this;
  19604. };
  19605. /**
  19606. * Scale the current bounding info by applying a scale factor
  19607. * @param factor defines the scale factor to apply
  19608. * @returns the current bounding info
  19609. */
  19610. BoundingInfo.prototype.scale = function (factor) {
  19611. this.boundingBox.scale(factor);
  19612. this.boundingSphere.scale(factor);
  19613. return this;
  19614. };
  19615. /**
  19616. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19617. * @param frustumPlanes defines the frustum to test
  19618. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19619. * @returns true if the bounding info is in the frustum planes
  19620. */
  19621. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19622. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19623. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19624. return false;
  19625. }
  19626. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19627. return true;
  19628. }
  19629. return this.boundingBox.isInFrustum(frustumPlanes);
  19630. };
  19631. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19632. /**
  19633. * Gets the world distance between the min and max points of the bounding box
  19634. */
  19635. get: function () {
  19636. var boundingBox = this.boundingBox;
  19637. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19638. return size.length();
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. /**
  19644. * Checks if a cullable object (mesh...) is in the camera frustum
  19645. * Unlike isInFrustum this cheks the full bounding box
  19646. * @param frustumPlanes Camera near/planes
  19647. * @returns true if the object is in frustum otherwise false
  19648. */
  19649. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19650. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19651. };
  19652. /** @hidden */
  19653. BoundingInfo.prototype._checkCollision = function (collider) {
  19654. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19655. };
  19656. /**
  19657. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19658. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19659. * @param point the point to check intersection with
  19660. * @returns if the point intersects
  19661. */
  19662. BoundingInfo.prototype.intersectsPoint = function (point) {
  19663. if (!this.boundingSphere.centerWorld) {
  19664. return false;
  19665. }
  19666. if (!this.boundingSphere.intersectsPoint(point)) {
  19667. return false;
  19668. }
  19669. if (!this.boundingBox.intersectsPoint(point)) {
  19670. return false;
  19671. }
  19672. return true;
  19673. };
  19674. /**
  19675. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19676. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19677. * @param boundingInfo the bounding info to check intersection with
  19678. * @param precise if the intersection should be done using OBB
  19679. * @returns if the bounding info intersects
  19680. */
  19681. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19682. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19683. return false;
  19684. }
  19685. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19686. return false;
  19687. }
  19688. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19689. return false;
  19690. }
  19691. if (!precise) {
  19692. return true;
  19693. }
  19694. var box0 = this.boundingBox;
  19695. var box1 = boundingInfo.boundingBox;
  19696. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19697. return false;
  19698. }
  19699. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19700. return false;
  19701. }
  19702. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19703. return false;
  19704. }
  19705. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19706. return false;
  19707. }
  19708. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19709. return false;
  19710. }
  19711. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19712. return false;
  19713. }
  19714. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19715. return false;
  19716. }
  19717. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19718. return false;
  19719. }
  19720. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19721. return false;
  19722. }
  19723. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19724. return false;
  19725. }
  19726. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19727. return false;
  19728. }
  19729. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19730. return false;
  19731. }
  19732. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19733. return false;
  19734. }
  19735. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19736. return false;
  19737. }
  19738. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19739. return false;
  19740. }
  19741. return true;
  19742. };
  19743. return BoundingInfo;
  19744. }());
  19745. BABYLON.BoundingInfo = BoundingInfo;
  19746. })(BABYLON || (BABYLON = {}));
  19747. //# sourceMappingURL=babylon.boundingInfo.js.map
  19748. var BABYLON;
  19749. (function (BABYLON) {
  19750. /**
  19751. * 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.
  19752. * @see https://doc.babylonjs.com/how_to/transformnode
  19753. */
  19754. var TransformNode = /** @class */ (function (_super) {
  19755. __extends(TransformNode, _super);
  19756. function TransformNode(name, scene, isPure) {
  19757. if (scene === void 0) { scene = null; }
  19758. if (isPure === void 0) { isPure = true; }
  19759. var _this = _super.call(this, name, scene) || this;
  19760. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19761. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19762. _this._up = new BABYLON.Vector3(0, 1, 0);
  19763. _this._right = new BABYLON.Vector3(1, 0, 0);
  19764. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19765. // Properties
  19766. _this._position = BABYLON.Vector3.Zero();
  19767. _this._rotation = BABYLON.Vector3.Zero();
  19768. _this._scaling = BABYLON.Vector3.One();
  19769. _this._isDirty = false;
  19770. /**
  19771. * Set the billboard mode. Default is 0.
  19772. *
  19773. * | Value | Type | Description |
  19774. * | --- | --- | --- |
  19775. * | 0 | BILLBOARDMODE_NONE | |
  19776. * | 1 | BILLBOARDMODE_X | |
  19777. * | 2 | BILLBOARDMODE_Y | |
  19778. * | 4 | BILLBOARDMODE_Z | |
  19779. * | 7 | BILLBOARDMODE_ALL | |
  19780. *
  19781. */
  19782. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19783. /**
  19784. * 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
  19785. */
  19786. _this.scalingDeterminant = 1;
  19787. /**
  19788. * Sets the distance of the object to max, often used by skybox
  19789. */
  19790. _this.infiniteDistance = false;
  19791. /**
  19792. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19793. * By default the system will update normals to compensate
  19794. */
  19795. _this.ignoreNonUniformScaling = false;
  19796. _this._localWorld = BABYLON.Matrix.Zero();
  19797. _this._absolutePosition = BABYLON.Vector3.Zero();
  19798. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19799. _this._postMultiplyPivotMatrix = false;
  19800. _this._isWorldMatrixFrozen = false;
  19801. /** @hidden */
  19802. _this._indexInSceneTransformNodesArray = -1;
  19803. /**
  19804. * An event triggered after the world matrix is updated
  19805. */
  19806. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19807. _this._nonUniformScaling = false;
  19808. if (isPure) {
  19809. _this.getScene().addTransformNode(_this);
  19810. }
  19811. return _this;
  19812. }
  19813. /**
  19814. * Gets a string identifying the name of the class
  19815. * @returns "TransformNode" string
  19816. */
  19817. TransformNode.prototype.getClassName = function () {
  19818. return "TransformNode";
  19819. };
  19820. Object.defineProperty(TransformNode.prototype, "position", {
  19821. /**
  19822. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19823. */
  19824. get: function () {
  19825. return this._position;
  19826. },
  19827. set: function (newPosition) {
  19828. this._position = newPosition;
  19829. this._isDirty = true;
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(TransformNode.prototype, "rotation", {
  19835. /**
  19836. * 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)).
  19837. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19838. */
  19839. get: function () {
  19840. return this._rotation;
  19841. },
  19842. set: function (newRotation) {
  19843. this._rotation = newRotation;
  19844. this._isDirty = true;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(TransformNode.prototype, "scaling", {
  19850. /**
  19851. * 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)).
  19852. */
  19853. get: function () {
  19854. return this._scaling;
  19855. },
  19856. set: function (newScaling) {
  19857. this._scaling = newScaling;
  19858. this._isDirty = true;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19864. /**
  19865. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19866. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19867. */
  19868. get: function () {
  19869. return this._rotationQuaternion;
  19870. },
  19871. set: function (quaternion) {
  19872. this._rotationQuaternion = quaternion;
  19873. //reset the rotation vector.
  19874. if (quaternion) {
  19875. this.rotation.setAll(0.0);
  19876. }
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(TransformNode.prototype, "forward", {
  19882. /**
  19883. * The forward direction of that transform in world space.
  19884. */
  19885. get: function () {
  19886. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(TransformNode.prototype, "up", {
  19892. /**
  19893. * The up direction of that transform in world space.
  19894. */
  19895. get: function () {
  19896. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Object.defineProperty(TransformNode.prototype, "right", {
  19902. /**
  19903. * The right direction of that transform in world space.
  19904. */
  19905. get: function () {
  19906. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. /**
  19912. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19913. * @param matrix the matrix to copy the pose from
  19914. * @returns this TransformNode.
  19915. */
  19916. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19917. this._poseMatrix.copyFrom(matrix);
  19918. return this;
  19919. };
  19920. /**
  19921. * Returns the mesh Pose matrix.
  19922. * @returns the pose matrix
  19923. */
  19924. TransformNode.prototype.getPoseMatrix = function () {
  19925. return this._poseMatrix;
  19926. };
  19927. /** @hidden */
  19928. TransformNode.prototype._isSynchronized = function () {
  19929. if (this._isDirty) {
  19930. return false;
  19931. }
  19932. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19933. return false;
  19934. }
  19935. if (this._cache.pivotMatrixUpdated) {
  19936. return false;
  19937. }
  19938. if (this.infiniteDistance) {
  19939. return false;
  19940. }
  19941. if (!this._cache.position.equals(this._position)) {
  19942. return false;
  19943. }
  19944. if (this._rotationQuaternion) {
  19945. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19946. return false;
  19947. }
  19948. }
  19949. if (!this._cache.rotation.equals(this._rotation)) {
  19950. return false;
  19951. }
  19952. if (!this._cache.scaling.equals(this._scaling)) {
  19953. return false;
  19954. }
  19955. return true;
  19956. };
  19957. /** @hidden */
  19958. TransformNode.prototype._initCache = function () {
  19959. _super.prototype._initCache.call(this);
  19960. this._cache.localMatrixUpdated = false;
  19961. this._cache.position = BABYLON.Vector3.Zero();
  19962. this._cache.scaling = BABYLON.Vector3.Zero();
  19963. this._cache.rotation = BABYLON.Vector3.Zero();
  19964. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19965. this._cache.billboardMode = -1;
  19966. };
  19967. /**
  19968. * Flag the transform node as dirty (Forcing it to update everything)
  19969. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19970. * @returns this transform node
  19971. */
  19972. TransformNode.prototype.markAsDirty = function (property) {
  19973. if (property === "rotation") {
  19974. this.rotationQuaternion = null;
  19975. }
  19976. this._currentRenderId = Number.MAX_VALUE;
  19977. this._isDirty = true;
  19978. return this;
  19979. };
  19980. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19981. /**
  19982. * Returns the current mesh absolute position.
  19983. * Returns a Vector3.
  19984. */
  19985. get: function () {
  19986. return this._absolutePosition;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. /**
  19992. * Sets a new matrix to apply before all other transformation
  19993. * @param matrix defines the transform matrix
  19994. * @returns the current TransformNode
  19995. */
  19996. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19997. return this.setPivotMatrix(matrix, false);
  19998. };
  19999. /**
  20000. * Sets a new pivot matrix to the current node
  20001. * @param matrix defines the new pivot matrix to use
  20002. * @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
  20003. * @returns the current TransformNode
  20004. */
  20005. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20006. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20007. this._pivotMatrix.copyFrom(matrix);
  20008. this._cache.pivotMatrixUpdated = true;
  20009. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20010. if (this._postMultiplyPivotMatrix) {
  20011. if (!this._pivotMatrixInverse) {
  20012. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20013. }
  20014. else {
  20015. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20016. }
  20017. }
  20018. return this;
  20019. };
  20020. /**
  20021. * Returns the mesh pivot matrix.
  20022. * Default : Identity.
  20023. * @returns the matrix
  20024. */
  20025. TransformNode.prototype.getPivotMatrix = function () {
  20026. return this._pivotMatrix;
  20027. };
  20028. /**
  20029. * Prevents the World matrix to be computed any longer.
  20030. * @returns the TransformNode.
  20031. */
  20032. TransformNode.prototype.freezeWorldMatrix = function () {
  20033. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20034. this.computeWorldMatrix(true);
  20035. this._isWorldMatrixFrozen = true;
  20036. return this;
  20037. };
  20038. /**
  20039. * Allows back the World matrix computation.
  20040. * @returns the TransformNode.
  20041. */
  20042. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20043. this._isWorldMatrixFrozen = false;
  20044. this.computeWorldMatrix(true);
  20045. return this;
  20046. };
  20047. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20048. /**
  20049. * True if the World matrix has been frozen.
  20050. */
  20051. get: function () {
  20052. return this._isWorldMatrixFrozen;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. /**
  20058. * Retuns the mesh absolute position in the World.
  20059. * @returns a Vector3.
  20060. */
  20061. TransformNode.prototype.getAbsolutePosition = function () {
  20062. this.computeWorldMatrix();
  20063. return this._absolutePosition;
  20064. };
  20065. /**
  20066. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20067. * @param absolutePosition the absolute position to set
  20068. * @returns the TransformNode.
  20069. */
  20070. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20071. if (!absolutePosition) {
  20072. return this;
  20073. }
  20074. var absolutePositionX;
  20075. var absolutePositionY;
  20076. var absolutePositionZ;
  20077. if (absolutePosition.x === undefined) {
  20078. if (arguments.length < 3) {
  20079. return this;
  20080. }
  20081. absolutePositionX = arguments[0];
  20082. absolutePositionY = arguments[1];
  20083. absolutePositionZ = arguments[2];
  20084. }
  20085. else {
  20086. absolutePositionX = absolutePosition.x;
  20087. absolutePositionY = absolutePosition.y;
  20088. absolutePositionZ = absolutePosition.z;
  20089. }
  20090. if (this.parent) {
  20091. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20092. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20093. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20094. }
  20095. else {
  20096. this.position.x = absolutePositionX;
  20097. this.position.y = absolutePositionY;
  20098. this.position.z = absolutePositionZ;
  20099. }
  20100. return this;
  20101. };
  20102. /**
  20103. * Sets the mesh position in its local space.
  20104. * @param vector3 the position to set in localspace
  20105. * @returns the TransformNode.
  20106. */
  20107. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20108. this.computeWorldMatrix();
  20109. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20110. return this;
  20111. };
  20112. /**
  20113. * Returns the mesh position in the local space from the current World matrix values.
  20114. * @returns a new Vector3.
  20115. */
  20116. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20117. this.computeWorldMatrix();
  20118. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20119. this._localWorld.invertToRef(invLocalWorldMatrix);
  20120. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20121. };
  20122. /**
  20123. * Translates the mesh along the passed Vector3 in its local space.
  20124. * @param vector3 the distance to translate in localspace
  20125. * @returns the TransformNode.
  20126. */
  20127. TransformNode.prototype.locallyTranslate = function (vector3) {
  20128. this.computeWorldMatrix(true);
  20129. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20130. return this;
  20131. };
  20132. /**
  20133. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20134. * @param targetPoint the position (must be in same space as current mesh) to look at
  20135. * @param yawCor optional yaw (y-axis) correction in radians
  20136. * @param pitchCor optional pitch (x-axis) correction in radians
  20137. * @param rollCor optional roll (z-axis) correction in radians
  20138. * @param space the choosen space of the target
  20139. * @returns the TransformNode.
  20140. */
  20141. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20142. if (yawCor === void 0) { yawCor = 0; }
  20143. if (pitchCor === void 0) { pitchCor = 0; }
  20144. if (rollCor === void 0) { rollCor = 0; }
  20145. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20146. var dv = TransformNode._lookAtVectorCache;
  20147. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20148. targetPoint.subtractToRef(pos, dv);
  20149. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20150. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20151. var pitch = Math.atan2(dv.y, len);
  20152. if (this.rotationQuaternion) {
  20153. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20154. }
  20155. else {
  20156. this.rotation.x = pitch + pitchCor;
  20157. this.rotation.y = yaw + yawCor;
  20158. this.rotation.z = rollCor;
  20159. }
  20160. return this;
  20161. };
  20162. /**
  20163. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20164. * This Vector3 is expressed in the World space.
  20165. * @param localAxis axis to rotate
  20166. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20167. */
  20168. TransformNode.prototype.getDirection = function (localAxis) {
  20169. var result = BABYLON.Vector3.Zero();
  20170. this.getDirectionToRef(localAxis, result);
  20171. return result;
  20172. };
  20173. /**
  20174. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20175. * localAxis is expressed in the mesh local space.
  20176. * result is computed in the Wordl space from the mesh World matrix.
  20177. * @param localAxis axis to rotate
  20178. * @param result the resulting transformnode
  20179. * @returns this TransformNode.
  20180. */
  20181. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20182. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20183. return this;
  20184. };
  20185. /**
  20186. * Sets a new pivot point to the current node
  20187. * @param point defines the new pivot point to use
  20188. * @param space defines if the point is in world or local space (local by default)
  20189. * @returns the current TransformNode
  20190. */
  20191. TransformNode.prototype.setPivotPoint = function (point, space) {
  20192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20193. if (this.getScene().getRenderId() == 0) {
  20194. this.computeWorldMatrix(true);
  20195. }
  20196. var wm = this.getWorldMatrix();
  20197. if (space == BABYLON.Space.WORLD) {
  20198. var tmat = BABYLON.Tmp.Matrix[0];
  20199. wm.invertToRef(tmat);
  20200. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20201. }
  20202. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20203. };
  20204. /**
  20205. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20206. * @returns the pivot point
  20207. */
  20208. TransformNode.prototype.getPivotPoint = function () {
  20209. var point = BABYLON.Vector3.Zero();
  20210. this.getPivotPointToRef(point);
  20211. return point;
  20212. };
  20213. /**
  20214. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20215. * @param result the vector3 to store the result
  20216. * @returns this TransformNode.
  20217. */
  20218. TransformNode.prototype.getPivotPointToRef = function (result) {
  20219. result.x = -this._pivotMatrix.m[12];
  20220. result.y = -this._pivotMatrix.m[13];
  20221. result.z = -this._pivotMatrix.m[14];
  20222. return this;
  20223. };
  20224. /**
  20225. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20226. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20227. */
  20228. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20229. var point = BABYLON.Vector3.Zero();
  20230. this.getAbsolutePivotPointToRef(point);
  20231. return point;
  20232. };
  20233. /**
  20234. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20235. * @param result vector3 to store the result
  20236. * @returns this TransformNode.
  20237. */
  20238. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20239. result.x = this._pivotMatrix.m[12];
  20240. result.y = this._pivotMatrix.m[13];
  20241. result.z = this._pivotMatrix.m[14];
  20242. this.getPivotPointToRef(result);
  20243. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20244. return this;
  20245. };
  20246. /**
  20247. * Defines the passed node as the parent of the current node.
  20248. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20249. * @param node the node ot set as the parent
  20250. * @returns this TransformNode.
  20251. */
  20252. TransformNode.prototype.setParent = function (node) {
  20253. if (!node && !this.parent) {
  20254. return this;
  20255. }
  20256. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20257. var position = BABYLON.Tmp.Vector3[0];
  20258. var scale = BABYLON.Tmp.Vector3[1];
  20259. if (!node) {
  20260. if (this.parent && this.parent.computeWorldMatrix) {
  20261. this.parent.computeWorldMatrix(true);
  20262. }
  20263. this.computeWorldMatrix(true);
  20264. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20265. }
  20266. else {
  20267. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20268. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20269. this.computeWorldMatrix(true);
  20270. node.computeWorldMatrix(true);
  20271. node.getWorldMatrix().invertToRef(invParentMatrix);
  20272. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20273. diffMatrix.decompose(scale, quatRotation, position);
  20274. }
  20275. if (this.rotationQuaternion) {
  20276. this.rotationQuaternion.copyFrom(quatRotation);
  20277. }
  20278. else {
  20279. quatRotation.toEulerAnglesToRef(this.rotation);
  20280. }
  20281. this.scaling.copyFrom(scale);
  20282. this.position.copyFrom(position);
  20283. this.parent = node;
  20284. return this;
  20285. };
  20286. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20287. /**
  20288. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20289. */
  20290. get: function () {
  20291. return this._nonUniformScaling;
  20292. },
  20293. enumerable: true,
  20294. configurable: true
  20295. });
  20296. /** @hidden */
  20297. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20298. if (this._nonUniformScaling === value) {
  20299. return false;
  20300. }
  20301. this._nonUniformScaling = value;
  20302. return true;
  20303. };
  20304. /**
  20305. * Attach the current TransformNode to another TransformNode associated with a bone
  20306. * @param bone Bone affecting the TransformNode
  20307. * @param affectedTransformNode TransformNode associated with the bone
  20308. * @returns this object
  20309. */
  20310. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20311. this._transformToBoneReferal = affectedTransformNode;
  20312. this.parent = bone;
  20313. if (bone.getWorldMatrix().determinant() < 0) {
  20314. this.scalingDeterminant *= -1;
  20315. }
  20316. return this;
  20317. };
  20318. /**
  20319. * Detach the transform node if its associated with a bone
  20320. * @returns this object
  20321. */
  20322. TransformNode.prototype.detachFromBone = function () {
  20323. if (!this.parent) {
  20324. return this;
  20325. }
  20326. if (this.parent.getWorldMatrix().determinant() < 0) {
  20327. this.scalingDeterminant *= -1;
  20328. }
  20329. this._transformToBoneReferal = null;
  20330. this.parent = null;
  20331. return this;
  20332. };
  20333. /**
  20334. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20335. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20336. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20337. * The passed axis is also normalized.
  20338. * @param axis the axis to rotate around
  20339. * @param amount the amount to rotate in radians
  20340. * @param space Space to rotate in (Default: local)
  20341. * @returns the TransformNode.
  20342. */
  20343. TransformNode.prototype.rotate = function (axis, amount, space) {
  20344. axis.normalize();
  20345. if (!this.rotationQuaternion) {
  20346. this.rotationQuaternion = this.rotation.toQuaternion();
  20347. this.rotation.setAll(0);
  20348. }
  20349. var rotationQuaternion;
  20350. if (!space || space === BABYLON.Space.LOCAL) {
  20351. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20352. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20353. }
  20354. else {
  20355. if (this.parent) {
  20356. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20357. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20358. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20359. }
  20360. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20361. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20362. }
  20363. return this;
  20364. };
  20365. /**
  20366. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20367. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20368. * The passed axis is also normalized. .
  20369. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20370. * @param point the point to rotate around
  20371. * @param axis the axis to rotate around
  20372. * @param amount the amount to rotate in radians
  20373. * @returns the TransformNode
  20374. */
  20375. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20376. axis.normalize();
  20377. if (!this.rotationQuaternion) {
  20378. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20379. this.rotation.setAll(0);
  20380. }
  20381. var tmpVector = BABYLON.Tmp.Vector3[0];
  20382. var finalScale = BABYLON.Tmp.Vector3[1];
  20383. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20384. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20385. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20386. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20387. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20388. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20389. point.subtractToRef(this.position, tmpVector);
  20390. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20391. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20392. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20393. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20394. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20395. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20396. this.position.addInPlace(finalTranslation);
  20397. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20398. return this;
  20399. };
  20400. /**
  20401. * Translates the mesh along the axis vector for the passed distance in the given space.
  20402. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20403. * @param axis the axis to translate in
  20404. * @param distance the distance to translate
  20405. * @param space Space to rotate in (Default: local)
  20406. * @returns the TransformNode.
  20407. */
  20408. TransformNode.prototype.translate = function (axis, distance, space) {
  20409. var displacementVector = axis.scale(distance);
  20410. if (!space || space === BABYLON.Space.LOCAL) {
  20411. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20412. this.setPositionWithLocalVector(tempV3);
  20413. }
  20414. else {
  20415. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20416. }
  20417. return this;
  20418. };
  20419. /**
  20420. * Adds a rotation step to the mesh current rotation.
  20421. * x, y, z are Euler angles expressed in radians.
  20422. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20423. * This means this rotation is made in the mesh local space only.
  20424. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20425. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20426. * ```javascript
  20427. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20428. * ```
  20429. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20430. * 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.
  20431. * @param x Rotation to add
  20432. * @param y Rotation to add
  20433. * @param z Rotation to add
  20434. * @returns the TransformNode.
  20435. */
  20436. TransformNode.prototype.addRotation = function (x, y, z) {
  20437. var rotationQuaternion;
  20438. if (this.rotationQuaternion) {
  20439. rotationQuaternion = this.rotationQuaternion;
  20440. }
  20441. else {
  20442. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20443. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20444. }
  20445. var accumulation = BABYLON.Tmp.Quaternion[0];
  20446. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20447. rotationQuaternion.multiplyInPlace(accumulation);
  20448. if (!this.rotationQuaternion) {
  20449. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20450. }
  20451. return this;
  20452. };
  20453. /**
  20454. * Computes the world matrix of the node
  20455. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20456. * @returns the world matrix
  20457. */
  20458. TransformNode.prototype.computeWorldMatrix = function (force) {
  20459. if (this._isWorldMatrixFrozen) {
  20460. return this._worldMatrix;
  20461. }
  20462. if (!force && this.isSynchronized()) {
  20463. this._currentRenderId = this.getScene().getRenderId();
  20464. return this._worldMatrix;
  20465. }
  20466. this._updateCache();
  20467. this._cache.position.copyFrom(this.position);
  20468. this._cache.scaling.copyFrom(this.scaling);
  20469. this._cache.pivotMatrixUpdated = false;
  20470. this._cache.billboardMode = this.billboardMode;
  20471. this._currentRenderId = this.getScene().getRenderId();
  20472. this._childRenderId = this.getScene().getRenderId();
  20473. this._isDirty = false;
  20474. // Scaling
  20475. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20476. // Rotation
  20477. //rotate, if quaternion is set and rotation was used
  20478. if (this.rotationQuaternion) {
  20479. var len = this.rotation.length();
  20480. if (len) {
  20481. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20482. this.rotation.copyFromFloats(0, 0, 0);
  20483. }
  20484. }
  20485. if (this.rotationQuaternion) {
  20486. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20487. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20488. }
  20489. else {
  20490. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20491. this._cache.rotation.copyFrom(this.rotation);
  20492. }
  20493. // Translation
  20494. var camera = this.getScene().activeCamera;
  20495. if (this.infiniteDistance && !this.parent && camera) {
  20496. var cameraWorldMatrix = camera.getWorldMatrix();
  20497. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20498. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20499. }
  20500. else {
  20501. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20502. }
  20503. // Composing transformations
  20504. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20505. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20506. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20507. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20508. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20509. // Need to decompose each rotation here
  20510. var currentPosition = BABYLON.Tmp.Vector3[3];
  20511. if (this.parent && this.parent.getWorldMatrix) {
  20512. if (this._transformToBoneReferal) {
  20513. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20514. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20515. }
  20516. else {
  20517. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20518. }
  20519. }
  20520. else {
  20521. currentPosition.copyFrom(this.position);
  20522. }
  20523. currentPosition.subtractInPlace(camera.globalPosition);
  20524. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20525. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20526. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20527. }
  20528. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20529. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20530. }
  20531. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20532. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20533. }
  20534. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20535. }
  20536. else {
  20537. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20538. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20539. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20540. }
  20541. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20542. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20543. }
  20544. // Post multiply inverse of pivotMatrix
  20545. if (this._postMultiplyPivotMatrix) {
  20546. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20547. }
  20548. // Local world
  20549. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20550. // Parent
  20551. if (this.parent && this.parent.getWorldMatrix) {
  20552. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20553. if (this._transformToBoneReferal) {
  20554. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20555. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20556. }
  20557. else {
  20558. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20559. }
  20560. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20561. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20562. this._worldMatrix.copyFrom(this._localWorld);
  20563. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20564. }
  20565. else {
  20566. if (this._transformToBoneReferal) {
  20567. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20568. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20569. }
  20570. else {
  20571. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20572. }
  20573. }
  20574. this._markSyncedWithParent();
  20575. }
  20576. else {
  20577. this._worldMatrix.copyFrom(this._localWorld);
  20578. }
  20579. // Normal matrix
  20580. if (!this.ignoreNonUniformScaling) {
  20581. if (this.scaling.isNonUniform) {
  20582. this._updateNonUniformScalingState(true);
  20583. }
  20584. else if (this.parent && this.parent._nonUniformScaling) {
  20585. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20586. }
  20587. else {
  20588. this._updateNonUniformScalingState(false);
  20589. }
  20590. }
  20591. else {
  20592. this._updateNonUniformScalingState(false);
  20593. }
  20594. this._afterComputeWorldMatrix();
  20595. // Absolute position
  20596. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20597. // Callbacks
  20598. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20599. if (!this._poseMatrix) {
  20600. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20601. }
  20602. // Cache the determinant
  20603. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20604. return this._worldMatrix;
  20605. };
  20606. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20607. };
  20608. /**
  20609. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20610. * @param func callback function to add
  20611. *
  20612. * @returns the TransformNode.
  20613. */
  20614. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20615. this.onAfterWorldMatrixUpdateObservable.add(func);
  20616. return this;
  20617. };
  20618. /**
  20619. * Removes a registered callback function.
  20620. * @param func callback function to remove
  20621. * @returns the TransformNode.
  20622. */
  20623. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20624. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20625. return this;
  20626. };
  20627. /**
  20628. * Clone the current transform node
  20629. * @param name Name of the new clone
  20630. * @param newParent New parent for the clone
  20631. * @param doNotCloneChildren Do not clone children hierarchy
  20632. * @returns the new transform node
  20633. */
  20634. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20635. var _this = this;
  20636. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20637. result.name = name;
  20638. result.id = name;
  20639. if (newParent) {
  20640. result.parent = newParent;
  20641. }
  20642. if (!doNotCloneChildren) {
  20643. // Children
  20644. var directDescendants = this.getDescendants(true);
  20645. for (var index = 0; index < directDescendants.length; index++) {
  20646. var child = directDescendants[index];
  20647. if (child.clone) {
  20648. child.clone(name + "." + child.name, result);
  20649. }
  20650. }
  20651. }
  20652. return result;
  20653. };
  20654. /**
  20655. * Serializes the objects information.
  20656. * @param currentSerializationObject defines the object to serialize in
  20657. * @returns the serialized object
  20658. */
  20659. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20660. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20661. serializationObject.type = this.getClassName();
  20662. // Parent
  20663. if (this.parent) {
  20664. serializationObject.parentId = this.parent.id;
  20665. }
  20666. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20667. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20668. }
  20669. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20670. serializationObject.isEnabled = this.isEnabled();
  20671. // Parent
  20672. if (this.parent) {
  20673. serializationObject.parentId = this.parent.id;
  20674. }
  20675. return serializationObject;
  20676. };
  20677. // Statics
  20678. /**
  20679. * Returns a new TransformNode object parsed from the source provided.
  20680. * @param parsedTransformNode is the source.
  20681. * @param scene the scne the object belongs to
  20682. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20683. * @returns a new TransformNode object parsed from the source provided.
  20684. */
  20685. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20686. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20687. if (BABYLON.Tags) {
  20688. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20689. }
  20690. if (parsedTransformNode.localMatrix) {
  20691. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20692. }
  20693. else if (parsedTransformNode.pivotMatrix) {
  20694. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20695. }
  20696. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20697. // Parent
  20698. if (parsedTransformNode.parentId) {
  20699. transformNode._waitingParentId = parsedTransformNode.parentId;
  20700. }
  20701. return transformNode;
  20702. };
  20703. /**
  20704. * Releases resources associated with this transform node.
  20705. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20706. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20707. */
  20708. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20709. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20710. // Animations
  20711. this.getScene().stopAnimation(this);
  20712. // Remove from scene
  20713. this.getScene().removeTransformNode(this);
  20714. this.onAfterWorldMatrixUpdateObservable.clear();
  20715. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20716. };
  20717. // Statics
  20718. /**
  20719. * Object will not rotate to face the camera
  20720. */
  20721. TransformNode.BILLBOARDMODE_NONE = 0;
  20722. /**
  20723. * Object will rotate to face the camera but only on the x axis
  20724. */
  20725. TransformNode.BILLBOARDMODE_X = 1;
  20726. /**
  20727. * Object will rotate to face the camera but only on the y axis
  20728. */
  20729. TransformNode.BILLBOARDMODE_Y = 2;
  20730. /**
  20731. * Object will rotate to face the camera but only on the z axis
  20732. */
  20733. TransformNode.BILLBOARDMODE_Z = 4;
  20734. /**
  20735. * Object will rotate to face the camera
  20736. */
  20737. TransformNode.BILLBOARDMODE_ALL = 7;
  20738. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20739. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20740. __decorate([
  20741. BABYLON.serializeAsVector3("position")
  20742. ], TransformNode.prototype, "_position", void 0);
  20743. __decorate([
  20744. BABYLON.serializeAsVector3("rotation")
  20745. ], TransformNode.prototype, "_rotation", void 0);
  20746. __decorate([
  20747. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20748. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20749. __decorate([
  20750. BABYLON.serializeAsVector3("scaling")
  20751. ], TransformNode.prototype, "_scaling", void 0);
  20752. __decorate([
  20753. BABYLON.serialize()
  20754. ], TransformNode.prototype, "billboardMode", void 0);
  20755. __decorate([
  20756. BABYLON.serialize()
  20757. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20758. __decorate([
  20759. BABYLON.serialize()
  20760. ], TransformNode.prototype, "infiniteDistance", void 0);
  20761. __decorate([
  20762. BABYLON.serialize()
  20763. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20764. return TransformNode;
  20765. }(BABYLON.Node));
  20766. BABYLON.TransformNode = TransformNode;
  20767. })(BABYLON || (BABYLON = {}));
  20768. //# sourceMappingURL=babylon.transformNode.js.map
  20769. var BABYLON;
  20770. (function (BABYLON) {
  20771. /** @hidden */
  20772. var _FacetDataStorage = /** @class */ (function () {
  20773. function _FacetDataStorage() {
  20774. this.facetNb = 0; // facet number
  20775. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20776. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20777. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20778. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20779. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20780. this.subDiv = {
  20781. max: 1,
  20782. X: 1,
  20783. Y: 1,
  20784. Z: 1
  20785. };
  20786. this.facetDepthSort = false; // is the facet depth sort to be computed
  20787. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20788. }
  20789. return _FacetDataStorage;
  20790. }());
  20791. /**
  20792. * Class used to store all common mesh properties
  20793. */
  20794. var AbstractMesh = /** @class */ (function (_super) {
  20795. __extends(AbstractMesh, _super);
  20796. // Constructor
  20797. /**
  20798. * Creates a new AbstractMesh
  20799. * @param name defines the name of the mesh
  20800. * @param scene defines the hosting scene
  20801. */
  20802. function AbstractMesh(name, scene) {
  20803. if (scene === void 0) { scene = null; }
  20804. var _this = _super.call(this, name, scene, false) || this;
  20805. _this._facetData = new _FacetDataStorage();
  20806. /** Gets ot sets the culling strategy to use to find visible meshes */
  20807. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20808. // Events
  20809. /**
  20810. * An event triggered when this mesh collides with another one
  20811. */
  20812. _this.onCollideObservable = new BABYLON.Observable();
  20813. /**
  20814. * An event triggered when the collision's position changes
  20815. */
  20816. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20817. /**
  20818. * An event triggered when material is changed
  20819. */
  20820. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20821. // Properties
  20822. /**
  20823. * Gets or sets the orientation for POV movement & rotation
  20824. */
  20825. _this.definedFacingForward = true;
  20826. _this._visibility = 1.0;
  20827. /** Gets or sets the alpha index used to sort transparent meshes
  20828. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20829. */
  20830. _this.alphaIndex = Number.MAX_VALUE;
  20831. /**
  20832. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20833. */
  20834. _this.isVisible = true;
  20835. /**
  20836. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20837. */
  20838. _this.isPickable = true;
  20839. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20840. _this.showSubMeshesBoundingBox = false;
  20841. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20842. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20843. */
  20844. _this.isBlocker = false;
  20845. /**
  20846. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20847. */
  20848. _this.enablePointerMoveEvents = false;
  20849. /**
  20850. * Specifies the rendering group id for this mesh (0 by default)
  20851. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20852. */
  20853. _this.renderingGroupId = 0;
  20854. _this._receiveShadows = false;
  20855. /** Defines color to use when rendering outline */
  20856. _this.outlineColor = BABYLON.Color3.Red();
  20857. /** Define width to use when rendering outline */
  20858. _this.outlineWidth = 0.02;
  20859. /** Defines color to use when rendering overlay */
  20860. _this.overlayColor = BABYLON.Color3.Red();
  20861. /** Defines alpha to use when rendering overlay */
  20862. _this.overlayAlpha = 0.5;
  20863. _this._hasVertexAlpha = false;
  20864. _this._useVertexColors = true;
  20865. _this._computeBonesUsingShaders = true;
  20866. _this._numBoneInfluencers = 4;
  20867. _this._applyFog = true;
  20868. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20869. _this.useOctreeForRenderingSelection = true;
  20870. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20871. _this.useOctreeForPicking = true;
  20872. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20873. _this.useOctreeForCollisions = true;
  20874. _this._layerMask = 0x0FFFFFFF;
  20875. /**
  20876. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20877. */
  20878. _this.alwaysSelectAsActiveMesh = false;
  20879. /**
  20880. * Gets or sets the current action manager
  20881. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20882. */
  20883. _this.actionManager = null;
  20884. // Collisions
  20885. _this._checkCollisions = false;
  20886. _this._collisionMask = -1;
  20887. _this._collisionGroup = -1;
  20888. /**
  20889. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20890. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20891. */
  20892. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20893. /**
  20894. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20895. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20896. */
  20897. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20898. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20899. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20900. // Edges
  20901. /**
  20902. * Defines edge width used when edgesRenderer is enabled
  20903. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20904. */
  20905. _this.edgesWidth = 1;
  20906. /**
  20907. * Defines edge color used when edgesRenderer is enabled
  20908. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20909. */
  20910. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20911. /** @hidden */
  20912. _this._renderId = 0;
  20913. /** @hidden */
  20914. _this._intersectionsInProgress = new Array();
  20915. /** @hidden */
  20916. _this._unIndexed = false;
  20917. /** @hidden */
  20918. _this._lightSources = new Array();
  20919. /**
  20920. * An event triggered when the mesh is rebuilt.
  20921. */
  20922. _this.onRebuildObservable = new BABYLON.Observable();
  20923. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20924. if (collidedMesh === void 0) { collidedMesh = null; }
  20925. //TODO move this to the collision coordinator!
  20926. if (_this.getScene().workerCollisions) {
  20927. newPosition.multiplyInPlace(_this._collider._radius);
  20928. }
  20929. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20930. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20931. _this.position.addInPlace(_this._diffPositionForCollisions);
  20932. }
  20933. if (collidedMesh) {
  20934. _this.onCollideObservable.notifyObservers(collidedMesh);
  20935. }
  20936. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20937. };
  20938. _this.getScene().addMesh(_this);
  20939. _this._resyncLightSources();
  20940. return _this;
  20941. }
  20942. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20943. /**
  20944. * No billboard
  20945. */
  20946. get: function () {
  20947. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20948. },
  20949. enumerable: true,
  20950. configurable: true
  20951. });
  20952. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20953. /** Billboard on X axis */
  20954. get: function () {
  20955. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20956. },
  20957. enumerable: true,
  20958. configurable: true
  20959. });
  20960. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20961. /** Billboard on Y axis */
  20962. get: function () {
  20963. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20964. },
  20965. enumerable: true,
  20966. configurable: true
  20967. });
  20968. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20969. /** Billboard on Z axis */
  20970. get: function () {
  20971. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20972. },
  20973. enumerable: true,
  20974. configurable: true
  20975. });
  20976. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20977. /** Billboard on all axes */
  20978. get: function () {
  20979. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20980. },
  20981. enumerable: true,
  20982. configurable: true
  20983. });
  20984. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20985. /**
  20986. * Gets the number of facets in the mesh
  20987. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20988. */
  20989. get: function () {
  20990. return this._facetData.facetNb;
  20991. },
  20992. enumerable: true,
  20993. configurable: true
  20994. });
  20995. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20996. /**
  20997. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20999. */
  21000. get: function () {
  21001. return this._facetData.partitioningSubdivisions;
  21002. },
  21003. set: function (nb) {
  21004. this._facetData.partitioningSubdivisions = nb;
  21005. },
  21006. enumerable: true,
  21007. configurable: true
  21008. });
  21009. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21010. /**
  21011. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21012. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21013. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21014. */
  21015. get: function () {
  21016. return this._facetData.partitioningBBoxRatio;
  21017. },
  21018. set: function (ratio) {
  21019. this._facetData.partitioningBBoxRatio = ratio;
  21020. },
  21021. enumerable: true,
  21022. configurable: true
  21023. });
  21024. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21025. /**
  21026. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21027. * Works only for updatable meshes.
  21028. * Doesn't work with multi-materials
  21029. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21030. */
  21031. get: function () {
  21032. return this._facetData.facetDepthSort;
  21033. },
  21034. set: function (sort) {
  21035. this._facetData.facetDepthSort = sort;
  21036. },
  21037. enumerable: true,
  21038. configurable: true
  21039. });
  21040. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21041. /**
  21042. * The location (Vector3) where the facet depth sort must be computed from.
  21043. * By default, the active camera position.
  21044. * Used only when facet depth sort is enabled
  21045. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21046. */
  21047. get: function () {
  21048. return this._facetData.facetDepthSortFrom;
  21049. },
  21050. set: function (location) {
  21051. this._facetData.facetDepthSortFrom = location;
  21052. },
  21053. enumerable: true,
  21054. configurable: true
  21055. });
  21056. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21057. /**
  21058. * gets a boolean indicating if facetData is enabled
  21059. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21060. */
  21061. get: function () {
  21062. return this._facetData.facetDataEnabled;
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. /** @hidden */
  21068. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21069. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21070. return false;
  21071. }
  21072. this._markSubMeshesAsMiscDirty();
  21073. return true;
  21074. };
  21075. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21076. /** Set a function to call when this mesh collides with another one */
  21077. set: function (callback) {
  21078. if (this._onCollideObserver) {
  21079. this.onCollideObservable.remove(this._onCollideObserver);
  21080. }
  21081. this._onCollideObserver = this.onCollideObservable.add(callback);
  21082. },
  21083. enumerable: true,
  21084. configurable: true
  21085. });
  21086. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21087. /** Set a function to call when the collision's position changes */
  21088. set: function (callback) {
  21089. if (this._onCollisionPositionChangeObserver) {
  21090. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21091. }
  21092. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21093. },
  21094. enumerable: true,
  21095. configurable: true
  21096. });
  21097. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21098. /**
  21099. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21100. */
  21101. get: function () {
  21102. return this._visibility;
  21103. },
  21104. /**
  21105. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21106. */
  21107. set: function (value) {
  21108. if (this._visibility === value) {
  21109. return;
  21110. }
  21111. this._visibility = value;
  21112. this._markSubMeshesAsMiscDirty();
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. Object.defineProperty(AbstractMesh.prototype, "material", {
  21118. /** Gets or sets current material */
  21119. get: function () {
  21120. return this._material;
  21121. },
  21122. set: function (value) {
  21123. if (this._material === value) {
  21124. return;
  21125. }
  21126. // remove from material mesh map id needed
  21127. if (this._material && this._material.meshMap) {
  21128. this._material.meshMap[this.uniqueId] = undefined;
  21129. }
  21130. this._material = value;
  21131. if (value && value.meshMap) {
  21132. value.meshMap[this.uniqueId] = this;
  21133. }
  21134. if (this.onMaterialChangedObservable.hasObservers) {
  21135. this.onMaterialChangedObservable.notifyObservers(this);
  21136. }
  21137. if (!this.subMeshes) {
  21138. return;
  21139. }
  21140. this._unBindEffect();
  21141. },
  21142. enumerable: true,
  21143. configurable: true
  21144. });
  21145. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21146. /**
  21147. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21148. * @see http://doc.babylonjs.com/babylon101/shadows
  21149. */
  21150. get: function () {
  21151. return this._receiveShadows;
  21152. },
  21153. set: function (value) {
  21154. if (this._receiveShadows === value) {
  21155. return;
  21156. }
  21157. this._receiveShadows = value;
  21158. this._markSubMeshesAsLightDirty();
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21164. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21165. get: function () {
  21166. return this._hasVertexAlpha;
  21167. },
  21168. set: function (value) {
  21169. if (this._hasVertexAlpha === value) {
  21170. return;
  21171. }
  21172. this._hasVertexAlpha = value;
  21173. this._markSubMeshesAsAttributesDirty();
  21174. this._markSubMeshesAsMiscDirty();
  21175. },
  21176. enumerable: true,
  21177. configurable: true
  21178. });
  21179. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21180. /** 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) */
  21181. get: function () {
  21182. return this._useVertexColors;
  21183. },
  21184. set: function (value) {
  21185. if (this._useVertexColors === value) {
  21186. return;
  21187. }
  21188. this._useVertexColors = value;
  21189. this._markSubMeshesAsAttributesDirty();
  21190. },
  21191. enumerable: true,
  21192. configurable: true
  21193. });
  21194. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21195. /**
  21196. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21197. */
  21198. get: function () {
  21199. return this._computeBonesUsingShaders;
  21200. },
  21201. set: function (value) {
  21202. if (this._computeBonesUsingShaders === value) {
  21203. return;
  21204. }
  21205. this._computeBonesUsingShaders = value;
  21206. this._markSubMeshesAsAttributesDirty();
  21207. },
  21208. enumerable: true,
  21209. configurable: true
  21210. });
  21211. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21212. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21213. get: function () {
  21214. return this._numBoneInfluencers;
  21215. },
  21216. set: function (value) {
  21217. if (this._numBoneInfluencers === value) {
  21218. return;
  21219. }
  21220. this._numBoneInfluencers = value;
  21221. this._markSubMeshesAsAttributesDirty();
  21222. },
  21223. enumerable: true,
  21224. configurable: true
  21225. });
  21226. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21227. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21228. get: function () {
  21229. return this._applyFog;
  21230. },
  21231. set: function (value) {
  21232. if (this._applyFog === value) {
  21233. return;
  21234. }
  21235. this._applyFog = value;
  21236. this._markSubMeshesAsMiscDirty();
  21237. },
  21238. enumerable: true,
  21239. configurable: true
  21240. });
  21241. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21242. /**
  21243. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21244. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21245. */
  21246. get: function () {
  21247. return this._layerMask;
  21248. },
  21249. set: function (value) {
  21250. if (value === this._layerMask) {
  21251. return;
  21252. }
  21253. this._layerMask = value;
  21254. this._resyncLightSources();
  21255. },
  21256. enumerable: true,
  21257. configurable: true
  21258. });
  21259. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21260. /**
  21261. * Gets or sets a collision mask used to mask collisions (default is -1).
  21262. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21263. */
  21264. get: function () {
  21265. return this._collisionMask;
  21266. },
  21267. set: function (mask) {
  21268. this._collisionMask = !isNaN(mask) ? mask : -1;
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21274. /**
  21275. * Gets or sets the current collision group mask (-1 by default).
  21276. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21277. */
  21278. get: function () {
  21279. return this._collisionGroup;
  21280. },
  21281. set: function (mask) {
  21282. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21283. },
  21284. enumerable: true,
  21285. configurable: true
  21286. });
  21287. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21288. /** @hidden */
  21289. get: function () {
  21290. return null;
  21291. },
  21292. enumerable: true,
  21293. configurable: true
  21294. });
  21295. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21296. get: function () {
  21297. return this._skeleton;
  21298. },
  21299. /**
  21300. * Gets or sets a skeleton to apply skining transformations
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21302. */
  21303. set: function (value) {
  21304. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21305. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21306. }
  21307. if (value && value.needInitialSkinMatrix) {
  21308. value._registerMeshWithPoseMatrix(this);
  21309. }
  21310. this._skeleton = value;
  21311. if (!this._skeleton) {
  21312. this._bonesTransformMatrices = null;
  21313. }
  21314. this._markSubMeshesAsAttributesDirty();
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. /**
  21320. * Returns the string "AbstractMesh"
  21321. * @returns "AbstractMesh"
  21322. */
  21323. AbstractMesh.prototype.getClassName = function () {
  21324. return "AbstractMesh";
  21325. };
  21326. /**
  21327. * Gets a string representation of the current mesh
  21328. * @param fullDetails defines a boolean indicating if full details must be included
  21329. * @returns a string representation of the current mesh
  21330. */
  21331. AbstractMesh.prototype.toString = function (fullDetails) {
  21332. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21333. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21334. if (this._skeleton) {
  21335. ret += ", skeleton: " + this._skeleton.name;
  21336. }
  21337. if (fullDetails) {
  21338. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21339. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21340. }
  21341. return ret;
  21342. };
  21343. /** @hidden */
  21344. AbstractMesh.prototype._rebuild = function () {
  21345. this.onRebuildObservable.notifyObservers(this);
  21346. if (this._occlusionQuery) {
  21347. this._occlusionQuery = null;
  21348. }
  21349. if (!this.subMeshes) {
  21350. return;
  21351. }
  21352. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21353. var subMesh = _a[_i];
  21354. subMesh._rebuild();
  21355. }
  21356. };
  21357. /** @hidden */
  21358. AbstractMesh.prototype._resyncLightSources = function () {
  21359. this._lightSources.length = 0;
  21360. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21361. var light = _a[_i];
  21362. if (!light.isEnabled()) {
  21363. continue;
  21364. }
  21365. if (light.canAffectMesh(this)) {
  21366. this._lightSources.push(light);
  21367. }
  21368. }
  21369. this._markSubMeshesAsLightDirty();
  21370. };
  21371. /** @hidden */
  21372. AbstractMesh.prototype._resyncLighSource = function (light) {
  21373. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21374. var index = this._lightSources.indexOf(light);
  21375. if (index === -1) {
  21376. if (!isIn) {
  21377. return;
  21378. }
  21379. this._lightSources.push(light);
  21380. }
  21381. else {
  21382. if (isIn) {
  21383. return;
  21384. }
  21385. this._lightSources.splice(index, 1);
  21386. }
  21387. this._markSubMeshesAsLightDirty();
  21388. };
  21389. /** @hidden */
  21390. AbstractMesh.prototype._unBindEffect = function () {
  21391. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21392. var subMesh = _a[_i];
  21393. subMesh.setEffect(null);
  21394. }
  21395. };
  21396. /** @hidden */
  21397. AbstractMesh.prototype._removeLightSource = function (light) {
  21398. var index = this._lightSources.indexOf(light);
  21399. if (index === -1) {
  21400. return;
  21401. }
  21402. this._lightSources.splice(index, 1);
  21403. this._markSubMeshesAsLightDirty();
  21404. };
  21405. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21406. if (!this.subMeshes) {
  21407. return;
  21408. }
  21409. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21410. var subMesh = _a[_i];
  21411. if (subMesh._materialDefines) {
  21412. func(subMesh._materialDefines);
  21413. }
  21414. }
  21415. };
  21416. /** @hidden */
  21417. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21418. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21419. };
  21420. /** @hidden */
  21421. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21422. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21423. };
  21424. /** @hidden */
  21425. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21426. if (!this.subMeshes) {
  21427. return;
  21428. }
  21429. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21430. var subMesh = _a[_i];
  21431. var material = subMesh.getMaterial();
  21432. if (material) {
  21433. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21434. }
  21435. }
  21436. };
  21437. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21438. /**
  21439. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21440. */
  21441. get: function () {
  21442. return this._scaling;
  21443. },
  21444. set: function (newScaling) {
  21445. this._scaling = newScaling;
  21446. if (this.physicsImpostor) {
  21447. this.physicsImpostor.forceUpdate();
  21448. }
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21454. // Methods
  21455. /**
  21456. * Returns true if the mesh is blocked. Implemented by child classes
  21457. */
  21458. get: function () {
  21459. return false;
  21460. },
  21461. enumerable: true,
  21462. configurable: true
  21463. });
  21464. /**
  21465. * Returns the mesh itself by default. Implemented by child classes
  21466. * @param camera defines the camera to use to pick the right LOD level
  21467. * @returns the currentAbstractMesh
  21468. */
  21469. AbstractMesh.prototype.getLOD = function (camera) {
  21470. return this;
  21471. };
  21472. /**
  21473. * Returns 0 by default. Implemented by child classes
  21474. * @returns an integer
  21475. */
  21476. AbstractMesh.prototype.getTotalVertices = function () {
  21477. return 0;
  21478. };
  21479. /**
  21480. * Returns null by default. Implemented by child classes
  21481. * @returns null
  21482. */
  21483. AbstractMesh.prototype.getIndices = function () {
  21484. return null;
  21485. };
  21486. /**
  21487. * Returns the array of the requested vertex data kind. Implemented by child classes
  21488. * @param kind defines the vertex data kind to use
  21489. * @returns null
  21490. */
  21491. AbstractMesh.prototype.getVerticesData = function (kind) {
  21492. return null;
  21493. };
  21494. /**
  21495. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21496. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21497. * Note that a new underlying VertexBuffer object is created each call.
  21498. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21499. * @param kind defines vertex data kind:
  21500. * * BABYLON.VertexBuffer.PositionKind
  21501. * * BABYLON.VertexBuffer.UVKind
  21502. * * BABYLON.VertexBuffer.UV2Kind
  21503. * * BABYLON.VertexBuffer.UV3Kind
  21504. * * BABYLON.VertexBuffer.UV4Kind
  21505. * * BABYLON.VertexBuffer.UV5Kind
  21506. * * BABYLON.VertexBuffer.UV6Kind
  21507. * * BABYLON.VertexBuffer.ColorKind
  21508. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21509. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21510. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21511. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21512. * @param data defines the data source
  21513. * @param updatable defines if the data must be flagged as updatable (or static)
  21514. * @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
  21515. * @returns the current mesh
  21516. */
  21517. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21518. return this;
  21519. };
  21520. /**
  21521. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21522. * If the mesh has no geometry, it is simply returned as it is.
  21523. * @param kind defines vertex data kind:
  21524. * * BABYLON.VertexBuffer.PositionKind
  21525. * * BABYLON.VertexBuffer.UVKind
  21526. * * BABYLON.VertexBuffer.UV2Kind
  21527. * * BABYLON.VertexBuffer.UV3Kind
  21528. * * BABYLON.VertexBuffer.UV4Kind
  21529. * * BABYLON.VertexBuffer.UV5Kind
  21530. * * BABYLON.VertexBuffer.UV6Kind
  21531. * * BABYLON.VertexBuffer.ColorKind
  21532. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21533. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21534. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21535. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21536. * @param data defines the data source
  21537. * @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
  21538. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21539. * @returns the current mesh
  21540. */
  21541. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21542. return this;
  21543. };
  21544. /**
  21545. * Sets the mesh indices,
  21546. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21547. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21548. * @param totalVertices Defines the total number of vertices
  21549. * @returns the current mesh
  21550. */
  21551. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21552. return this;
  21553. };
  21554. /**
  21555. * Gets a boolean indicating if specific vertex data is present
  21556. * @param kind defines the vertex data kind to use
  21557. * @returns true is data kind is present
  21558. */
  21559. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21560. return false;
  21561. };
  21562. /**
  21563. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21564. * @returns a BoundingInfo
  21565. */
  21566. AbstractMesh.prototype.getBoundingInfo = function () {
  21567. if (this._masterMesh) {
  21568. return this._masterMesh.getBoundingInfo();
  21569. }
  21570. if (!this._boundingInfo) {
  21571. // this._boundingInfo is being created here
  21572. this._updateBoundingInfo();
  21573. }
  21574. // cannot be null.
  21575. return this._boundingInfo;
  21576. };
  21577. /**
  21578. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21579. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21580. * @returns the current mesh
  21581. */
  21582. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21583. if (includeDescendants === void 0) { includeDescendants = true; }
  21584. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21585. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21586. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21587. if (maxDimension === 0) {
  21588. return this;
  21589. }
  21590. var scale = 1 / maxDimension;
  21591. this.scaling.scaleInPlace(scale);
  21592. return this;
  21593. };
  21594. /**
  21595. * Overwrite the current bounding info
  21596. * @param boundingInfo defines the new bounding info
  21597. * @returns the current mesh
  21598. */
  21599. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21600. this._boundingInfo = boundingInfo;
  21601. return this;
  21602. };
  21603. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21604. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21605. get: function () {
  21606. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. /** @hidden */
  21612. AbstractMesh.prototype._preActivate = function () {
  21613. };
  21614. /** @hidden */
  21615. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21616. };
  21617. /** @hidden */
  21618. AbstractMesh.prototype._activate = function (renderId) {
  21619. this._renderId = renderId;
  21620. };
  21621. /**
  21622. * Gets the current world matrix
  21623. * @returns a Matrix
  21624. */
  21625. AbstractMesh.prototype.getWorldMatrix = function () {
  21626. if (this._masterMesh) {
  21627. return this._masterMesh.getWorldMatrix();
  21628. }
  21629. return _super.prototype.getWorldMatrix.call(this);
  21630. };
  21631. /** @hidden */
  21632. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21633. if (this._masterMesh) {
  21634. return this._masterMesh._getWorldMatrixDeterminant();
  21635. }
  21636. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21637. };
  21638. // ================================== Point of View Movement =================================
  21639. /**
  21640. * Perform relative position change from the point of view of behind the front of the mesh.
  21641. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21642. * Supports definition of mesh facing forward or backward
  21643. * @param amountRight defines the distance on the right axis
  21644. * @param amountUp defines the distance on the up axis
  21645. * @param amountForward defines the distance on the forward axis
  21646. * @returns the current mesh
  21647. */
  21648. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21649. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21650. return this;
  21651. };
  21652. /**
  21653. * Calculate relative position change from the point of view of behind the front of the mesh.
  21654. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21655. * Supports definition of mesh facing forward or backward
  21656. * @param amountRight defines the distance on the right axis
  21657. * @param amountUp defines the distance on the up axis
  21658. * @param amountForward defines the distance on the forward axis
  21659. * @returns the new displacement vector
  21660. */
  21661. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21662. var rotMatrix = new BABYLON.Matrix();
  21663. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21664. rotQuaternion.toRotationMatrix(rotMatrix);
  21665. var translationDelta = BABYLON.Vector3.Zero();
  21666. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21667. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21668. return translationDelta;
  21669. };
  21670. // ================================== Point of View Rotation =================================
  21671. /**
  21672. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21673. * Supports definition of mesh facing forward or backward
  21674. * @param flipBack defines the flip
  21675. * @param twirlClockwise defines the twirl
  21676. * @param tiltRight defines the tilt
  21677. * @returns the current mesh
  21678. */
  21679. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21680. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21681. return this;
  21682. };
  21683. /**
  21684. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21685. * Supports definition of mesh facing forward or backward.
  21686. * @param flipBack defines the flip
  21687. * @param twirlClockwise defines the twirl
  21688. * @param tiltRight defines the tilt
  21689. * @returns the new rotation vector
  21690. */
  21691. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21692. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21693. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21694. };
  21695. /**
  21696. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21697. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21698. * @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
  21699. * @returns the new bounding vectors
  21700. */
  21701. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21702. if (includeDescendants === void 0) { includeDescendants = true; }
  21703. if (predicate === void 0) { predicate = null; }
  21704. // Ensures that all world matrix will be recomputed.
  21705. this.getScene().incrementRenderId();
  21706. this.computeWorldMatrix(true);
  21707. var min;
  21708. var max;
  21709. var boundingInfo = this.getBoundingInfo();
  21710. if (!this.subMeshes) {
  21711. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21712. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21713. }
  21714. else {
  21715. min = boundingInfo.boundingBox.minimumWorld;
  21716. max = boundingInfo.boundingBox.maximumWorld;
  21717. }
  21718. if (includeDescendants) {
  21719. var descendants = this.getDescendants(false);
  21720. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21721. var descendant = descendants_1[_i];
  21722. var childMesh = descendant;
  21723. childMesh.computeWorldMatrix(true);
  21724. // Filters meshes based on custom predicate function.
  21725. if (predicate && !predicate(childMesh)) {
  21726. continue;
  21727. }
  21728. //make sure we have the needed params to get mix and max
  21729. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21730. continue;
  21731. }
  21732. var childBoundingInfo = childMesh.getBoundingInfo();
  21733. var boundingBox = childBoundingInfo.boundingBox;
  21734. var minBox = boundingBox.minimumWorld;
  21735. var maxBox = boundingBox.maximumWorld;
  21736. BABYLON.Tools.CheckExtends(minBox, min, max);
  21737. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21738. }
  21739. }
  21740. return {
  21741. min: min,
  21742. max: max
  21743. };
  21744. };
  21745. /** @hidden */
  21746. AbstractMesh.prototype._updateBoundingInfo = function () {
  21747. if (this._boundingInfo) {
  21748. this._boundingInfo.update(this.worldMatrixFromCache);
  21749. }
  21750. else {
  21751. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  21752. }
  21753. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21754. return this;
  21755. };
  21756. /** @hidden */
  21757. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21758. if (!this.subMeshes) {
  21759. return this;
  21760. }
  21761. var count = this.subMeshes.length;
  21762. for (var subIndex = 0; subIndex < count; subIndex++) {
  21763. var subMesh = this.subMeshes[subIndex];
  21764. if (count > 1 || !subMesh.IsGlobal) {
  21765. subMesh.updateBoundingInfo(matrix);
  21766. }
  21767. }
  21768. return this;
  21769. };
  21770. /** @hidden */
  21771. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21772. // Bounding info
  21773. this._updateBoundingInfo();
  21774. };
  21775. /**
  21776. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21777. * A mesh is in the frustum if its bounding box intersects the frustum
  21778. * @param frustumPlanes defines the frustum to test
  21779. * @returns true if the mesh is in the frustum planes
  21780. */
  21781. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21782. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21783. };
  21784. /**
  21785. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21786. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21787. * @param frustumPlanes defines the frustum to test
  21788. * @returns true if the mesh is completely in the frustum planes
  21789. */
  21790. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21791. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21792. };
  21793. /**
  21794. * True if the mesh intersects another mesh or a SolidParticle object
  21795. * @param mesh defines a target mesh or SolidParticle to test
  21796. * @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)
  21797. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21798. * @returns true if there is an intersection
  21799. */
  21800. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21801. if (precise === void 0) { precise = false; }
  21802. if (!this._boundingInfo || !mesh._boundingInfo) {
  21803. return false;
  21804. }
  21805. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21806. return true;
  21807. }
  21808. if (includeDescendants) {
  21809. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21810. var child = _a[_i];
  21811. if (child.intersectsMesh(mesh, precise, true)) {
  21812. return true;
  21813. }
  21814. }
  21815. }
  21816. return false;
  21817. };
  21818. /**
  21819. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21820. * @param point defines the point to test
  21821. * @returns true if there is an intersection
  21822. */
  21823. AbstractMesh.prototype.intersectsPoint = function (point) {
  21824. if (!this._boundingInfo) {
  21825. return false;
  21826. }
  21827. return this._boundingInfo.intersectsPoint(point);
  21828. };
  21829. /**
  21830. * Gets the position of the current mesh in camera space
  21831. * @param camera defines the camera to use
  21832. * @returns a position
  21833. */
  21834. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21835. if (camera === void 0) { camera = null; }
  21836. if (!camera) {
  21837. camera = this.getScene().activeCamera;
  21838. }
  21839. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21840. };
  21841. /**
  21842. * Returns the distance from the mesh to the active camera
  21843. * @param camera defines the camera to use
  21844. * @returns the distance
  21845. */
  21846. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21847. if (camera === void 0) { camera = null; }
  21848. if (!camera) {
  21849. camera = this.getScene().activeCamera;
  21850. }
  21851. return this.absolutePosition.subtract(camera.position).length();
  21852. };
  21853. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21854. // Collisions
  21855. /**
  21856. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21857. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21858. */
  21859. get: function () {
  21860. return this._checkCollisions;
  21861. },
  21862. set: function (collisionEnabled) {
  21863. this._checkCollisions = collisionEnabled;
  21864. if (this.getScene().workerCollisions) {
  21865. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21866. }
  21867. },
  21868. enumerable: true,
  21869. configurable: true
  21870. });
  21871. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21872. /**
  21873. * Gets Collider object used to compute collisions (not physics)
  21874. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21875. */
  21876. get: function () {
  21877. return this._collider;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. /**
  21883. * Move the mesh using collision engine
  21884. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21885. * @param displacement defines the requested displacement vector
  21886. * @returns the current mesh
  21887. */
  21888. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21889. var globalPosition = this.getAbsolutePosition();
  21890. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21891. if (!this._collider) {
  21892. this._collider = new BABYLON.Collider();
  21893. }
  21894. this._collider._radius = this.ellipsoid;
  21895. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21896. return this;
  21897. };
  21898. // Collisions
  21899. /** @hidden */
  21900. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21901. this._generatePointsArray();
  21902. if (!this._positions) {
  21903. return this;
  21904. }
  21905. // Transformation
  21906. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21907. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21908. subMesh._lastColliderWorldVertices = [];
  21909. subMesh._trianglePlanes = [];
  21910. var start = subMesh.verticesStart;
  21911. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21912. for (var i = start; i < end; i++) {
  21913. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21914. }
  21915. }
  21916. // Collide
  21917. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21918. if (collider.collisionFound) {
  21919. collider.collidedMesh = this;
  21920. }
  21921. return this;
  21922. };
  21923. /** @hidden */
  21924. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21925. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21926. var len = subMeshes.length;
  21927. for (var index = 0; index < len; index++) {
  21928. var subMesh = subMeshes.data[index];
  21929. // Bounding test
  21930. if (len > 1 && !subMesh._checkCollision(collider)) {
  21931. continue;
  21932. }
  21933. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21934. }
  21935. return this;
  21936. };
  21937. /** @hidden */
  21938. AbstractMesh.prototype._checkCollision = function (collider) {
  21939. // Bounding box test
  21940. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21941. return this;
  21942. }
  21943. // Transformation matrix
  21944. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21945. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21946. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21947. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21948. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21949. return this;
  21950. };
  21951. // Picking
  21952. /** @hidden */
  21953. AbstractMesh.prototype._generatePointsArray = function () {
  21954. return false;
  21955. };
  21956. /**
  21957. * Checks if the passed Ray intersects with the mesh
  21958. * @param ray defines the ray to use
  21959. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21960. * @returns the picking info
  21961. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21962. */
  21963. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21964. var pickingInfo = new BABYLON.PickingInfo();
  21965. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21966. return pickingInfo;
  21967. }
  21968. if (!this._generatePointsArray()) {
  21969. return pickingInfo;
  21970. }
  21971. var intersectInfo = null;
  21972. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21973. var len = subMeshes.length;
  21974. for (var index = 0; index < len; index++) {
  21975. var subMesh = subMeshes.data[index];
  21976. // Bounding test
  21977. if (len > 1 && !subMesh.canIntersects(ray)) {
  21978. continue;
  21979. }
  21980. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21981. if (currentIntersectInfo) {
  21982. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21983. intersectInfo = currentIntersectInfo;
  21984. intersectInfo.subMeshId = index;
  21985. if (fastCheck) {
  21986. break;
  21987. }
  21988. }
  21989. }
  21990. }
  21991. if (intersectInfo) {
  21992. // Get picked point
  21993. var world = this.getWorldMatrix();
  21994. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21995. var direction = ray.direction.clone();
  21996. direction = direction.scale(intersectInfo.distance);
  21997. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21998. var pickedPoint = worldOrigin.add(worldDirection);
  21999. // Return result
  22000. pickingInfo.hit = true;
  22001. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22002. pickingInfo.pickedPoint = pickedPoint;
  22003. pickingInfo.pickedMesh = this;
  22004. pickingInfo.bu = intersectInfo.bu || 0;
  22005. pickingInfo.bv = intersectInfo.bv || 0;
  22006. pickingInfo.faceId = intersectInfo.faceId;
  22007. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22008. return pickingInfo;
  22009. }
  22010. return pickingInfo;
  22011. };
  22012. /**
  22013. * Clones the current mesh
  22014. * @param name defines the mesh name
  22015. * @param newParent defines the new mesh parent
  22016. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22017. * @returns the new mesh
  22018. */
  22019. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22020. return null;
  22021. };
  22022. /**
  22023. * Disposes all the submeshes of the current meshnp
  22024. * @returns the current mesh
  22025. */
  22026. AbstractMesh.prototype.releaseSubMeshes = function () {
  22027. if (this.subMeshes) {
  22028. while (this.subMeshes.length) {
  22029. this.subMeshes[0].dispose();
  22030. }
  22031. }
  22032. else {
  22033. this.subMeshes = new Array();
  22034. }
  22035. return this;
  22036. };
  22037. /**
  22038. * Releases resources associated with this abstract mesh.
  22039. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22040. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22041. */
  22042. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22043. var _this = this;
  22044. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22045. var index;
  22046. // Smart Array Retainers.
  22047. this.getScene().freeActiveMeshes();
  22048. this.getScene().freeRenderingGroups();
  22049. // Action manager
  22050. if (this.actionManager !== undefined && this.actionManager !== null) {
  22051. this.actionManager.dispose();
  22052. this.actionManager = null;
  22053. }
  22054. // Skeleton
  22055. this._skeleton = null;
  22056. // Intersections in progress
  22057. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22058. var other = this._intersectionsInProgress[index];
  22059. var pos = other._intersectionsInProgress.indexOf(this);
  22060. other._intersectionsInProgress.splice(pos, 1);
  22061. }
  22062. this._intersectionsInProgress = [];
  22063. // Lights
  22064. var lights = this.getScene().lights;
  22065. lights.forEach(function (light) {
  22066. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22067. if (meshIndex !== -1) {
  22068. light.includedOnlyMeshes.splice(meshIndex, 1);
  22069. }
  22070. meshIndex = light.excludedMeshes.indexOf(_this);
  22071. if (meshIndex !== -1) {
  22072. light.excludedMeshes.splice(meshIndex, 1);
  22073. }
  22074. // Shadow generators
  22075. var generator = light.getShadowGenerator();
  22076. if (generator) {
  22077. var shadowMap = generator.getShadowMap();
  22078. if (shadowMap && shadowMap.renderList) {
  22079. meshIndex = shadowMap.renderList.indexOf(_this);
  22080. if (meshIndex !== -1) {
  22081. shadowMap.renderList.splice(meshIndex, 1);
  22082. }
  22083. }
  22084. }
  22085. });
  22086. // SubMeshes
  22087. if (this.getClassName() !== "InstancedMesh") {
  22088. this.releaseSubMeshes();
  22089. }
  22090. // Query
  22091. var engine = this.getScene().getEngine();
  22092. if (this._occlusionQuery) {
  22093. this.isOcclusionQueryInProgress = false;
  22094. engine.deleteQuery(this._occlusionQuery);
  22095. this._occlusionQuery = null;
  22096. }
  22097. // Engine
  22098. engine.wipeCaches();
  22099. // Remove from scene
  22100. this.getScene().removeMesh(this);
  22101. if (disposeMaterialAndTextures) {
  22102. if (this.material) {
  22103. this.material.dispose(false, true);
  22104. }
  22105. }
  22106. if (!doNotRecurse) {
  22107. // Particles
  22108. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22109. if (this.getScene().particleSystems[index].emitter === this) {
  22110. this.getScene().particleSystems[index].dispose();
  22111. index--;
  22112. }
  22113. }
  22114. }
  22115. // facet data
  22116. if (this._facetData.facetDataEnabled) {
  22117. this.disableFacetData();
  22118. }
  22119. this.onAfterWorldMatrixUpdateObservable.clear();
  22120. this.onCollideObservable.clear();
  22121. this.onCollisionPositionChangeObservable.clear();
  22122. this.onRebuildObservable.clear();
  22123. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22124. };
  22125. /**
  22126. * Adds the passed mesh as a child to the current mesh
  22127. * @param mesh defines the child mesh
  22128. * @returns the current mesh
  22129. */
  22130. AbstractMesh.prototype.addChild = function (mesh) {
  22131. mesh.setParent(this);
  22132. return this;
  22133. };
  22134. /**
  22135. * Removes the passed mesh from the current mesh children list
  22136. * @param mesh defines the child mesh
  22137. * @returns the current mesh
  22138. */
  22139. AbstractMesh.prototype.removeChild = function (mesh) {
  22140. mesh.setParent(null);
  22141. return this;
  22142. };
  22143. // Facet data
  22144. /** @hidden */
  22145. AbstractMesh.prototype._initFacetData = function () {
  22146. var data = this._facetData;
  22147. if (!data.facetNormals) {
  22148. data.facetNormals = new Array();
  22149. }
  22150. if (!data.facetPositions) {
  22151. data.facetPositions = new Array();
  22152. }
  22153. if (!data.facetPartitioning) {
  22154. data.facetPartitioning = new Array();
  22155. }
  22156. data.facetNb = (this.getIndices().length / 3) | 0;
  22157. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22158. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22159. for (var f = 0; f < data.facetNb; f++) {
  22160. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22161. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22162. }
  22163. data.facetDataEnabled = true;
  22164. return this;
  22165. };
  22166. /**
  22167. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22168. * This method can be called within the render loop.
  22169. * 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
  22170. * @returns the current mesh
  22171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22172. */
  22173. AbstractMesh.prototype.updateFacetData = function () {
  22174. var data = this._facetData;
  22175. if (!data.facetDataEnabled) {
  22176. this._initFacetData();
  22177. }
  22178. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22179. var indices = this.getIndices();
  22180. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22181. var bInfo = this.getBoundingInfo();
  22182. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22183. // init arrays, matrix and sort function on first call
  22184. data.facetDepthSortEnabled = true;
  22185. if (indices instanceof Uint16Array) {
  22186. data.depthSortedIndices = new Uint16Array(indices);
  22187. }
  22188. else if (indices instanceof Uint32Array) {
  22189. data.depthSortedIndices = new Uint32Array(indices);
  22190. }
  22191. else {
  22192. var needs32bits = false;
  22193. for (var i = 0; i < indices.length; i++) {
  22194. if (indices[i] > 65535) {
  22195. needs32bits = true;
  22196. break;
  22197. }
  22198. }
  22199. if (needs32bits) {
  22200. data.depthSortedIndices = new Uint32Array(indices);
  22201. }
  22202. else {
  22203. data.depthSortedIndices = new Uint16Array(indices);
  22204. }
  22205. }
  22206. data.facetDepthSortFunction = function (f1, f2) {
  22207. return (f2.sqDistance - f1.sqDistance);
  22208. };
  22209. if (!data.facetDepthSortFrom) {
  22210. var camera = this.getScene().activeCamera;
  22211. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22212. }
  22213. data.depthSortedFacets = [];
  22214. for (var f = 0; f < data.facetNb; f++) {
  22215. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22216. data.depthSortedFacets.push(depthSortedFacet);
  22217. }
  22218. data.invertedMatrix = BABYLON.Matrix.Identity();
  22219. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22220. }
  22221. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22222. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22223. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22224. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22225. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22226. data.subDiv.max = data.partitioningSubdivisions;
  22227. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22228. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22229. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22230. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22231. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22232. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22233. // set the parameters for ComputeNormals()
  22234. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22235. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22236. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22237. data.facetParameters.bInfo = bInfo;
  22238. data.facetParameters.bbSize = data.bbSize;
  22239. data.facetParameters.subDiv = data.subDiv;
  22240. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22241. data.facetParameters.depthSort = data.facetDepthSort;
  22242. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22243. this.computeWorldMatrix(true);
  22244. this._worldMatrix.invertToRef(data.invertedMatrix);
  22245. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22246. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22247. }
  22248. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22249. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22250. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22251. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22252. var l = (data.depthSortedIndices.length / 3) | 0;
  22253. for (var f = 0; f < l; f++) {
  22254. var sind = data.depthSortedFacets[f].ind;
  22255. data.depthSortedIndices[f * 3] = indices[sind];
  22256. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22257. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22258. }
  22259. this.updateIndices(data.depthSortedIndices);
  22260. }
  22261. return this;
  22262. };
  22263. /**
  22264. * Returns the facetLocalNormals array.
  22265. * The normals are expressed in the mesh local spac
  22266. * @returns an array of Vector3
  22267. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22268. */
  22269. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22270. if (!this._facetData.facetNormals) {
  22271. this.updateFacetData();
  22272. }
  22273. return this._facetData.facetNormals;
  22274. };
  22275. /**
  22276. * Returns the facetLocalPositions array.
  22277. * The facet positions are expressed in the mesh local space
  22278. * @returns an array of Vector3
  22279. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22280. */
  22281. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22282. if (!this._facetData.facetPositions) {
  22283. this.updateFacetData();
  22284. }
  22285. return this._facetData.facetPositions;
  22286. };
  22287. /**
  22288. * Returns the facetLocalPartioning array
  22289. * @returns an array of array of numbers
  22290. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22291. */
  22292. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22293. if (!this._facetData.facetPartitioning) {
  22294. this.updateFacetData();
  22295. }
  22296. return this._facetData.facetPartitioning;
  22297. };
  22298. /**
  22299. * Returns the i-th facet position in the world system.
  22300. * This method allocates a new Vector3 per call
  22301. * @param i defines the facet index
  22302. * @returns a new Vector3
  22303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22304. */
  22305. AbstractMesh.prototype.getFacetPosition = function (i) {
  22306. var pos = BABYLON.Vector3.Zero();
  22307. this.getFacetPositionToRef(i, pos);
  22308. return pos;
  22309. };
  22310. /**
  22311. * Sets the reference Vector3 with the i-th facet position in the world system
  22312. * @param i defines the facet index
  22313. * @param ref defines the target vector
  22314. * @returns the current mesh
  22315. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22316. */
  22317. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22318. var localPos = (this.getFacetLocalPositions())[i];
  22319. var world = this.getWorldMatrix();
  22320. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22321. return this;
  22322. };
  22323. /**
  22324. * Returns the i-th facet normal in the world system.
  22325. * This method allocates a new Vector3 per call
  22326. * @param i defines the facet index
  22327. * @returns a new Vector3
  22328. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22329. */
  22330. AbstractMesh.prototype.getFacetNormal = function (i) {
  22331. var norm = BABYLON.Vector3.Zero();
  22332. this.getFacetNormalToRef(i, norm);
  22333. return norm;
  22334. };
  22335. /**
  22336. * Sets the reference Vector3 with the i-th facet normal in the world system
  22337. * @param i defines the facet index
  22338. * @param ref defines the target vector
  22339. * @returns the current mesh
  22340. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22341. */
  22342. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22343. var localNorm = (this.getFacetLocalNormals())[i];
  22344. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22345. return this;
  22346. };
  22347. /**
  22348. * 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)
  22349. * @param x defines x coordinate
  22350. * @param y defines y coordinate
  22351. * @param z defines z coordinate
  22352. * @returns the array of facet indexes
  22353. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22354. */
  22355. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22356. var bInfo = this.getBoundingInfo();
  22357. var data = this._facetData;
  22358. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22359. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22360. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22361. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22362. return null;
  22363. }
  22364. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22365. };
  22366. /**
  22367. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22368. * @param projected sets as the (x,y,z) world projection on the facet
  22369. * @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
  22370. * @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
  22371. * @param x defines x coordinate
  22372. * @param y defines y coordinate
  22373. * @param z defines z coordinate
  22374. * @returns the face index if found (or null instead)
  22375. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22376. */
  22377. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22378. if (checkFace === void 0) { checkFace = false; }
  22379. if (facing === void 0) { facing = true; }
  22380. var world = this.getWorldMatrix();
  22381. var invMat = BABYLON.Tmp.Matrix[5];
  22382. world.invertToRef(invMat);
  22383. var invVect = BABYLON.Tmp.Vector3[8];
  22384. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22385. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22386. if (projected) {
  22387. // tranform the local computed projected vector to world coordinates
  22388. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22389. }
  22390. return closest;
  22391. };
  22392. /**
  22393. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22394. * @param projected sets as the (x,y,z) local projection on the facet
  22395. * @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
  22396. * @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
  22397. * @param x defines x coordinate
  22398. * @param y defines y coordinate
  22399. * @param z defines z coordinate
  22400. * @returns the face index if found (or null instead)
  22401. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22402. */
  22403. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22404. if (checkFace === void 0) { checkFace = false; }
  22405. if (facing === void 0) { facing = true; }
  22406. var closest = null;
  22407. var tmpx = 0.0;
  22408. var tmpy = 0.0;
  22409. var tmpz = 0.0;
  22410. var d = 0.0; // tmp dot facet normal * facet position
  22411. var t0 = 0.0;
  22412. var projx = 0.0;
  22413. var projy = 0.0;
  22414. var projz = 0.0;
  22415. // Get all the facets in the same partitioning block than (x, y, z)
  22416. var facetPositions = this.getFacetLocalPositions();
  22417. var facetNormals = this.getFacetLocalNormals();
  22418. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22419. if (!facetsInBlock) {
  22420. return null;
  22421. }
  22422. // Get the closest facet to (x, y, z)
  22423. var shortest = Number.MAX_VALUE; // init distance vars
  22424. var tmpDistance = shortest;
  22425. var fib; // current facet in the block
  22426. var norm; // current facet normal
  22427. var p0; // current facet barycenter position
  22428. // loop on all the facets in the current partitioning block
  22429. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22430. fib = facetsInBlock[idx];
  22431. norm = facetNormals[fib];
  22432. p0 = facetPositions[fib];
  22433. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22434. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22435. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22436. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22437. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22438. projx = x + norm.x * t0;
  22439. projy = y + norm.y * t0;
  22440. projz = z + norm.z * t0;
  22441. tmpx = projx - x;
  22442. tmpy = projy - y;
  22443. tmpz = projz - z;
  22444. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22445. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22446. shortest = tmpDistance;
  22447. closest = fib;
  22448. if (projected) {
  22449. projected.x = projx;
  22450. projected.y = projy;
  22451. projected.z = projz;
  22452. }
  22453. }
  22454. }
  22455. }
  22456. return closest;
  22457. };
  22458. /**
  22459. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22460. * @returns the parameters
  22461. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22462. */
  22463. AbstractMesh.prototype.getFacetDataParameters = function () {
  22464. return this._facetData.facetParameters;
  22465. };
  22466. /**
  22467. * Disables the feature FacetData and frees the related memory
  22468. * @returns the current mesh
  22469. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22470. */
  22471. AbstractMesh.prototype.disableFacetData = function () {
  22472. if (this._facetData.facetDataEnabled) {
  22473. this._facetData.facetDataEnabled = false;
  22474. this._facetData.facetPositions = new Array();
  22475. this._facetData.facetNormals = new Array();
  22476. this._facetData.facetPartitioning = new Array();
  22477. this._facetData.facetParameters = null;
  22478. this._facetData.depthSortedIndices = new Uint32Array(0);
  22479. }
  22480. return this;
  22481. };
  22482. /**
  22483. * Updates the AbstractMesh indices array
  22484. * @param indices defines the data source
  22485. * @returns the current mesh
  22486. */
  22487. AbstractMesh.prototype.updateIndices = function (indices) {
  22488. return this;
  22489. };
  22490. /**
  22491. * Creates new normals data for the mesh
  22492. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22493. * @returns the current mesh
  22494. */
  22495. AbstractMesh.prototype.createNormals = function (updatable) {
  22496. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22497. var indices = this.getIndices();
  22498. var normals;
  22499. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22500. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22501. }
  22502. else {
  22503. normals = [];
  22504. }
  22505. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22506. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22507. return this;
  22508. };
  22509. /**
  22510. * Align the mesh with a normal
  22511. * @param normal defines the normal to use
  22512. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22513. * @returns the current mesh
  22514. */
  22515. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22516. if (!upDirection) {
  22517. upDirection = BABYLON.Axis.Y;
  22518. }
  22519. var axisX = BABYLON.Tmp.Vector3[0];
  22520. var axisZ = BABYLON.Tmp.Vector3[1];
  22521. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22522. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22523. if (this.rotationQuaternion) {
  22524. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22525. }
  22526. else {
  22527. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22528. }
  22529. return this;
  22530. };
  22531. /** @hidden */
  22532. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22533. return false;
  22534. };
  22535. /** No occlusion */
  22536. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22537. /** Occlusion set to optimisitic */
  22538. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22539. /** Occlusion set to strict */
  22540. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22541. /** Use an accurante occlusion algorithm */
  22542. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22543. /** Use a conservative occlusion algorithm */
  22544. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22545. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22546. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22547. /** Culling strategy with bounding sphere only and then frustum culling */
  22548. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22549. return AbstractMesh;
  22550. }(BABYLON.TransformNode));
  22551. BABYLON.AbstractMesh = AbstractMesh;
  22552. })(BABYLON || (BABYLON = {}));
  22553. //# sourceMappingURL=babylon.abstractMesh.js.map
  22554. var BABYLON;
  22555. (function (BABYLON) {
  22556. /**
  22557. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22558. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22559. * 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.
  22560. */
  22561. var Light = /** @class */ (function (_super) {
  22562. __extends(Light, _super);
  22563. /**
  22564. * Creates a Light object in the scene.
  22565. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22566. * @param name The firendly name of the light
  22567. * @param scene The scene the light belongs too
  22568. */
  22569. function Light(name, scene) {
  22570. var _this = _super.call(this, name, scene) || this;
  22571. /**
  22572. * Diffuse gives the basic color to an object.
  22573. */
  22574. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22575. /**
  22576. * Specular produces a highlight color on an object.
  22577. * Note: This is note affecting PBR materials.
  22578. */
  22579. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22580. /**
  22581. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22582. * falling off base on range or angle.
  22583. * This can be set to any values in Light.FALLOFF_x.
  22584. *
  22585. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22586. * other types of materials.
  22587. */
  22588. _this.falloffType = Light.FALLOFF_DEFAULT;
  22589. /**
  22590. * Strength of the light.
  22591. * Note: By default it is define in the framework own unit.
  22592. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22593. */
  22594. _this.intensity = 1.0;
  22595. _this._range = Number.MAX_VALUE;
  22596. _this._inverseSquaredRange = 0;
  22597. /**
  22598. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22599. * of light.
  22600. */
  22601. _this._photometricScale = 1.0;
  22602. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22603. _this._radius = 0.00001;
  22604. /**
  22605. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22606. * exceeding the number allowed of the materials.
  22607. */
  22608. _this.renderPriority = 0;
  22609. _this._shadowEnabled = true;
  22610. _this._excludeWithLayerMask = 0;
  22611. _this._includeOnlyWithLayerMask = 0;
  22612. _this._lightmapMode = 0;
  22613. /**
  22614. * @hidden Internal use only.
  22615. */
  22616. _this._excludedMeshesIds = new Array();
  22617. /**
  22618. * @hidden Internal use only.
  22619. */
  22620. _this._includedOnlyMeshesIds = new Array();
  22621. _this.getScene().addLight(_this);
  22622. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22623. _this._buildUniformLayout();
  22624. _this.includedOnlyMeshes = new Array();
  22625. _this.excludedMeshes = new Array();
  22626. _this._resyncMeshes();
  22627. return _this;
  22628. }
  22629. Object.defineProperty(Light.prototype, "range", {
  22630. /**
  22631. * Defines how far from the source the light is impacting in scene units.
  22632. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22633. */
  22634. get: function () {
  22635. return this._range;
  22636. },
  22637. /**
  22638. * Defines how far from the source the light is impacting in scene units.
  22639. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22640. */
  22641. set: function (value) {
  22642. this._range = value;
  22643. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22644. },
  22645. enumerable: true,
  22646. configurable: true
  22647. });
  22648. Object.defineProperty(Light.prototype, "intensityMode", {
  22649. /**
  22650. * Gets the photometric scale used to interpret the intensity.
  22651. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22652. */
  22653. get: function () {
  22654. return this._intensityMode;
  22655. },
  22656. /**
  22657. * Sets the photometric scale used to interpret the intensity.
  22658. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22659. */
  22660. set: function (value) {
  22661. this._intensityMode = value;
  22662. this._computePhotometricScale();
  22663. },
  22664. enumerable: true,
  22665. configurable: true
  22666. });
  22667. Object.defineProperty(Light.prototype, "radius", {
  22668. /**
  22669. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22670. */
  22671. get: function () {
  22672. return this._radius;
  22673. },
  22674. /**
  22675. * sets the light radius used by PBR Materials to simulate soft area lights.
  22676. */
  22677. set: function (value) {
  22678. this._radius = value;
  22679. this._computePhotometricScale();
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22685. /**
  22686. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22687. * the current shadow generator.
  22688. */
  22689. get: function () {
  22690. return this._shadowEnabled;
  22691. },
  22692. /**
  22693. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22694. * the current shadow generator.
  22695. */
  22696. set: function (value) {
  22697. if (this._shadowEnabled === value) {
  22698. return;
  22699. }
  22700. this._shadowEnabled = value;
  22701. this._markMeshesAsLightDirty();
  22702. },
  22703. enumerable: true,
  22704. configurable: true
  22705. });
  22706. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22707. /**
  22708. * Gets the only meshes impacted by this light.
  22709. */
  22710. get: function () {
  22711. return this._includedOnlyMeshes;
  22712. },
  22713. /**
  22714. * Sets the only meshes impacted by this light.
  22715. */
  22716. set: function (value) {
  22717. this._includedOnlyMeshes = value;
  22718. this._hookArrayForIncludedOnly(value);
  22719. },
  22720. enumerable: true,
  22721. configurable: true
  22722. });
  22723. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22724. /**
  22725. * Gets the meshes not impacted by this light.
  22726. */
  22727. get: function () {
  22728. return this._excludedMeshes;
  22729. },
  22730. /**
  22731. * Sets the meshes not impacted by this light.
  22732. */
  22733. set: function (value) {
  22734. this._excludedMeshes = value;
  22735. this._hookArrayForExcluded(value);
  22736. },
  22737. enumerable: true,
  22738. configurable: true
  22739. });
  22740. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22741. /**
  22742. * Gets the layer id use to find what meshes are not impacted by the light.
  22743. * Inactive if 0
  22744. */
  22745. get: function () {
  22746. return this._excludeWithLayerMask;
  22747. },
  22748. /**
  22749. * Sets the layer id use to find what meshes are not impacted by the light.
  22750. * Inactive if 0
  22751. */
  22752. set: function (value) {
  22753. this._excludeWithLayerMask = value;
  22754. this._resyncMeshes();
  22755. },
  22756. enumerable: true,
  22757. configurable: true
  22758. });
  22759. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22760. /**
  22761. * Gets the layer id use to find what meshes are impacted by the light.
  22762. * Inactive if 0
  22763. */
  22764. get: function () {
  22765. return this._includeOnlyWithLayerMask;
  22766. },
  22767. /**
  22768. * Sets the layer id use to find what meshes are impacted by the light.
  22769. * Inactive if 0
  22770. */
  22771. set: function (value) {
  22772. this._includeOnlyWithLayerMask = value;
  22773. this._resyncMeshes();
  22774. },
  22775. enumerable: true,
  22776. configurable: true
  22777. });
  22778. Object.defineProperty(Light.prototype, "lightmapMode", {
  22779. /**
  22780. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22781. */
  22782. get: function () {
  22783. return this._lightmapMode;
  22784. },
  22785. /**
  22786. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22787. */
  22788. set: function (value) {
  22789. if (this._lightmapMode === value) {
  22790. return;
  22791. }
  22792. this._lightmapMode = value;
  22793. this._markMeshesAsLightDirty();
  22794. },
  22795. enumerable: true,
  22796. configurable: true
  22797. });
  22798. /**
  22799. * Returns the string "Light".
  22800. * @returns the class name
  22801. */
  22802. Light.prototype.getClassName = function () {
  22803. return "Light";
  22804. };
  22805. /**
  22806. * Converts the light information to a readable string for debug purpose.
  22807. * @param fullDetails Supports for multiple levels of logging within scene loading
  22808. * @returns the human readable light info
  22809. */
  22810. Light.prototype.toString = function (fullDetails) {
  22811. var ret = "Name: " + this.name;
  22812. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22813. if (this.animations) {
  22814. for (var i = 0; i < this.animations.length; i++) {
  22815. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22816. }
  22817. }
  22818. if (fullDetails) {
  22819. }
  22820. return ret;
  22821. };
  22822. /** @hidden */
  22823. Light.prototype._syncParentEnabledState = function () {
  22824. _super.prototype._syncParentEnabledState.call(this);
  22825. this._resyncMeshes();
  22826. };
  22827. /**
  22828. * Set the enabled state of this node.
  22829. * @param value - the new enabled state
  22830. */
  22831. Light.prototype.setEnabled = function (value) {
  22832. _super.prototype.setEnabled.call(this, value);
  22833. this._resyncMeshes();
  22834. };
  22835. /**
  22836. * Returns the Light associated shadow generator if any.
  22837. * @return the associated shadow generator.
  22838. */
  22839. Light.prototype.getShadowGenerator = function () {
  22840. return this._shadowGenerator;
  22841. };
  22842. /**
  22843. * Returns a Vector3, the absolute light position in the World.
  22844. * @returns the world space position of the light
  22845. */
  22846. Light.prototype.getAbsolutePosition = function () {
  22847. return BABYLON.Vector3.Zero();
  22848. };
  22849. /**
  22850. * Specifies if the light will affect the passed mesh.
  22851. * @param mesh The mesh to test against the light
  22852. * @return true the mesh is affected otherwise, false.
  22853. */
  22854. Light.prototype.canAffectMesh = function (mesh) {
  22855. if (!mesh) {
  22856. return true;
  22857. }
  22858. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22859. return false;
  22860. }
  22861. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22862. return false;
  22863. }
  22864. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22865. return false;
  22866. }
  22867. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22868. return false;
  22869. }
  22870. return true;
  22871. };
  22872. /**
  22873. * Sort function to order lights for rendering.
  22874. * @param a First Light object to compare to second.
  22875. * @param b Second Light object to compare first.
  22876. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22877. */
  22878. Light.CompareLightsPriority = function (a, b) {
  22879. //shadow-casting lights have priority over non-shadow-casting lights
  22880. //the renderPrioirty is a secondary sort criterion
  22881. if (a.shadowEnabled !== b.shadowEnabled) {
  22882. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22883. }
  22884. return b.renderPriority - a.renderPriority;
  22885. };
  22886. /**
  22887. * Releases resources associated with this node.
  22888. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22889. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22890. */
  22891. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22892. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22893. if (this._shadowGenerator) {
  22894. this._shadowGenerator.dispose();
  22895. this._shadowGenerator = null;
  22896. }
  22897. // Animations
  22898. this.getScene().stopAnimation(this);
  22899. // Remove from meshes
  22900. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22901. var mesh = _a[_i];
  22902. mesh._removeLightSource(this);
  22903. }
  22904. this._uniformBuffer.dispose();
  22905. // Remove from scene
  22906. this.getScene().removeLight(this);
  22907. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22908. };
  22909. /**
  22910. * Returns the light type ID (integer).
  22911. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22912. */
  22913. Light.prototype.getTypeID = function () {
  22914. return 0;
  22915. };
  22916. /**
  22917. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22918. * @returns the scaled intensity in intensity mode unit
  22919. */
  22920. Light.prototype.getScaledIntensity = function () {
  22921. return this._photometricScale * this.intensity;
  22922. };
  22923. /**
  22924. * Returns a new Light object, named "name", from the current one.
  22925. * @param name The name of the cloned light
  22926. * @returns the new created light
  22927. */
  22928. Light.prototype.clone = function (name) {
  22929. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22930. if (!constructor) {
  22931. return null;
  22932. }
  22933. return BABYLON.SerializationHelper.Clone(constructor, this);
  22934. };
  22935. /**
  22936. * Serializes the current light into a Serialization object.
  22937. * @returns the serialized object.
  22938. */
  22939. Light.prototype.serialize = function () {
  22940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22941. // Type
  22942. serializationObject.type = this.getTypeID();
  22943. // Parent
  22944. if (this.parent) {
  22945. serializationObject.parentId = this.parent.id;
  22946. }
  22947. // Inclusion / exclusions
  22948. if (this.excludedMeshes.length > 0) {
  22949. serializationObject.excludedMeshesIds = [];
  22950. this.excludedMeshes.forEach(function (mesh) {
  22951. serializationObject.excludedMeshesIds.push(mesh.id);
  22952. });
  22953. }
  22954. if (this.includedOnlyMeshes.length > 0) {
  22955. serializationObject.includedOnlyMeshesIds = [];
  22956. this.includedOnlyMeshes.forEach(function (mesh) {
  22957. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22958. });
  22959. }
  22960. // Animations
  22961. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22962. serializationObject.ranges = this.serializeAnimationRanges();
  22963. return serializationObject;
  22964. };
  22965. /**
  22966. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22967. * This new light is named "name" and added to the passed scene.
  22968. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22969. * @param name The friendly name of the light
  22970. * @param scene The scene the new light will belong to
  22971. * @returns the constructor function
  22972. */
  22973. Light.GetConstructorFromName = function (type, name, scene) {
  22974. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22975. if (constructorFunc) {
  22976. return constructorFunc;
  22977. }
  22978. // Default to no light for none present once.
  22979. return null;
  22980. };
  22981. /**
  22982. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22983. * @param parsedLight The JSON representation of the light
  22984. * @param scene The scene to create the parsed light in
  22985. * @returns the created light after parsing
  22986. */
  22987. Light.Parse = function (parsedLight, scene) {
  22988. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22989. if (!constructor) {
  22990. return null;
  22991. }
  22992. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22993. // Inclusion / exclusions
  22994. if (parsedLight.excludedMeshesIds) {
  22995. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22996. }
  22997. if (parsedLight.includedOnlyMeshesIds) {
  22998. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22999. }
  23000. // Parent
  23001. if (parsedLight.parentId) {
  23002. light._waitingParentId = parsedLight.parentId;
  23003. }
  23004. // Animations
  23005. if (parsedLight.animations) {
  23006. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23007. var parsedAnimation = parsedLight.animations[animationIndex];
  23008. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23009. }
  23010. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23011. }
  23012. if (parsedLight.autoAnimate) {
  23013. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23014. }
  23015. return light;
  23016. };
  23017. Light.prototype._hookArrayForExcluded = function (array) {
  23018. var _this = this;
  23019. var oldPush = array.push;
  23020. array.push = function () {
  23021. var items = [];
  23022. for (var _i = 0; _i < arguments.length; _i++) {
  23023. items[_i] = arguments[_i];
  23024. }
  23025. var result = oldPush.apply(array, items);
  23026. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23027. var item = items_1[_a];
  23028. item._resyncLighSource(_this);
  23029. }
  23030. return result;
  23031. };
  23032. var oldSplice = array.splice;
  23033. array.splice = function (index, deleteCount) {
  23034. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23035. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23036. var item = deleted_1[_i];
  23037. item._resyncLighSource(_this);
  23038. }
  23039. return deleted;
  23040. };
  23041. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23042. var item = array_1[_i];
  23043. item._resyncLighSource(this);
  23044. }
  23045. };
  23046. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23047. var _this = this;
  23048. var oldPush = array.push;
  23049. array.push = function () {
  23050. var items = [];
  23051. for (var _i = 0; _i < arguments.length; _i++) {
  23052. items[_i] = arguments[_i];
  23053. }
  23054. var result = oldPush.apply(array, items);
  23055. _this._resyncMeshes();
  23056. return result;
  23057. };
  23058. var oldSplice = array.splice;
  23059. array.splice = function (index, deleteCount) {
  23060. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23061. _this._resyncMeshes();
  23062. return deleted;
  23063. };
  23064. this._resyncMeshes();
  23065. };
  23066. Light.prototype._resyncMeshes = function () {
  23067. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23068. var mesh = _a[_i];
  23069. mesh._resyncLighSource(this);
  23070. }
  23071. };
  23072. /**
  23073. * Forces the meshes to update their light related information in their rendering used effects
  23074. * @hidden Internal Use Only
  23075. */
  23076. Light.prototype._markMeshesAsLightDirty = function () {
  23077. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23078. var mesh = _a[_i];
  23079. if (mesh._lightSources.indexOf(this) !== -1) {
  23080. mesh._markSubMeshesAsLightDirty();
  23081. }
  23082. }
  23083. };
  23084. /**
  23085. * Recomputes the cached photometric scale if needed.
  23086. */
  23087. Light.prototype._computePhotometricScale = function () {
  23088. this._photometricScale = this._getPhotometricScale();
  23089. this.getScene().resetCachedMaterial();
  23090. };
  23091. /**
  23092. * Returns the Photometric Scale according to the light type and intensity mode.
  23093. */
  23094. Light.prototype._getPhotometricScale = function () {
  23095. var photometricScale = 0.0;
  23096. var lightTypeID = this.getTypeID();
  23097. //get photometric mode
  23098. var photometricMode = this.intensityMode;
  23099. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23100. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23101. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23102. }
  23103. else {
  23104. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23105. }
  23106. }
  23107. //compute photometric scale
  23108. switch (lightTypeID) {
  23109. case Light.LIGHTTYPEID_POINTLIGHT:
  23110. case Light.LIGHTTYPEID_SPOTLIGHT:
  23111. switch (photometricMode) {
  23112. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23113. photometricScale = 1.0 / (4.0 * Math.PI);
  23114. break;
  23115. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23116. photometricScale = 1.0;
  23117. break;
  23118. case Light.INTENSITYMODE_LUMINANCE:
  23119. photometricScale = this.radius * this.radius;
  23120. break;
  23121. }
  23122. break;
  23123. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23124. switch (photometricMode) {
  23125. case Light.INTENSITYMODE_ILLUMINANCE:
  23126. photometricScale = 1.0;
  23127. break;
  23128. case Light.INTENSITYMODE_LUMINANCE:
  23129. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23130. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23131. var apexAngleRadians = this.radius;
  23132. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23133. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23134. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23135. photometricScale = solidAngle;
  23136. break;
  23137. }
  23138. break;
  23139. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23140. // No fall off in hemisperic light.
  23141. photometricScale = 1.0;
  23142. break;
  23143. }
  23144. return photometricScale;
  23145. };
  23146. /**
  23147. * Reorder the light in the scene according to their defined priority.
  23148. * @hidden Internal Use Only
  23149. */
  23150. Light.prototype._reorderLightsInScene = function () {
  23151. var scene = this.getScene();
  23152. if (this._renderPriority != 0) {
  23153. scene.requireLightSorting = true;
  23154. }
  23155. this.getScene().sortLightsByPriority();
  23156. };
  23157. /**
  23158. * Falloff Default: light is falling off following the material specification:
  23159. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23160. */
  23161. Light.FALLOFF_DEFAULT = 0;
  23162. /**
  23163. * Falloff Physical: light is falling off following the inverse squared distance law.
  23164. */
  23165. Light.FALLOFF_PHYSICAL = 1;
  23166. /**
  23167. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23168. * to enhance interoperability with other engines.
  23169. */
  23170. Light.FALLOFF_GLTF = 2;
  23171. /**
  23172. * Falloff Standard: light is falling off like in the standard material
  23173. * to enhance interoperability with other materials.
  23174. */
  23175. Light.FALLOFF_STANDARD = 3;
  23176. //lightmapMode Consts
  23177. /**
  23178. * If every light affecting the material is in this lightmapMode,
  23179. * material.lightmapTexture adds or multiplies
  23180. * (depends on material.useLightmapAsShadowmap)
  23181. * after every other light calculations.
  23182. */
  23183. Light.LIGHTMAP_DEFAULT = 0;
  23184. /**
  23185. * material.lightmapTexture as only diffuse lighting from this light
  23186. * adds only specular lighting from this light
  23187. * adds dynamic shadows
  23188. */
  23189. Light.LIGHTMAP_SPECULAR = 1;
  23190. /**
  23191. * material.lightmapTexture as only lighting
  23192. * no light calculation from this light
  23193. * only adds dynamic shadows from this light
  23194. */
  23195. Light.LIGHTMAP_SHADOWSONLY = 2;
  23196. // Intensity Mode Consts
  23197. /**
  23198. * Each light type uses the default quantity according to its type:
  23199. * point/spot lights use luminous intensity
  23200. * directional lights use illuminance
  23201. */
  23202. Light.INTENSITYMODE_AUTOMATIC = 0;
  23203. /**
  23204. * lumen (lm)
  23205. */
  23206. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23207. /**
  23208. * candela (lm/sr)
  23209. */
  23210. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23211. /**
  23212. * lux (lm/m^2)
  23213. */
  23214. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23215. /**
  23216. * nit (cd/m^2)
  23217. */
  23218. Light.INTENSITYMODE_LUMINANCE = 4;
  23219. // Light types ids const.
  23220. /**
  23221. * Light type const id of the point light.
  23222. */
  23223. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23224. /**
  23225. * Light type const id of the directional light.
  23226. */
  23227. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23228. /**
  23229. * Light type const id of the spot light.
  23230. */
  23231. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23232. /**
  23233. * Light type const id of the hemispheric light.
  23234. */
  23235. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23236. __decorate([
  23237. BABYLON.serializeAsColor3()
  23238. ], Light.prototype, "diffuse", void 0);
  23239. __decorate([
  23240. BABYLON.serializeAsColor3()
  23241. ], Light.prototype, "specular", void 0);
  23242. __decorate([
  23243. BABYLON.serialize()
  23244. ], Light.prototype, "falloffType", void 0);
  23245. __decorate([
  23246. BABYLON.serialize()
  23247. ], Light.prototype, "intensity", void 0);
  23248. __decorate([
  23249. BABYLON.serialize()
  23250. ], Light.prototype, "range", null);
  23251. __decorate([
  23252. BABYLON.serialize()
  23253. ], Light.prototype, "intensityMode", null);
  23254. __decorate([
  23255. BABYLON.serialize()
  23256. ], Light.prototype, "radius", null);
  23257. __decorate([
  23258. BABYLON.serialize()
  23259. ], Light.prototype, "_renderPriority", void 0);
  23260. __decorate([
  23261. BABYLON.expandToProperty("_reorderLightsInScene")
  23262. ], Light.prototype, "renderPriority", void 0);
  23263. __decorate([
  23264. BABYLON.serialize("shadowEnabled")
  23265. ], Light.prototype, "_shadowEnabled", void 0);
  23266. __decorate([
  23267. BABYLON.serialize("excludeWithLayerMask")
  23268. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23269. __decorate([
  23270. BABYLON.serialize("includeOnlyWithLayerMask")
  23271. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23272. __decorate([
  23273. BABYLON.serialize("lightmapMode")
  23274. ], Light.prototype, "_lightmapMode", void 0);
  23275. return Light;
  23276. }(BABYLON.Node));
  23277. BABYLON.Light = Light;
  23278. })(BABYLON || (BABYLON = {}));
  23279. //# sourceMappingURL=babylon.light.js.map
  23280. var BABYLON;
  23281. (function (BABYLON) {
  23282. /**
  23283. * This is the base class of all the camera used in the application.
  23284. * @see http://doc.babylonjs.com/features/cameras
  23285. */
  23286. var Camera = /** @class */ (function (_super) {
  23287. __extends(Camera, _super);
  23288. /**
  23289. * Instantiates a new camera object.
  23290. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23291. * @see http://doc.babylonjs.com/features/cameras
  23292. * @param name Defines the name of the camera in the scene
  23293. * @param position Defines the position of the camera
  23294. * @param scene Defines the scene the camera belongs too
  23295. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23296. */
  23297. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23298. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23299. var _this = _super.call(this, name, scene) || this;
  23300. /**
  23301. * The vector the camera should consider as up.
  23302. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23303. */
  23304. _this.upVector = BABYLON.Vector3.Up();
  23305. /**
  23306. * Define the current limit on the left side for an orthographic camera
  23307. * In scene unit
  23308. */
  23309. _this.orthoLeft = null;
  23310. /**
  23311. * Define the current limit on the right side for an orthographic camera
  23312. * In scene unit
  23313. */
  23314. _this.orthoRight = null;
  23315. /**
  23316. * Define the current limit on the bottom side for an orthographic camera
  23317. * In scene unit
  23318. */
  23319. _this.orthoBottom = null;
  23320. /**
  23321. * Define the current limit on the top side for an orthographic camera
  23322. * In scene unit
  23323. */
  23324. _this.orthoTop = null;
  23325. /**
  23326. * Field Of View is set in Radians. (default is 0.8)
  23327. */
  23328. _this.fov = 0.8;
  23329. /**
  23330. * Define the minimum distance the camera can see from.
  23331. * This is important to note that the depth buffer are not infinite and the closer it starts
  23332. * the more your scene might encounter depth fighting issue.
  23333. */
  23334. _this.minZ = 1;
  23335. /**
  23336. * Define the maximum distance the camera can see to.
  23337. * This is important to note that the depth buffer are not infinite and the further it end
  23338. * the more your scene might encounter depth fighting issue.
  23339. */
  23340. _this.maxZ = 10000.0;
  23341. /**
  23342. * Define the default inertia of the camera.
  23343. * This helps giving a smooth feeling to the camera movement.
  23344. */
  23345. _this.inertia = 0.9;
  23346. /**
  23347. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23348. */
  23349. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23350. /**
  23351. * Define wether the camera is intermediate.
  23352. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23353. */
  23354. _this.isIntermediate = false;
  23355. /**
  23356. * Define the viewport of the camera.
  23357. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23358. */
  23359. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23360. /**
  23361. * Restricts the camera to viewing objects with the same layerMask.
  23362. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23363. */
  23364. _this.layerMask = 0x0FFFFFFF;
  23365. /**
  23366. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23367. */
  23368. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23369. /**
  23370. * Rig mode of the camera.
  23371. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23372. * This is normally controlled byt the camera themselves as internal use.
  23373. */
  23374. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23375. /**
  23376. * Defines the list of custom render target the camera should render to.
  23377. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23378. * else in the scene.
  23379. */
  23380. _this.customRenderTargets = new Array();
  23381. /**
  23382. * When set, the camera will render to this render target instead of the default canvas
  23383. */
  23384. _this.customDefaultRenderTarget = null;
  23385. /**
  23386. * Observable triggered when the camera view matrix has changed.
  23387. */
  23388. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23389. /**
  23390. * Observable triggered when the camera Projection matrix has changed.
  23391. */
  23392. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23393. /**
  23394. * Observable triggered when the inputs have been processed.
  23395. */
  23396. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23397. /**
  23398. * Observable triggered when reset has been called and applied to the camera.
  23399. */
  23400. _this.onRestoreStateObservable = new BABYLON.Observable();
  23401. /** @hidden */
  23402. _this._rigCameras = new Array();
  23403. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23404. /** @hidden */
  23405. _this._skipRendering = false;
  23406. /** @hidden */
  23407. _this._projectionMatrix = new BABYLON.Matrix();
  23408. /** @hidden */
  23409. _this._postProcesses = new Array();
  23410. /** @hidden */
  23411. _this._activeMeshes = new BABYLON.SmartArray(256);
  23412. _this._globalPosition = BABYLON.Vector3.Zero();
  23413. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23414. _this._doNotComputeProjectionMatrix = false;
  23415. _this._transformMatrix = BABYLON.Matrix.Zero();
  23416. _this._refreshFrustumPlanes = true;
  23417. _this.getScene().addCamera(_this);
  23418. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23419. _this.getScene().activeCamera = _this;
  23420. }
  23421. _this.position = position;
  23422. return _this;
  23423. }
  23424. /**
  23425. * Store current camera state (fov, position, etc..)
  23426. * @returns the camera
  23427. */
  23428. Camera.prototype.storeState = function () {
  23429. this._stateStored = true;
  23430. this._storedFov = this.fov;
  23431. return this;
  23432. };
  23433. /**
  23434. * Restores the camera state values if it has been stored. You must call storeState() first
  23435. */
  23436. Camera.prototype._restoreStateValues = function () {
  23437. if (!this._stateStored) {
  23438. return false;
  23439. }
  23440. this.fov = this._storedFov;
  23441. return true;
  23442. };
  23443. /**
  23444. * Restored camera state. You must call storeState() first.
  23445. * @returns true if restored and false otherwise
  23446. */
  23447. Camera.prototype.restoreState = function () {
  23448. if (this._restoreStateValues()) {
  23449. this.onRestoreStateObservable.notifyObservers(this);
  23450. return true;
  23451. }
  23452. return false;
  23453. };
  23454. /**
  23455. * Gets the class name of the camera.
  23456. * @returns the class name
  23457. */
  23458. Camera.prototype.getClassName = function () {
  23459. return "Camera";
  23460. };
  23461. /**
  23462. * Gets a string representation of the camera usefull for debug purpose.
  23463. * @param fullDetails Defines that a more verboe level of logging is required
  23464. * @returns the string representation
  23465. */
  23466. Camera.prototype.toString = function (fullDetails) {
  23467. var ret = "Name: " + this.name;
  23468. ret += ", type: " + this.getClassName();
  23469. if (this.animations) {
  23470. for (var i = 0; i < this.animations.length; i++) {
  23471. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23472. }
  23473. }
  23474. if (fullDetails) {
  23475. }
  23476. return ret;
  23477. };
  23478. Object.defineProperty(Camera.prototype, "globalPosition", {
  23479. /**
  23480. * Gets the current world space position of the camera.
  23481. */
  23482. get: function () {
  23483. return this._globalPosition;
  23484. },
  23485. enumerable: true,
  23486. configurable: true
  23487. });
  23488. /**
  23489. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23490. * @returns the active meshe list
  23491. */
  23492. Camera.prototype.getActiveMeshes = function () {
  23493. return this._activeMeshes;
  23494. };
  23495. /**
  23496. * Check wether a mesh is part of the current active mesh list of the camera
  23497. * @param mesh Defines the mesh to check
  23498. * @returns true if active, false otherwise
  23499. */
  23500. Camera.prototype.isActiveMesh = function (mesh) {
  23501. return (this._activeMeshes.indexOf(mesh) !== -1);
  23502. };
  23503. /**
  23504. * Is this camera ready to be used/rendered
  23505. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23506. * @return true if the camera is ready
  23507. */
  23508. Camera.prototype.isReady = function (completeCheck) {
  23509. if (completeCheck === void 0) { completeCheck = false; }
  23510. if (completeCheck) {
  23511. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23512. var pp = _a[_i];
  23513. if (pp && !pp.isReady()) {
  23514. return false;
  23515. }
  23516. }
  23517. }
  23518. return _super.prototype.isReady.call(this, completeCheck);
  23519. };
  23520. /** @hidden */
  23521. Camera.prototype._initCache = function () {
  23522. _super.prototype._initCache.call(this);
  23523. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23524. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23525. this._cache.mode = undefined;
  23526. this._cache.minZ = undefined;
  23527. this._cache.maxZ = undefined;
  23528. this._cache.fov = undefined;
  23529. this._cache.fovMode = undefined;
  23530. this._cache.aspectRatio = undefined;
  23531. this._cache.orthoLeft = undefined;
  23532. this._cache.orthoRight = undefined;
  23533. this._cache.orthoBottom = undefined;
  23534. this._cache.orthoTop = undefined;
  23535. this._cache.renderWidth = undefined;
  23536. this._cache.renderHeight = undefined;
  23537. };
  23538. /** @hidden */
  23539. Camera.prototype._updateCache = function (ignoreParentClass) {
  23540. if (!ignoreParentClass) {
  23541. _super.prototype._updateCache.call(this);
  23542. }
  23543. this._cache.position.copyFrom(this.position);
  23544. this._cache.upVector.copyFrom(this.upVector);
  23545. };
  23546. /** @hidden */
  23547. Camera.prototype._isSynchronized = function () {
  23548. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23549. };
  23550. /** @hidden */
  23551. Camera.prototype._isSynchronizedViewMatrix = function () {
  23552. if (!_super.prototype._isSynchronized.call(this)) {
  23553. return false;
  23554. }
  23555. return this._cache.position.equals(this.position)
  23556. && this._cache.upVector.equals(this.upVector)
  23557. && this.isSynchronizedWithParent();
  23558. };
  23559. /** @hidden */
  23560. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23561. var check = this._cache.mode === this.mode
  23562. && this._cache.minZ === this.minZ
  23563. && this._cache.maxZ === this.maxZ;
  23564. if (!check) {
  23565. return false;
  23566. }
  23567. var engine = this.getEngine();
  23568. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23569. check = this._cache.fov === this.fov
  23570. && this._cache.fovMode === this.fovMode
  23571. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23572. }
  23573. else {
  23574. check = this._cache.orthoLeft === this.orthoLeft
  23575. && this._cache.orthoRight === this.orthoRight
  23576. && this._cache.orthoBottom === this.orthoBottom
  23577. && this._cache.orthoTop === this.orthoTop
  23578. && this._cache.renderWidth === engine.getRenderWidth()
  23579. && this._cache.renderHeight === engine.getRenderHeight();
  23580. }
  23581. return check;
  23582. };
  23583. /**
  23584. * Attach the input controls to a specific dom element to get the input from.
  23585. * @param element Defines the element the controls should be listened from
  23586. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23587. */
  23588. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23589. };
  23590. /**
  23591. * Detach the current controls from the specified dom element.
  23592. * @param element Defines the element to stop listening the inputs from
  23593. */
  23594. Camera.prototype.detachControl = function (element) {
  23595. };
  23596. /**
  23597. * Update the camera state according to the different inputs gathered during the frame.
  23598. */
  23599. Camera.prototype.update = function () {
  23600. this._checkInputs();
  23601. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23602. this._updateRigCameras();
  23603. }
  23604. };
  23605. /** @hidden */
  23606. Camera.prototype._checkInputs = function () {
  23607. this.onAfterCheckInputsObservable.notifyObservers(this);
  23608. };
  23609. Object.defineProperty(Camera.prototype, "rigCameras", {
  23610. /** @hidden */
  23611. get: function () {
  23612. return this._rigCameras;
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23618. /**
  23619. * Gets the post process used by the rig cameras
  23620. */
  23621. get: function () {
  23622. return this._rigPostProcess;
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. /**
  23628. * Internal, gets the first post proces.
  23629. * @returns the first post process to be run on this camera.
  23630. */
  23631. Camera.prototype._getFirstPostProcess = function () {
  23632. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23633. if (this._postProcesses[ppIndex] !== null) {
  23634. return this._postProcesses[ppIndex];
  23635. }
  23636. }
  23637. return null;
  23638. };
  23639. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23640. // invalidate framebuffer
  23641. var firstPostProcess = this._getFirstPostProcess();
  23642. if (firstPostProcess) {
  23643. firstPostProcess.markTextureDirty();
  23644. }
  23645. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23646. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23647. var cam = this._rigCameras[i];
  23648. var rigPostProcess = cam._rigPostProcess;
  23649. // for VR rig, there does not have to be a post process
  23650. if (rigPostProcess) {
  23651. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23652. if (isPass) {
  23653. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23654. cam.isIntermediate = this._postProcesses.length === 0;
  23655. }
  23656. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23657. rigPostProcess.markTextureDirty();
  23658. }
  23659. else {
  23660. cam._postProcesses = this._postProcesses.slice(0);
  23661. }
  23662. }
  23663. };
  23664. /**
  23665. * Attach a post process to the camera.
  23666. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23667. * @param postProcess The post process to attach to the camera
  23668. * @param insertAt The position of the post process in case several of them are in use in the scene
  23669. * @returns the position the post process has been inserted at
  23670. */
  23671. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23672. if (insertAt === void 0) { insertAt = null; }
  23673. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23674. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23675. return 0;
  23676. }
  23677. if (insertAt == null || insertAt < 0) {
  23678. this._postProcesses.push(postProcess);
  23679. }
  23680. else if (this._postProcesses[insertAt] === null) {
  23681. this._postProcesses[insertAt] = postProcess;
  23682. }
  23683. else {
  23684. this._postProcesses.splice(insertAt, 0, postProcess);
  23685. }
  23686. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23687. return this._postProcesses.indexOf(postProcess);
  23688. };
  23689. /**
  23690. * Detach a post process to the camera.
  23691. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23692. * @param postProcess The post process to detach from the camera
  23693. */
  23694. Camera.prototype.detachPostProcess = function (postProcess) {
  23695. var idx = this._postProcesses.indexOf(postProcess);
  23696. if (idx !== -1) {
  23697. this._postProcesses[idx] = null;
  23698. }
  23699. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23700. };
  23701. /**
  23702. * Gets the current world matrix of the camera
  23703. */
  23704. Camera.prototype.getWorldMatrix = function () {
  23705. if (this._isSynchronizedViewMatrix()) {
  23706. return this._worldMatrix;
  23707. }
  23708. // Getting the the view matrix will also compute the world matrix.
  23709. this.getViewMatrix();
  23710. return this._worldMatrix;
  23711. };
  23712. /** @hidden */
  23713. Camera.prototype._getViewMatrix = function () {
  23714. return BABYLON.Matrix.Identity();
  23715. };
  23716. /**
  23717. * Gets the current view matrix of the camera.
  23718. * @param force forces the camera to recompute the matrix without looking at the cached state
  23719. * @returns the view matrix
  23720. */
  23721. Camera.prototype.getViewMatrix = function (force) {
  23722. if (!force && this._isSynchronizedViewMatrix()) {
  23723. return this._computedViewMatrix;
  23724. }
  23725. this.updateCache();
  23726. this._computedViewMatrix = this._getViewMatrix();
  23727. this._currentRenderId = this.getScene().getRenderId();
  23728. this._childRenderId = this._currentRenderId;
  23729. this._refreshFrustumPlanes = true;
  23730. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23731. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23732. }
  23733. this.onViewMatrixChangedObservable.notifyObservers(this);
  23734. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23735. return this._computedViewMatrix;
  23736. };
  23737. /**
  23738. * Freeze the projection matrix.
  23739. * It will prevent the cache check of the camera projection compute and can speed up perf
  23740. * if no parameter of the camera are meant to change
  23741. * @param projection Defines manually a projection if necessary
  23742. */
  23743. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23744. this._doNotComputeProjectionMatrix = true;
  23745. if (projection !== undefined) {
  23746. this._projectionMatrix = projection;
  23747. }
  23748. };
  23749. /**
  23750. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23751. */
  23752. Camera.prototype.unfreezeProjectionMatrix = function () {
  23753. this._doNotComputeProjectionMatrix = false;
  23754. };
  23755. /**
  23756. * Gets the current projection matrix of the camera.
  23757. * @param force forces the camera to recompute the matrix without looking at the cached state
  23758. * @returns the projection matrix
  23759. */
  23760. Camera.prototype.getProjectionMatrix = function (force) {
  23761. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23762. return this._projectionMatrix;
  23763. }
  23764. // Cache
  23765. this._cache.mode = this.mode;
  23766. this._cache.minZ = this.minZ;
  23767. this._cache.maxZ = this.maxZ;
  23768. // Matrix
  23769. this._refreshFrustumPlanes = true;
  23770. var engine = this.getEngine();
  23771. var scene = this.getScene();
  23772. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23773. this._cache.fov = this.fov;
  23774. this._cache.fovMode = this.fovMode;
  23775. this._cache.aspectRatio = engine.getAspectRatio(this);
  23776. if (this.minZ <= 0) {
  23777. this.minZ = 0.1;
  23778. }
  23779. if (scene.useRightHandedSystem) {
  23780. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23781. }
  23782. else {
  23783. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23784. }
  23785. }
  23786. else {
  23787. var halfWidth = engine.getRenderWidth() / 2.0;
  23788. var halfHeight = engine.getRenderHeight() / 2.0;
  23789. if (scene.useRightHandedSystem) {
  23790. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23791. }
  23792. else {
  23793. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23794. }
  23795. this._cache.orthoLeft = this.orthoLeft;
  23796. this._cache.orthoRight = this.orthoRight;
  23797. this._cache.orthoBottom = this.orthoBottom;
  23798. this._cache.orthoTop = this.orthoTop;
  23799. this._cache.renderWidth = engine.getRenderWidth();
  23800. this._cache.renderHeight = engine.getRenderHeight();
  23801. }
  23802. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23803. return this._projectionMatrix;
  23804. };
  23805. /**
  23806. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23807. * @returns a Matrix
  23808. */
  23809. Camera.prototype.getTransformationMatrix = function () {
  23810. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23811. return this._transformMatrix;
  23812. };
  23813. Camera.prototype._updateFrustumPlanes = function () {
  23814. if (!this._refreshFrustumPlanes) {
  23815. return;
  23816. }
  23817. this.getTransformationMatrix();
  23818. if (!this._frustumPlanes) {
  23819. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23820. }
  23821. else {
  23822. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23823. }
  23824. this._refreshFrustumPlanes = false;
  23825. };
  23826. /**
  23827. * Checks if a cullable object (mesh...) is in the camera frustum
  23828. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23829. * @param target The object to check
  23830. * @returns true if the object is in frustum otherwise false
  23831. */
  23832. Camera.prototype.isInFrustum = function (target) {
  23833. this._updateFrustumPlanes();
  23834. return target.isInFrustum(this._frustumPlanes);
  23835. };
  23836. /**
  23837. * Checks if a cullable object (mesh...) is in the camera frustum
  23838. * Unlike isInFrustum this cheks the full bounding box
  23839. * @param target The object to check
  23840. * @returns true if the object is in frustum otherwise false
  23841. */
  23842. Camera.prototype.isCompletelyInFrustum = function (target) {
  23843. this._updateFrustumPlanes();
  23844. return target.isCompletelyInFrustum(this._frustumPlanes);
  23845. };
  23846. /**
  23847. * Gets a ray in the forward direction from the camera.
  23848. * @param length Defines the length of the ray to create
  23849. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23850. * @param origin Defines the start point of the ray which defaults to the camera position
  23851. * @returns the forward ray
  23852. */
  23853. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23854. if (length === void 0) { length = 100; }
  23855. if (!transform) {
  23856. transform = this.getWorldMatrix();
  23857. }
  23858. if (!origin) {
  23859. origin = this.position;
  23860. }
  23861. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23862. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23863. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23864. return new BABYLON.Ray(origin, direction, length);
  23865. };
  23866. /**
  23867. * Releases resources associated with this node.
  23868. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23869. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23870. */
  23871. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23872. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23873. // Observables
  23874. this.onViewMatrixChangedObservable.clear();
  23875. this.onProjectionMatrixChangedObservable.clear();
  23876. this.onAfterCheckInputsObservable.clear();
  23877. this.onRestoreStateObservable.clear();
  23878. // Inputs
  23879. if (this.inputs) {
  23880. this.inputs.clear();
  23881. }
  23882. // Animations
  23883. this.getScene().stopAnimation(this);
  23884. // Remove from scene
  23885. this.getScene().removeCamera(this);
  23886. while (this._rigCameras.length > 0) {
  23887. var camera = this._rigCameras.pop();
  23888. if (camera) {
  23889. camera.dispose();
  23890. }
  23891. }
  23892. // Postprocesses
  23893. if (this._rigPostProcess) {
  23894. this._rigPostProcess.dispose(this);
  23895. this._rigPostProcess = null;
  23896. this._postProcesses = [];
  23897. }
  23898. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23899. this._rigPostProcess = null;
  23900. this._postProcesses = [];
  23901. }
  23902. else {
  23903. var i = this._postProcesses.length;
  23904. while (--i >= 0) {
  23905. var postProcess = this._postProcesses[i];
  23906. if (postProcess) {
  23907. postProcess.dispose(this);
  23908. }
  23909. }
  23910. }
  23911. // Render targets
  23912. var i = this.customRenderTargets.length;
  23913. while (--i >= 0) {
  23914. this.customRenderTargets[i].dispose();
  23915. }
  23916. this.customRenderTargets = [];
  23917. // Active Meshes
  23918. this._activeMeshes.dispose();
  23919. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23920. };
  23921. Object.defineProperty(Camera.prototype, "leftCamera", {
  23922. /**
  23923. * Gets the left camera of a rig setup in case of Rigged Camera
  23924. */
  23925. get: function () {
  23926. if (this._rigCameras.length < 1) {
  23927. return null;
  23928. }
  23929. return this._rigCameras[0];
  23930. },
  23931. enumerable: true,
  23932. configurable: true
  23933. });
  23934. Object.defineProperty(Camera.prototype, "rightCamera", {
  23935. /**
  23936. * Gets the right camera of a rig setup in case of Rigged Camera
  23937. */
  23938. get: function () {
  23939. if (this._rigCameras.length < 2) {
  23940. return null;
  23941. }
  23942. return this._rigCameras[1];
  23943. },
  23944. enumerable: true,
  23945. configurable: true
  23946. });
  23947. /**
  23948. * Gets the left camera target of a rig setup in case of Rigged Camera
  23949. * @returns the target position
  23950. */
  23951. Camera.prototype.getLeftTarget = function () {
  23952. if (this._rigCameras.length < 1) {
  23953. return null;
  23954. }
  23955. return this._rigCameras[0].getTarget();
  23956. };
  23957. /**
  23958. * Gets the right camera target of a rig setup in case of Rigged Camera
  23959. * @returns the target position
  23960. */
  23961. Camera.prototype.getRightTarget = function () {
  23962. if (this._rigCameras.length < 2) {
  23963. return null;
  23964. }
  23965. return this._rigCameras[1].getTarget();
  23966. };
  23967. /**
  23968. * @hidden
  23969. */
  23970. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23971. if (this.cameraRigMode === mode) {
  23972. return;
  23973. }
  23974. while (this._rigCameras.length > 0) {
  23975. var camera = this._rigCameras.pop();
  23976. if (camera) {
  23977. camera.dispose();
  23978. }
  23979. }
  23980. this.cameraRigMode = mode;
  23981. this._cameraRigParams = {};
  23982. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23983. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23984. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23985. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23986. // create the rig cameras, unless none
  23987. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23988. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23989. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23990. if (leftCamera && rightCamera) {
  23991. this._rigCameras.push(leftCamera);
  23992. this._rigCameras.push(rightCamera);
  23993. }
  23994. }
  23995. switch (this.cameraRigMode) {
  23996. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23997. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23998. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23999. break;
  24000. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24001. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24002. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24003. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24004. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24005. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24006. break;
  24007. case Camera.RIG_MODE_VR:
  24008. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24009. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24010. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24011. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24012. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24013. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24014. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24015. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24016. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24017. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24018. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24019. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24020. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24021. if (metrics.compensateDistortion) {
  24022. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24023. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24024. }
  24025. break;
  24026. case Camera.RIG_MODE_WEBVR:
  24027. if (rigParams.vrDisplay) {
  24028. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24029. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24030. //Left eye
  24031. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24032. this._rigCameras[0].setCameraRigParameter("left", true);
  24033. //leaving this for future reference
  24034. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24035. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24036. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24037. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24038. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24039. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24040. this._rigCameras[0].parent = this;
  24041. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24042. //Right eye
  24043. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24044. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24045. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24046. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24047. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24048. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24049. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24050. this._rigCameras[1].parent = this;
  24051. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24052. if (Camera.UseAlternateWebVRRendering) {
  24053. this._rigCameras[1]._skipRendering = true;
  24054. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24055. }
  24056. }
  24057. break;
  24058. }
  24059. this._cascadePostProcessesToRigCams();
  24060. this.update();
  24061. };
  24062. Camera.prototype._getVRProjectionMatrix = function () {
  24063. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24064. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24065. return this._projectionMatrix;
  24066. };
  24067. Camera.prototype._updateCameraRotationMatrix = function () {
  24068. //Here for WebVR
  24069. };
  24070. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24071. //Here for WebVR
  24072. };
  24073. /**
  24074. * This function MUST be overwritten by the different WebVR cameras available.
  24075. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24076. */
  24077. Camera.prototype._getWebVRProjectionMatrix = function () {
  24078. return BABYLON.Matrix.Identity();
  24079. };
  24080. /**
  24081. * This function MUST be overwritten by the different WebVR cameras available.
  24082. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24083. */
  24084. Camera.prototype._getWebVRViewMatrix = function () {
  24085. return BABYLON.Matrix.Identity();
  24086. };
  24087. /** @hidden */
  24088. Camera.prototype.setCameraRigParameter = function (name, value) {
  24089. if (!this._cameraRigParams) {
  24090. this._cameraRigParams = {};
  24091. }
  24092. this._cameraRigParams[name] = value;
  24093. //provisionnally:
  24094. if (name === "interaxialDistance") {
  24095. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24096. }
  24097. };
  24098. /**
  24099. * needs to be overridden by children so sub has required properties to be copied
  24100. * @hidden
  24101. */
  24102. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24103. return null;
  24104. };
  24105. /**
  24106. * May need to be overridden by children
  24107. * @hidden
  24108. */
  24109. Camera.prototype._updateRigCameras = function () {
  24110. for (var i = 0; i < this._rigCameras.length; i++) {
  24111. this._rigCameras[i].minZ = this.minZ;
  24112. this._rigCameras[i].maxZ = this.maxZ;
  24113. this._rigCameras[i].fov = this.fov;
  24114. }
  24115. // only update viewport when ANAGLYPH
  24116. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24117. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24118. }
  24119. };
  24120. /** @hidden */
  24121. Camera.prototype._setupInputs = function () {
  24122. };
  24123. /**
  24124. * Serialiaze the camera setup to a json represention
  24125. * @returns the JSON representation
  24126. */
  24127. Camera.prototype.serialize = function () {
  24128. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24129. // Type
  24130. serializationObject.type = this.getClassName();
  24131. // Parent
  24132. if (this.parent) {
  24133. serializationObject.parentId = this.parent.id;
  24134. }
  24135. if (this.inputs) {
  24136. this.inputs.serialize(serializationObject);
  24137. }
  24138. // Animations
  24139. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24140. serializationObject.ranges = this.serializeAnimationRanges();
  24141. return serializationObject;
  24142. };
  24143. /**
  24144. * Clones the current camera.
  24145. * @param name The cloned camera name
  24146. * @returns the cloned camera
  24147. */
  24148. Camera.prototype.clone = function (name) {
  24149. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24150. };
  24151. /**
  24152. * Gets the direction of the camera relative to a given local axis.
  24153. * @param localAxis Defines the reference axis to provide a relative direction.
  24154. * @return the direction
  24155. */
  24156. Camera.prototype.getDirection = function (localAxis) {
  24157. var result = BABYLON.Vector3.Zero();
  24158. this.getDirectionToRef(localAxis, result);
  24159. return result;
  24160. };
  24161. /**
  24162. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24163. * @param localAxis Defines the reference axis to provide a relative direction.
  24164. * @param result Defines the vector to store the result in
  24165. */
  24166. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24167. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24168. };
  24169. /**
  24170. * Gets a camera constructor for a given camera type
  24171. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24172. * @param name The name of the camera the result will be able to instantiate
  24173. * @param scene The scene the result will construct the camera in
  24174. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24175. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24176. * @returns a factory method to construc the camera
  24177. */
  24178. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24179. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24180. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24181. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24182. interaxial_distance: interaxial_distance,
  24183. isStereoscopicSideBySide: isStereoscopicSideBySide
  24184. });
  24185. if (constructorFunc) {
  24186. return constructorFunc;
  24187. }
  24188. // Default to universal camera
  24189. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24190. };
  24191. /**
  24192. * Compute the world matrix of the camera.
  24193. * @returns the camera workd matrix
  24194. */
  24195. Camera.prototype.computeWorldMatrix = function () {
  24196. return this.getWorldMatrix();
  24197. };
  24198. /**
  24199. * Parse a JSON and creates the camera from the parsed information
  24200. * @param parsedCamera The JSON to parse
  24201. * @param scene The scene to instantiate the camera in
  24202. * @returns the newly constructed camera
  24203. */
  24204. Camera.Parse = function (parsedCamera, scene) {
  24205. var type = parsedCamera.type;
  24206. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24207. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24208. // Parent
  24209. if (parsedCamera.parentId) {
  24210. camera._waitingParentId = parsedCamera.parentId;
  24211. }
  24212. //If camera has an input manager, let it parse inputs settings
  24213. if (camera.inputs) {
  24214. camera.inputs.parse(parsedCamera);
  24215. camera._setupInputs();
  24216. }
  24217. if (camera.setPosition) { // need to force position
  24218. camera.position.copyFromFloats(0, 0, 0);
  24219. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24220. }
  24221. // Target
  24222. if (parsedCamera.target) {
  24223. if (camera.setTarget) {
  24224. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24225. }
  24226. }
  24227. // Apply 3d rig, when found
  24228. if (parsedCamera.cameraRigMode) {
  24229. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24230. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24231. }
  24232. // Animations
  24233. if (parsedCamera.animations) {
  24234. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24235. var parsedAnimation = parsedCamera.animations[animationIndex];
  24236. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24237. }
  24238. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24239. }
  24240. if (parsedCamera.autoAnimate) {
  24241. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24242. }
  24243. return camera;
  24244. };
  24245. /**
  24246. * This is the default projection mode used by the cameras.
  24247. * It helps recreating a feeling of perspective and better appreciate depth.
  24248. * This is the best way to simulate real life cameras.
  24249. */
  24250. Camera.PERSPECTIVE_CAMERA = 0;
  24251. /**
  24252. * This helps creating camera with an orthographic mode.
  24253. * 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.
  24254. */
  24255. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24256. /**
  24257. * This is the default FOV mode for perspective cameras.
  24258. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24259. */
  24260. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24261. /**
  24262. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24263. */
  24264. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24265. /**
  24266. * This specifies ther is no need for a camera rig.
  24267. * Basically only one eye is rendered corresponding to the camera.
  24268. */
  24269. Camera.RIG_MODE_NONE = 0;
  24270. /**
  24271. * Simulates a camera Rig with one blue eye and one red eye.
  24272. * This can be use with 3d blue and red glasses.
  24273. */
  24274. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24275. /**
  24276. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24277. */
  24278. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24279. /**
  24280. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24281. */
  24282. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24283. /**
  24284. * Defines that both eyes of the camera will be rendered over under each other.
  24285. */
  24286. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24287. /**
  24288. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24289. */
  24290. Camera.RIG_MODE_VR = 20;
  24291. /**
  24292. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24293. */
  24294. Camera.RIG_MODE_WEBVR = 21;
  24295. /**
  24296. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24297. */
  24298. Camera.RIG_MODE_CUSTOM = 22;
  24299. /**
  24300. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24301. */
  24302. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24303. /**
  24304. * @hidden
  24305. * Might be removed once multiview will be a thing
  24306. */
  24307. Camera.UseAlternateWebVRRendering = false;
  24308. __decorate([
  24309. BABYLON.serializeAsVector3()
  24310. ], Camera.prototype, "position", void 0);
  24311. __decorate([
  24312. BABYLON.serializeAsVector3()
  24313. ], Camera.prototype, "upVector", void 0);
  24314. __decorate([
  24315. BABYLON.serialize()
  24316. ], Camera.prototype, "orthoLeft", void 0);
  24317. __decorate([
  24318. BABYLON.serialize()
  24319. ], Camera.prototype, "orthoRight", void 0);
  24320. __decorate([
  24321. BABYLON.serialize()
  24322. ], Camera.prototype, "orthoBottom", void 0);
  24323. __decorate([
  24324. BABYLON.serialize()
  24325. ], Camera.prototype, "orthoTop", void 0);
  24326. __decorate([
  24327. BABYLON.serialize()
  24328. ], Camera.prototype, "fov", void 0);
  24329. __decorate([
  24330. BABYLON.serialize()
  24331. ], Camera.prototype, "minZ", void 0);
  24332. __decorate([
  24333. BABYLON.serialize()
  24334. ], Camera.prototype, "maxZ", void 0);
  24335. __decorate([
  24336. BABYLON.serialize()
  24337. ], Camera.prototype, "inertia", void 0);
  24338. __decorate([
  24339. BABYLON.serialize()
  24340. ], Camera.prototype, "mode", void 0);
  24341. __decorate([
  24342. BABYLON.serialize()
  24343. ], Camera.prototype, "layerMask", void 0);
  24344. __decorate([
  24345. BABYLON.serialize()
  24346. ], Camera.prototype, "fovMode", void 0);
  24347. __decorate([
  24348. BABYLON.serialize()
  24349. ], Camera.prototype, "cameraRigMode", void 0);
  24350. __decorate([
  24351. BABYLON.serialize()
  24352. ], Camera.prototype, "interaxialDistance", void 0);
  24353. __decorate([
  24354. BABYLON.serialize()
  24355. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24356. return Camera;
  24357. }(BABYLON.Node));
  24358. BABYLON.Camera = Camera;
  24359. })(BABYLON || (BABYLON = {}));
  24360. //# sourceMappingURL=babylon.camera.js.map
  24361. var BABYLON;
  24362. (function (BABYLON) {
  24363. /**
  24364. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24365. * It is enable to manage the different groups as well as the different necessary sort functions.
  24366. * This should not be used directly aside of the few static configurations
  24367. */
  24368. var RenderingManager = /** @class */ (function () {
  24369. /**
  24370. * Instantiates a new rendering group for a particular scene
  24371. * @param scene Defines the scene the groups belongs to
  24372. */
  24373. function RenderingManager(scene) {
  24374. /**
  24375. * @hidden
  24376. */
  24377. this._useSceneAutoClearSetup = false;
  24378. this._renderingGroups = new Array();
  24379. this._autoClearDepthStencil = {};
  24380. this._customOpaqueSortCompareFn = {};
  24381. this._customAlphaTestSortCompareFn = {};
  24382. this._customTransparentSortCompareFn = {};
  24383. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24384. this._scene = scene;
  24385. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24386. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24387. }
  24388. }
  24389. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24390. if (depth === void 0) { depth = true; }
  24391. if (stencil === void 0) { stencil = true; }
  24392. if (this._depthStencilBufferAlreadyCleaned) {
  24393. return;
  24394. }
  24395. this._scene.getEngine().clear(null, false, depth, stencil);
  24396. this._depthStencilBufferAlreadyCleaned = true;
  24397. };
  24398. /**
  24399. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24400. * @hidden
  24401. */
  24402. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24403. // Update the observable context (not null as it only goes away on dispose)
  24404. var info = this._renderingGroupInfo;
  24405. info.scene = this._scene;
  24406. info.camera = this._scene.activeCamera;
  24407. // Dispatch sprites
  24408. if (this._scene.spriteManagers && renderSprites) {
  24409. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24410. var manager = this._scene.spriteManagers[index];
  24411. this.dispatchSprites(manager);
  24412. }
  24413. }
  24414. // Render
  24415. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24416. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24417. var renderingGroup = this._renderingGroups[index];
  24418. if (!renderingGroup) {
  24419. continue;
  24420. }
  24421. var renderingGroupMask = Math.pow(2, index);
  24422. info.renderingGroupId = index;
  24423. // Before Observable
  24424. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24425. // Clear depth/stencil if needed
  24426. if (RenderingManager.AUTOCLEAR) {
  24427. var autoClear = this._useSceneAutoClearSetup ?
  24428. this._scene.getAutoClearDepthStencilSetup(index) :
  24429. this._autoClearDepthStencil[index];
  24430. if (autoClear && autoClear.autoClear) {
  24431. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24432. }
  24433. }
  24434. // Render
  24435. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24436. var step = _a[_i];
  24437. step.action(index);
  24438. }
  24439. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24440. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24441. var step = _c[_b];
  24442. step.action(index);
  24443. }
  24444. // After Observable
  24445. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24446. }
  24447. };
  24448. /**
  24449. * Resets the different information of the group to prepare a new frame
  24450. * @hidden
  24451. */
  24452. RenderingManager.prototype.reset = function () {
  24453. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24454. var renderingGroup = this._renderingGroups[index];
  24455. if (renderingGroup) {
  24456. renderingGroup.prepare();
  24457. }
  24458. }
  24459. };
  24460. /**
  24461. * Dispose and release the group and its associated resources.
  24462. * @hidden
  24463. */
  24464. RenderingManager.prototype.dispose = function () {
  24465. this.freeRenderingGroups();
  24466. this._renderingGroups.length = 0;
  24467. this._renderingGroupInfo = null;
  24468. };
  24469. /**
  24470. * Clear the info related to rendering groups preventing retention points during dispose.
  24471. */
  24472. RenderingManager.prototype.freeRenderingGroups = function () {
  24473. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24474. var renderingGroup = this._renderingGroups[index];
  24475. if (renderingGroup) {
  24476. renderingGroup.dispose();
  24477. }
  24478. }
  24479. };
  24480. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24481. if (this._renderingGroups[renderingGroupId] === undefined) {
  24482. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24483. }
  24484. };
  24485. /**
  24486. * Add a sprite manager to the rendering manager in order to render it this frame.
  24487. * @param spriteManager Define the sprite manager to render
  24488. */
  24489. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24490. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24491. this._prepareRenderingGroup(renderingGroupId);
  24492. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24493. };
  24494. /**
  24495. * Add a particle system to the rendering manager in order to render it this frame.
  24496. * @param particleSystem Define the particle system to render
  24497. */
  24498. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24499. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24500. this._prepareRenderingGroup(renderingGroupId);
  24501. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24502. };
  24503. /**
  24504. * Add a submesh to the manager in order to render it this frame
  24505. * @param subMesh The submesh to dispatch
  24506. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24507. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24508. */
  24509. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24510. if (mesh === undefined) {
  24511. mesh = subMesh.getMesh();
  24512. }
  24513. var renderingGroupId = mesh.renderingGroupId || 0;
  24514. this._prepareRenderingGroup(renderingGroupId);
  24515. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24516. };
  24517. /**
  24518. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24519. * This allowed control for front to back rendering or reversly depending of the special needs.
  24520. *
  24521. * @param renderingGroupId The rendering group id corresponding to its index
  24522. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24523. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24524. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24525. */
  24526. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24527. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24528. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24529. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24530. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24531. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24532. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24533. if (this._renderingGroups[renderingGroupId]) {
  24534. var group = this._renderingGroups[renderingGroupId];
  24535. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24536. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24537. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24538. }
  24539. };
  24540. /**
  24541. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24542. *
  24543. * @param renderingGroupId The rendering group id corresponding to its index
  24544. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24545. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24546. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24547. */
  24548. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24549. if (depth === void 0) { depth = true; }
  24550. if (stencil === void 0) { stencil = true; }
  24551. this._autoClearDepthStencil[renderingGroupId] = {
  24552. autoClear: autoClearDepthStencil,
  24553. depth: depth,
  24554. stencil: stencil
  24555. };
  24556. };
  24557. /**
  24558. * Gets the current auto clear configuration for one rendering group of the rendering
  24559. * manager.
  24560. * @param index the rendering group index to get the information for
  24561. * @returns The auto clear setup for the requested rendering group
  24562. */
  24563. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24564. return this._autoClearDepthStencil[index];
  24565. };
  24566. /**
  24567. * The max id used for rendering groups (not included)
  24568. */
  24569. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24570. /**
  24571. * The min id used for rendering groups (included)
  24572. */
  24573. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24574. /**
  24575. * Used to globally prevent autoclearing scenes.
  24576. */
  24577. RenderingManager.AUTOCLEAR = true;
  24578. return RenderingManager;
  24579. }());
  24580. BABYLON.RenderingManager = RenderingManager;
  24581. })(BABYLON || (BABYLON = {}));
  24582. //# sourceMappingURL=babylon.renderingManager.js.map
  24583. var BABYLON;
  24584. (function (BABYLON) {
  24585. /**
  24586. * This represents the object necessary to create a rendering group.
  24587. * This is exclusively used and created by the rendering manager.
  24588. * To modify the behavior, you use the available helpers in your scene or meshes.
  24589. * @hidden
  24590. */
  24591. var RenderingGroup = /** @class */ (function () {
  24592. /**
  24593. * Creates a new rendering group.
  24594. * @param index The rendering group index
  24595. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24596. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24597. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24598. */
  24599. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24600. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24601. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24602. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24603. this.index = index;
  24604. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24605. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24606. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24607. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24608. this._particleSystems = new BABYLON.SmartArray(256);
  24609. this._spriteManagers = new BABYLON.SmartArray(256);
  24610. this._edgesRenderers = new BABYLON.SmartArray(16);
  24611. this._scene = scene;
  24612. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24613. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24614. this.transparentSortCompareFn = transparentSortCompareFn;
  24615. }
  24616. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24617. /**
  24618. * Set the opaque sort comparison function.
  24619. * If null the sub meshes will be render in the order they were created
  24620. */
  24621. set: function (value) {
  24622. this._opaqueSortCompareFn = value;
  24623. if (value) {
  24624. this._renderOpaque = this.renderOpaqueSorted;
  24625. }
  24626. else {
  24627. this._renderOpaque = RenderingGroup.renderUnsorted;
  24628. }
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24634. /**
  24635. * Set the alpha test sort comparison function.
  24636. * If null the sub meshes will be render in the order they were created
  24637. */
  24638. set: function (value) {
  24639. this._alphaTestSortCompareFn = value;
  24640. if (value) {
  24641. this._renderAlphaTest = this.renderAlphaTestSorted;
  24642. }
  24643. else {
  24644. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24645. }
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24651. /**
  24652. * Set the transparent sort comparison function.
  24653. * If null the sub meshes will be render in the order they were created
  24654. */
  24655. set: function (value) {
  24656. if (value) {
  24657. this._transparentSortCompareFn = value;
  24658. }
  24659. else {
  24660. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24661. }
  24662. this._renderTransparent = this.renderTransparentSorted;
  24663. },
  24664. enumerable: true,
  24665. configurable: true
  24666. });
  24667. /**
  24668. * Render all the sub meshes contained in the group.
  24669. * @param customRenderFunction Used to override the default render behaviour of the group.
  24670. * @returns true if rendered some submeshes.
  24671. */
  24672. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24673. if (customRenderFunction) {
  24674. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24675. return;
  24676. }
  24677. var engine = this._scene.getEngine();
  24678. // Depth only
  24679. if (this._depthOnlySubMeshes.length !== 0) {
  24680. engine.setColorWrite(false);
  24681. this._renderAlphaTest(this._depthOnlySubMeshes);
  24682. engine.setColorWrite(true);
  24683. }
  24684. // Opaque
  24685. if (this._opaqueSubMeshes.length !== 0) {
  24686. this._renderOpaque(this._opaqueSubMeshes);
  24687. }
  24688. // Alpha test
  24689. if (this._alphaTestSubMeshes.length !== 0) {
  24690. this._renderAlphaTest(this._alphaTestSubMeshes);
  24691. }
  24692. var stencilState = engine.getStencilBuffer();
  24693. engine.setStencilBuffer(false);
  24694. // Sprites
  24695. if (renderSprites) {
  24696. this._renderSprites();
  24697. }
  24698. // Particles
  24699. if (renderParticles) {
  24700. this._renderParticles(activeMeshes);
  24701. }
  24702. if (this.onBeforeTransparentRendering) {
  24703. this.onBeforeTransparentRendering();
  24704. }
  24705. // Transparent
  24706. if (this._transparentSubMeshes.length !== 0) {
  24707. this._renderTransparent(this._transparentSubMeshes);
  24708. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24709. }
  24710. // Set back stencil to false in case it changes before the edge renderer.
  24711. engine.setStencilBuffer(false);
  24712. // Edges
  24713. if (this._edgesRenderers.length) {
  24714. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24715. this._edgesRenderers.data[edgesRendererIndex].render();
  24716. }
  24717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24718. }
  24719. // Restore Stencil state.
  24720. engine.setStencilBuffer(stencilState);
  24721. };
  24722. /**
  24723. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24724. * @param subMeshes The submeshes to render
  24725. */
  24726. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24727. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24728. };
  24729. /**
  24730. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24731. * @param subMeshes The submeshes to render
  24732. */
  24733. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24734. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24735. };
  24736. /**
  24737. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24738. * @param subMeshes The submeshes to render
  24739. */
  24740. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24741. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24742. };
  24743. /**
  24744. * Renders the submeshes in a specified order.
  24745. * @param subMeshes The submeshes to sort before render
  24746. * @param sortCompareFn The comparison function use to sort
  24747. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24748. * @param transparent Specifies to activate blending if true
  24749. */
  24750. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24751. var subIndex = 0;
  24752. var subMesh;
  24753. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24754. for (; subIndex < subMeshes.length; subIndex++) {
  24755. subMesh = subMeshes.data[subIndex];
  24756. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24757. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24758. }
  24759. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24760. if (sortCompareFn) {
  24761. sortedArray.sort(sortCompareFn);
  24762. }
  24763. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24764. subMesh = sortedArray[subIndex];
  24765. if (transparent) {
  24766. var material = subMesh.getMaterial();
  24767. if (material && material.needDepthPrePass) {
  24768. var engine = material.getScene().getEngine();
  24769. engine.setColorWrite(false);
  24770. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24771. subMesh.render(false);
  24772. engine.setColorWrite(true);
  24773. }
  24774. }
  24775. subMesh.render(transparent);
  24776. }
  24777. };
  24778. /**
  24779. * Renders the submeshes in the order they were dispatched (no sort applied).
  24780. * @param subMeshes The submeshes to render
  24781. */
  24782. RenderingGroup.renderUnsorted = function (subMeshes) {
  24783. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24784. var submesh = subMeshes.data[subIndex];
  24785. submesh.render(false);
  24786. }
  24787. };
  24788. /**
  24789. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24790. * are rendered back to front if in the same alpha index.
  24791. *
  24792. * @param a The first submesh
  24793. * @param b The second submesh
  24794. * @returns The result of the comparison
  24795. */
  24796. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24797. // Alpha index first
  24798. if (a._alphaIndex > b._alphaIndex) {
  24799. return 1;
  24800. }
  24801. if (a._alphaIndex < b._alphaIndex) {
  24802. return -1;
  24803. }
  24804. // Then distance to camera
  24805. return RenderingGroup.backToFrontSortCompare(a, b);
  24806. };
  24807. /**
  24808. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24809. * are rendered back to front.
  24810. *
  24811. * @param a The first submesh
  24812. * @param b The second submesh
  24813. * @returns The result of the comparison
  24814. */
  24815. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24816. // Then distance to camera
  24817. if (a._distanceToCamera < b._distanceToCamera) {
  24818. return 1;
  24819. }
  24820. if (a._distanceToCamera > b._distanceToCamera) {
  24821. return -1;
  24822. }
  24823. return 0;
  24824. };
  24825. /**
  24826. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24827. * are rendered front to back (prevent overdraw).
  24828. *
  24829. * @param a The first submesh
  24830. * @param b The second submesh
  24831. * @returns The result of the comparison
  24832. */
  24833. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24834. // Then distance to camera
  24835. if (a._distanceToCamera < b._distanceToCamera) {
  24836. return -1;
  24837. }
  24838. if (a._distanceToCamera > b._distanceToCamera) {
  24839. return 1;
  24840. }
  24841. return 0;
  24842. };
  24843. /**
  24844. * Resets the different lists of submeshes to prepare a new frame.
  24845. */
  24846. RenderingGroup.prototype.prepare = function () {
  24847. this._opaqueSubMeshes.reset();
  24848. this._transparentSubMeshes.reset();
  24849. this._alphaTestSubMeshes.reset();
  24850. this._depthOnlySubMeshes.reset();
  24851. this._particleSystems.reset();
  24852. this._spriteManagers.reset();
  24853. this._edgesRenderers.reset();
  24854. };
  24855. RenderingGroup.prototype.dispose = function () {
  24856. this._opaqueSubMeshes.dispose();
  24857. this._transparentSubMeshes.dispose();
  24858. this._alphaTestSubMeshes.dispose();
  24859. this._depthOnlySubMeshes.dispose();
  24860. this._particleSystems.dispose();
  24861. this._spriteManagers.dispose();
  24862. this._edgesRenderers.dispose();
  24863. };
  24864. /**
  24865. * Inserts the submesh in its correct queue depending on its material.
  24866. * @param subMesh The submesh to dispatch
  24867. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24868. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24869. */
  24870. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24871. // Get mesh and materials if not provided
  24872. if (mesh === undefined) {
  24873. mesh = subMesh.getMesh();
  24874. }
  24875. if (material === undefined) {
  24876. material = subMesh.getMaterial();
  24877. }
  24878. if (material === null || material === undefined) {
  24879. return;
  24880. }
  24881. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24882. this._transparentSubMeshes.push(subMesh);
  24883. }
  24884. else if (material.needAlphaTesting()) { // Alpha test
  24885. if (material.needDepthPrePass) {
  24886. this._depthOnlySubMeshes.push(subMesh);
  24887. }
  24888. this._alphaTestSubMeshes.push(subMesh);
  24889. }
  24890. else {
  24891. if (material.needDepthPrePass) {
  24892. this._depthOnlySubMeshes.push(subMesh);
  24893. }
  24894. this._opaqueSubMeshes.push(subMesh); // Opaque
  24895. }
  24896. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24897. this._edgesRenderers.push(mesh._edgesRenderer);
  24898. }
  24899. };
  24900. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24901. this._spriteManagers.push(spriteManager);
  24902. };
  24903. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24904. this._particleSystems.push(particleSystem);
  24905. };
  24906. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24907. if (this._particleSystems.length === 0) {
  24908. return;
  24909. }
  24910. // Particles
  24911. var activeCamera = this._scene.activeCamera;
  24912. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24913. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24914. var particleSystem = this._particleSystems.data[particleIndex];
  24915. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24916. continue;
  24917. }
  24918. var emitter = particleSystem.emitter;
  24919. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24920. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24921. }
  24922. }
  24923. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24924. };
  24925. RenderingGroup.prototype._renderSprites = function () {
  24926. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24927. return;
  24928. }
  24929. // Sprites
  24930. var activeCamera = this._scene.activeCamera;
  24931. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24932. for (var id = 0; id < this._spriteManagers.length; id++) {
  24933. var spriteManager = this._spriteManagers.data[id];
  24934. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24935. spriteManager.render();
  24936. }
  24937. }
  24938. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24939. };
  24940. return RenderingGroup;
  24941. }());
  24942. BABYLON.RenderingGroup = RenderingGroup;
  24943. })(BABYLON || (BABYLON = {}));
  24944. //# sourceMappingURL=babylon.renderingGroup.js.map
  24945. var BABYLON;
  24946. (function (BABYLON) {
  24947. /**
  24948. * Groups all the scene component constants in one place to ease maintenance.
  24949. * @hidden
  24950. */
  24951. var SceneComponentConstants = /** @class */ (function () {
  24952. function SceneComponentConstants() {
  24953. }
  24954. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24955. SceneComponentConstants.NAME_LAYER = "Layer";
  24956. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24957. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24958. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24959. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24960. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24961. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24962. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24963. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24964. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24965. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24966. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24967. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24968. SceneComponentConstants.NAME_OCTREE = "Octree";
  24969. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24970. SceneComponentConstants.NAME_AUDIO = "Audio";
  24971. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24972. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24973. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24974. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24975. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24976. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24977. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24978. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24979. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24980. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24981. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24982. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24983. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24984. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24985. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24986. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24987. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24988. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24989. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24990. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24991. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24992. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24993. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24994. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24995. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24996. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24997. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24998. return SceneComponentConstants;
  24999. }());
  25000. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25001. /**
  25002. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25003. * @hidden
  25004. */
  25005. var Stage = /** @class */ (function (_super) {
  25006. __extends(Stage, _super);
  25007. /**
  25008. * Hide ctor from the rest of the world.
  25009. * @param items The items to add.
  25010. */
  25011. function Stage(items) {
  25012. return _super.apply(this, items) || this;
  25013. }
  25014. /**
  25015. * Creates a new Stage.
  25016. * @returns A new instance of a Stage
  25017. */
  25018. Stage.Create = function () {
  25019. return Object.create(Stage.prototype);
  25020. };
  25021. /**
  25022. * Registers a step in an ordered way in the targeted stage.
  25023. * @param index Defines the position to register the step in
  25024. * @param component Defines the component attached to the step
  25025. * @param action Defines the action to launch during the step
  25026. */
  25027. Stage.prototype.registerStep = function (index, component, action) {
  25028. var i = 0;
  25029. var maxIndex = Number.MAX_VALUE;
  25030. for (; i < this.length; i++) {
  25031. var step = this[i];
  25032. maxIndex = step.index;
  25033. if (index < maxIndex) {
  25034. break;
  25035. }
  25036. }
  25037. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25038. };
  25039. /**
  25040. * Clears all the steps from the stage.
  25041. */
  25042. Stage.prototype.clear = function () {
  25043. this.length = 0;
  25044. };
  25045. return Stage;
  25046. }(Array));
  25047. BABYLON.Stage = Stage;
  25048. })(BABYLON || (BABYLON = {}));
  25049. //# sourceMappingURL=babylon.sceneComponent.js.map
  25050. var BABYLON;
  25051. (function (BABYLON) {
  25052. /**
  25053. * Base class of the scene acting as a container for the different elements composing a scene.
  25054. * This class is dynamically extended by the different components of the scene increasing
  25055. * flexibility and reducing coupling
  25056. */
  25057. var AbstractScene = /** @class */ (function () {
  25058. function AbstractScene() {
  25059. /**
  25060. * Gets the list of root nodes (ie. nodes with no parent)
  25061. */
  25062. this.rootNodes = new Array();
  25063. /** All of the cameras added to this scene
  25064. * @see http://doc.babylonjs.com/babylon101/cameras
  25065. */
  25066. this.cameras = new Array();
  25067. /**
  25068. * All of the lights added to this scene
  25069. * @see http://doc.babylonjs.com/babylon101/lights
  25070. */
  25071. this.lights = new Array();
  25072. /**
  25073. * All of the (abstract) meshes added to this scene
  25074. */
  25075. this.meshes = new Array();
  25076. /**
  25077. * The list of skeletons added to the scene
  25078. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25079. */
  25080. this.skeletons = new Array();
  25081. /**
  25082. * All of the particle systems added to this scene
  25083. * @see http://doc.babylonjs.com/babylon101/particles
  25084. */
  25085. this.particleSystems = new Array();
  25086. /**
  25087. * Gets a list of Animations associated with the scene
  25088. */
  25089. this.animations = [];
  25090. /**
  25091. * All of the animation groups added to this scene
  25092. * @see http://doc.babylonjs.com/how_to/group
  25093. */
  25094. this.animationGroups = new Array();
  25095. /**
  25096. * All of the multi-materials added to this scene
  25097. * @see http://doc.babylonjs.com/how_to/multi_materials
  25098. */
  25099. this.multiMaterials = new Array();
  25100. /**
  25101. * All of the materials added to this scene
  25102. * In the context of a Scene, it is not supposed to be modified manually.
  25103. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25104. * Note also that the order of the Material wihin the array is not significant and might change.
  25105. * @see http://doc.babylonjs.com/babylon101/materials
  25106. */
  25107. this.materials = new Array();
  25108. /**
  25109. * The list of morph target managers added to the scene
  25110. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25111. */
  25112. this.morphTargetManagers = new Array();
  25113. /**
  25114. * The list of geometries used in the scene.
  25115. */
  25116. this.geometries = new Array();
  25117. /**
  25118. * All of the tranform nodes added to this scene
  25119. * In the context of a Scene, it is not supposed to be modified manually.
  25120. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25121. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25122. * @see http://doc.babylonjs.com/how_to/transformnode
  25123. */
  25124. this.transformNodes = new Array();
  25125. /**
  25126. * ActionManagers available on the scene.
  25127. */
  25128. this.actionManagers = new Array();
  25129. /**
  25130. * Textures to keep.
  25131. */
  25132. this.textures = new Array();
  25133. }
  25134. /**
  25135. * Adds a parser in the list of available ones
  25136. * @param name Defines the name of the parser
  25137. * @param parser Defines the parser to add
  25138. */
  25139. AbstractScene.AddParser = function (name, parser) {
  25140. this._BabylonFileParsers[name] = parser;
  25141. };
  25142. /**
  25143. * Gets a general parser from the list of avaialble ones
  25144. * @param name Defines the name of the parser
  25145. * @returns the requested parser or null
  25146. */
  25147. AbstractScene.GetParser = function (name) {
  25148. if (this._BabylonFileParsers[name]) {
  25149. return this._BabylonFileParsers[name];
  25150. }
  25151. return null;
  25152. };
  25153. /**
  25154. * Adds n individual parser in the list of available ones
  25155. * @param name Defines the name of the parser
  25156. * @param parser Defines the parser to add
  25157. */
  25158. AbstractScene.AddIndividualParser = function (name, parser) {
  25159. this._IndividualBabylonFileParsers[name] = parser;
  25160. };
  25161. /**
  25162. * Gets an individual parser from the list of avaialble ones
  25163. * @param name Defines the name of the parser
  25164. * @returns the requested parser or null
  25165. */
  25166. AbstractScene.GetIndividualParser = function (name) {
  25167. if (this._IndividualBabylonFileParsers[name]) {
  25168. return this._IndividualBabylonFileParsers[name];
  25169. }
  25170. return null;
  25171. };
  25172. /**
  25173. * Parser json data and populate both a scene and its associated container object
  25174. * @param jsonData Defines the data to parse
  25175. * @param scene Defines the scene to parse the data for
  25176. * @param container Defines the container attached to the parsing sequence
  25177. * @param rootUrl Defines the root url of the data
  25178. */
  25179. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25180. for (var parserName in this._BabylonFileParsers) {
  25181. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25182. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25183. }
  25184. }
  25185. };
  25186. /**
  25187. * Stores the list of available parsers in the application.
  25188. */
  25189. AbstractScene._BabylonFileParsers = {};
  25190. /**
  25191. * Stores the list of available individual parsers in the application.
  25192. */
  25193. AbstractScene._IndividualBabylonFileParsers = {};
  25194. return AbstractScene;
  25195. }());
  25196. BABYLON.AbstractScene = AbstractScene;
  25197. })(BABYLON || (BABYLON = {}));
  25198. //# sourceMappingURL=babylon.abstractScene.js.map
  25199. var BABYLON;
  25200. (function (BABYLON) {
  25201. /** @hidden */
  25202. var ClickInfo = /** @class */ (function () {
  25203. function ClickInfo() {
  25204. this._singleClick = false;
  25205. this._doubleClick = false;
  25206. this._hasSwiped = false;
  25207. this._ignore = false;
  25208. }
  25209. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25210. get: function () {
  25211. return this._singleClick;
  25212. },
  25213. set: function (b) {
  25214. this._singleClick = b;
  25215. },
  25216. enumerable: true,
  25217. configurable: true
  25218. });
  25219. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25220. get: function () {
  25221. return this._doubleClick;
  25222. },
  25223. set: function (b) {
  25224. this._doubleClick = b;
  25225. },
  25226. enumerable: true,
  25227. configurable: true
  25228. });
  25229. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25230. get: function () {
  25231. return this._hasSwiped;
  25232. },
  25233. set: function (b) {
  25234. this._hasSwiped = b;
  25235. },
  25236. enumerable: true,
  25237. configurable: true
  25238. });
  25239. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25240. get: function () {
  25241. return this._ignore;
  25242. },
  25243. set: function (b) {
  25244. this._ignore = b;
  25245. },
  25246. enumerable: true,
  25247. configurable: true
  25248. });
  25249. return ClickInfo;
  25250. }());
  25251. /**
  25252. * This class is used by the onRenderingGroupObservable
  25253. */
  25254. var RenderingGroupInfo = /** @class */ (function () {
  25255. function RenderingGroupInfo() {
  25256. }
  25257. return RenderingGroupInfo;
  25258. }());
  25259. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25260. /**
  25261. * Represents a scene to be rendered by the engine.
  25262. * @see http://doc.babylonjs.com/features/scene
  25263. */
  25264. var Scene = /** @class */ (function (_super) {
  25265. __extends(Scene, _super);
  25266. /**
  25267. * Creates a new Scene
  25268. * @param engine defines the engine to use to render this scene
  25269. */
  25270. function Scene(engine, options) {
  25271. var _this = _super.call(this) || this;
  25272. // Members
  25273. /**
  25274. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25275. */
  25276. _this.autoClear = true;
  25277. /**
  25278. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25279. */
  25280. _this.autoClearDepthAndStencil = true;
  25281. /**
  25282. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25283. */
  25284. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25285. /**
  25286. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25287. */
  25288. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25289. _this._forceWireframe = false;
  25290. _this._forcePointsCloud = false;
  25291. /**
  25292. * Gets or sets a boolean indicating if animations are enabled
  25293. */
  25294. _this.animationsEnabled = true;
  25295. _this._animationPropertiesOverride = null;
  25296. /**
  25297. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25298. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25299. */
  25300. _this.useConstantAnimationDeltaTime = false;
  25301. /**
  25302. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25303. * Please note that it requires to run a ray cast through the scene on every frame
  25304. */
  25305. _this.constantlyUpdateMeshUnderPointer = false;
  25306. /**
  25307. * Defines the HTML cursor to use when hovering over interactive elements
  25308. */
  25309. _this.hoverCursor = "pointer";
  25310. /**
  25311. * Defines the HTML default cursor to use (empty by default)
  25312. */
  25313. _this.defaultCursor = "";
  25314. /**
  25315. * This is used to call preventDefault() on pointer down
  25316. * in order to block unwanted artifacts like system double clicks
  25317. */
  25318. _this.preventDefaultOnPointerDown = true;
  25319. /**
  25320. * This is used to call preventDefault() on pointer up
  25321. * in order to block unwanted artifacts like system double clicks
  25322. */
  25323. _this.preventDefaultOnPointerUp = true;
  25324. // Metadata
  25325. /**
  25326. * Gets or sets user defined metadata
  25327. */
  25328. _this.metadata = null;
  25329. /**
  25330. * Use this array to add regular expressions used to disable offline support for specific urls
  25331. */
  25332. _this.disableOfflineSupportExceptionRules = new Array();
  25333. /**
  25334. * An event triggered when the scene is disposed.
  25335. */
  25336. _this.onDisposeObservable = new BABYLON.Observable();
  25337. _this._onDisposeObserver = null;
  25338. /**
  25339. * An event triggered before rendering the scene (right after animations and physics)
  25340. */
  25341. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25342. _this._onBeforeRenderObserver = null;
  25343. /**
  25344. * An event triggered after rendering the scene
  25345. */
  25346. _this.onAfterRenderObservable = new BABYLON.Observable();
  25347. _this._onAfterRenderObserver = null;
  25348. /**
  25349. * An event triggered before animating the scene
  25350. */
  25351. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25352. /**
  25353. * An event triggered after animations processing
  25354. */
  25355. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25356. /**
  25357. * An event triggered before draw calls are ready to be sent
  25358. */
  25359. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25360. /**
  25361. * An event triggered after draw calls have been sent
  25362. */
  25363. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25364. /**
  25365. * An event triggered when the scene is ready
  25366. */
  25367. _this.onReadyObservable = new BABYLON.Observable();
  25368. /**
  25369. * An event triggered before rendering a camera
  25370. */
  25371. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25372. _this._onBeforeCameraRenderObserver = null;
  25373. /**
  25374. * An event triggered after rendering a camera
  25375. */
  25376. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25377. _this._onAfterCameraRenderObserver = null;
  25378. /**
  25379. * An event triggered when active meshes evaluation is about to start
  25380. */
  25381. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25382. /**
  25383. * An event triggered when active meshes evaluation is done
  25384. */
  25385. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25386. /**
  25387. * An event triggered when particles rendering is about to start
  25388. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25389. */
  25390. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25391. /**
  25392. * An event triggered when particles rendering is done
  25393. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25394. */
  25395. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25396. /**
  25397. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25398. */
  25399. _this.onDataLoadedObservable = new BABYLON.Observable();
  25400. /**
  25401. * An event triggered when a camera is created
  25402. */
  25403. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25404. /**
  25405. * An event triggered when a camera is removed
  25406. */
  25407. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25408. /**
  25409. * An event triggered when a light is created
  25410. */
  25411. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25412. /**
  25413. * An event triggered when a light is removed
  25414. */
  25415. _this.onLightRemovedObservable = new BABYLON.Observable();
  25416. /**
  25417. * An event triggered when a geometry is created
  25418. */
  25419. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25420. /**
  25421. * An event triggered when a geometry is removed
  25422. */
  25423. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25424. /**
  25425. * An event triggered when a transform node is created
  25426. */
  25427. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25428. /**
  25429. * An event triggered when a transform node is removed
  25430. */
  25431. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25432. /**
  25433. * An event triggered when a mesh is created
  25434. */
  25435. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25436. /**
  25437. * An event triggered when a mesh is removed
  25438. */
  25439. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25440. /**
  25441. * An event triggered when a material is created
  25442. */
  25443. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25444. /**
  25445. * An event triggered when a material is removed
  25446. */
  25447. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25448. /**
  25449. * An event triggered when a texture is created
  25450. */
  25451. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25452. /**
  25453. * An event triggered when a texture is removed
  25454. */
  25455. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25456. /**
  25457. * An event triggered when render targets are about to be rendered
  25458. * Can happen multiple times per frame.
  25459. */
  25460. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25461. /**
  25462. * An event triggered when render targets were rendered.
  25463. * Can happen multiple times per frame.
  25464. */
  25465. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25466. /**
  25467. * An event triggered before calculating deterministic simulation step
  25468. */
  25469. _this.onBeforeStepObservable = new BABYLON.Observable();
  25470. /**
  25471. * An event triggered after calculating deterministic simulation step
  25472. */
  25473. _this.onAfterStepObservable = new BABYLON.Observable();
  25474. /**
  25475. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25476. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25477. * 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)
  25478. */
  25479. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25480. /**
  25481. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25482. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25483. * 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)
  25484. */
  25485. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25486. /**
  25487. * This Observable will when a mesh has been imported into the scene.
  25488. */
  25489. _this.onMeshImportedObservable = new BABYLON.Observable();
  25490. // Animations
  25491. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25492. /**
  25493. * 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).
  25494. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25495. */
  25496. _this.onPrePointerObservable = new BABYLON.Observable();
  25497. /**
  25498. * Observable event triggered each time an input event is received from the rendering canvas
  25499. */
  25500. _this.onPointerObservable = new BABYLON.Observable();
  25501. _this._meshPickProceed = false;
  25502. _this._currentPickResult = null;
  25503. _this._previousPickResult = null;
  25504. _this._totalPointersPressed = 0;
  25505. _this._doubleClickOccured = false;
  25506. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25507. _this.cameraToUseForPointers = null;
  25508. _this._pointerX = 0;
  25509. _this._pointerY = 0;
  25510. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25511. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25512. _this._startingPointerTime = 0;
  25513. _this._previousStartingPointerTime = 0;
  25514. _this._pointerCaptures = {};
  25515. // Deterministic lockstep
  25516. _this._timeAccumulator = 0;
  25517. _this._currentStepId = 0;
  25518. _this._currentInternalStep = 0;
  25519. // Keyboard
  25520. /**
  25521. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25522. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25523. */
  25524. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25525. /**
  25526. * Observable event triggered each time an keyboard event is received from the hosting window
  25527. */
  25528. _this.onKeyboardObservable = new BABYLON.Observable();
  25529. // Coordinates system
  25530. _this._useRightHandedSystem = false;
  25531. // Fog
  25532. _this._fogEnabled = true;
  25533. _this._fogMode = Scene.FOGMODE_NONE;
  25534. /**
  25535. * Gets or sets the fog color to use
  25536. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25537. * (Default is Color3(0.2, 0.2, 0.3))
  25538. */
  25539. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25540. /**
  25541. * Gets or sets the fog density to use
  25542. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25543. * (Default is 0.1)
  25544. */
  25545. _this.fogDensity = 0.1;
  25546. /**
  25547. * Gets or sets the fog start distance to use
  25548. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25549. * (Default is 0)
  25550. */
  25551. _this.fogStart = 0;
  25552. /**
  25553. * Gets or sets the fog end distance to use
  25554. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25555. * (Default is 1000)
  25556. */
  25557. _this.fogEnd = 1000.0;
  25558. // Lights
  25559. _this._shadowsEnabled = true;
  25560. _this._lightsEnabled = true;
  25561. /** All of the active cameras added to this scene. */
  25562. _this.activeCameras = new Array();
  25563. // Textures
  25564. _this._texturesEnabled = true;
  25565. // Particles
  25566. /**
  25567. * Gets or sets a boolean indicating if particles are enabled on this scene
  25568. */
  25569. _this.particlesEnabled = true;
  25570. // Sprites
  25571. /**
  25572. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25573. */
  25574. _this.spritesEnabled = true;
  25575. // Skeletons
  25576. _this._skeletonsEnabled = true;
  25577. // Lens flares
  25578. /**
  25579. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25580. */
  25581. _this.lensFlaresEnabled = true;
  25582. // Collisions
  25583. /**
  25584. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25585. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25586. */
  25587. _this.collisionsEnabled = true;
  25588. /**
  25589. * Defines the gravity applied to this scene (used only for collisions)
  25590. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25591. */
  25592. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25593. // Postprocesses
  25594. /**
  25595. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25596. */
  25597. _this.postProcessesEnabled = true;
  25598. /**
  25599. * The list of postprocesses added to the scene
  25600. */
  25601. _this.postProcesses = new Array();
  25602. // Customs render targets
  25603. /**
  25604. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25605. */
  25606. _this.renderTargetsEnabled = true;
  25607. /**
  25608. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25609. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25610. */
  25611. _this.dumpNextRenderTargets = false;
  25612. /**
  25613. * The list of user defined render targets added to the scene
  25614. */
  25615. _this.customRenderTargets = new Array();
  25616. /**
  25617. * Gets the list of meshes imported to the scene through SceneLoader
  25618. */
  25619. _this.importedMeshesFiles = new Array();
  25620. // Probes
  25621. /**
  25622. * Gets or sets a boolean indicating if probes are enabled on this scene
  25623. */
  25624. _this.probesEnabled = true;
  25625. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25626. // Procedural textures
  25627. /**
  25628. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25629. */
  25630. _this.proceduralTexturesEnabled = true;
  25631. // Performance counters
  25632. _this._totalVertices = new BABYLON.PerfCounter();
  25633. /** @hidden */
  25634. _this._activeIndices = new BABYLON.PerfCounter();
  25635. /** @hidden */
  25636. _this._activeParticles = new BABYLON.PerfCounter();
  25637. /** @hidden */
  25638. _this._activeBones = new BABYLON.PerfCounter();
  25639. _this._animationTime = 0;
  25640. /**
  25641. * Gets or sets a general scale for animation speed
  25642. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25643. */
  25644. _this.animationTimeScale = 1;
  25645. _this._renderId = 0;
  25646. _this._frameId = 0;
  25647. _this._executeWhenReadyTimeoutId = -1;
  25648. _this._intermediateRendering = false;
  25649. _this._viewUpdateFlag = -1;
  25650. _this._projectionUpdateFlag = -1;
  25651. _this._alternateViewUpdateFlag = -1;
  25652. _this._alternateProjectionUpdateFlag = -1;
  25653. /** @hidden */
  25654. _this._toBeDisposed = new Array(256);
  25655. _this._activeRequests = new Array();
  25656. _this._pendingData = new Array();
  25657. _this._isDisposed = false;
  25658. /**
  25659. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25660. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25661. */
  25662. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25663. _this._activeMeshes = new BABYLON.SmartArray(256);
  25664. _this._processedMaterials = new BABYLON.SmartArray(256);
  25665. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25666. /** @hidden */
  25667. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25668. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25669. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25670. /** @hidden */
  25671. _this._activeAnimatables = new Array();
  25672. _this._transformMatrix = BABYLON.Matrix.Zero();
  25673. _this._useAlternateCameraConfiguration = false;
  25674. _this._alternateRendering = false;
  25675. /**
  25676. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25677. * This is useful if there are more lights that the maximum simulteanous authorized
  25678. */
  25679. _this.requireLightSorting = false;
  25680. /**
  25681. * @hidden
  25682. * Backing store of defined scene components.
  25683. */
  25684. _this._components = [];
  25685. /**
  25686. * @hidden
  25687. * Backing store of defined scene components.
  25688. */
  25689. _this._serializableComponents = [];
  25690. /**
  25691. * List of components to register on the next registration step.
  25692. */
  25693. _this._transientComponents = [];
  25694. /**
  25695. * @hidden
  25696. * Defines the actions happening before camera updates.
  25697. */
  25698. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25699. /**
  25700. * @hidden
  25701. * Defines the actions happening before clear the canvas.
  25702. */
  25703. _this._beforeClearStage = BABYLON.Stage.Create();
  25704. /**
  25705. * @hidden
  25706. * Defines the actions when collecting render targets for the frame.
  25707. */
  25708. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25709. /**
  25710. * @hidden
  25711. * Defines the actions happening for one camera in the frame.
  25712. */
  25713. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25714. /**
  25715. * @hidden
  25716. * Defines the actions happening during the per mesh ready checks.
  25717. */
  25718. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25719. /**
  25720. * @hidden
  25721. * Defines the actions happening before evaluate active mesh checks.
  25722. */
  25723. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25724. /**
  25725. * @hidden
  25726. * Defines the actions happening during the evaluate sub mesh checks.
  25727. */
  25728. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25729. /**
  25730. * @hidden
  25731. * Defines the actions happening during the active mesh stage.
  25732. */
  25733. _this._activeMeshStage = BABYLON.Stage.Create();
  25734. /**
  25735. * @hidden
  25736. * Defines the actions happening during the per camera render target step.
  25737. */
  25738. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25739. /**
  25740. * @hidden
  25741. * Defines the actions happening just before the active camera is drawing.
  25742. */
  25743. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25744. /**
  25745. * @hidden
  25746. * Defines the actions happening just before a rendering group is drawing.
  25747. */
  25748. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25749. /**
  25750. * @hidden
  25751. * Defines the actions happening just before a mesh is drawing.
  25752. */
  25753. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25754. /**
  25755. * @hidden
  25756. * Defines the actions happening just after a mesh has been drawn.
  25757. */
  25758. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25759. /**
  25760. * @hidden
  25761. * Defines the actions happening just after a rendering group has been drawn.
  25762. */
  25763. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25764. /**
  25765. * @hidden
  25766. * Defines the actions happening just after the active camera has been drawn.
  25767. */
  25768. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25769. /**
  25770. * @hidden
  25771. * Defines the actions happening just after rendering all cameras and computing intersections.
  25772. */
  25773. _this._afterRenderStage = BABYLON.Stage.Create();
  25774. /**
  25775. * @hidden
  25776. * Defines the actions happening when a pointer move event happens.
  25777. */
  25778. _this._pointerMoveStage = BABYLON.Stage.Create();
  25779. /**
  25780. * @hidden
  25781. * Defines the actions happening when a pointer down event happens.
  25782. */
  25783. _this._pointerDownStage = BABYLON.Stage.Create();
  25784. /**
  25785. * @hidden
  25786. * Defines the actions happening when a pointer up event happens.
  25787. */
  25788. _this._pointerUpStage = BABYLON.Stage.Create();
  25789. /**
  25790. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  25791. */
  25792. _this.geometriesById = null;
  25793. _this._defaultMeshCandidates = {
  25794. data: [],
  25795. length: 0
  25796. };
  25797. _this._defaultSubMeshCandidates = {
  25798. data: [],
  25799. length: 0
  25800. };
  25801. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  25802. _this._activeMeshesFrozen = false;
  25803. /** @hidden */
  25804. _this._allowPostProcessClearColor = true;
  25805. /**
  25806. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25807. */
  25808. _this.getDeterministicFrameTime = function () {
  25809. return 1000.0 / 60.0; // frame time in ms
  25810. };
  25811. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25812. _this._blockMaterialDirtyMechanism = false;
  25813. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25814. _this._engine.scenes.push(_this);
  25815. _this._uid = null;
  25816. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25817. if (BABYLON.PostProcessManager) {
  25818. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25819. }
  25820. if (BABYLON.Tools.IsWindowObjectExist()) {
  25821. _this.attachControl();
  25822. }
  25823. //collision coordinator initialization. For now legacy per default.
  25824. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25825. // Uniform Buffer
  25826. _this._createUbo();
  25827. // Default Image processing definition
  25828. if (BABYLON.ImageProcessingConfiguration) {
  25829. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25830. }
  25831. _this.setDefaultCandidateProviders();
  25832. if (options && options.useGeometryIdsMap === true) {
  25833. _this.geometriesById = {};
  25834. }
  25835. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  25836. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  25837. return _this;
  25838. }
  25839. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25840. /**
  25841. * Texture used in all pbr material as the reflection texture.
  25842. * As in the majority of the scene they are the same (exception for multi room and so on),
  25843. * this is easier to reference from here than from all the materials.
  25844. */
  25845. get: function () {
  25846. return this._environmentTexture;
  25847. },
  25848. /**
  25849. * Texture used in all pbr material as the reflection texture.
  25850. * As in the majority of the scene they are the same (exception for multi room and so on),
  25851. * this is easier to set here than in all the materials.
  25852. */
  25853. set: function (value) {
  25854. if (this._environmentTexture === value) {
  25855. return;
  25856. }
  25857. this._environmentTexture = value;
  25858. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25864. /**
  25865. * Default image processing configuration used either in the rendering
  25866. * Forward main pass or through the imageProcessingPostProcess if present.
  25867. * As in the majority of the scene they are the same (exception for multi camera),
  25868. * this is easier to reference from here than from all the materials and post process.
  25869. *
  25870. * No setter as we it is a shared configuration, you can set the values instead.
  25871. */
  25872. get: function () {
  25873. return this._imageProcessingConfiguration;
  25874. },
  25875. enumerable: true,
  25876. configurable: true
  25877. });
  25878. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25879. get: function () {
  25880. return this._forceWireframe;
  25881. },
  25882. /**
  25883. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25884. */
  25885. set: function (value) {
  25886. if (this._forceWireframe === value) {
  25887. return;
  25888. }
  25889. this._forceWireframe = value;
  25890. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25896. get: function () {
  25897. return this._forcePointsCloud;
  25898. },
  25899. /**
  25900. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25901. */
  25902. set: function (value) {
  25903. if (this._forcePointsCloud === value) {
  25904. return;
  25905. }
  25906. this._forcePointsCloud = value;
  25907. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25908. },
  25909. enumerable: true,
  25910. configurable: true
  25911. });
  25912. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25913. /**
  25914. * Gets or sets the animation properties override
  25915. */
  25916. get: function () {
  25917. return this._animationPropertiesOverride;
  25918. },
  25919. set: function (value) {
  25920. this._animationPropertiesOverride = value;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Object.defineProperty(Scene.prototype, "onDispose", {
  25926. /** Sets a function to be executed when this scene is disposed. */
  25927. set: function (callback) {
  25928. if (this._onDisposeObserver) {
  25929. this.onDisposeObservable.remove(this._onDisposeObserver);
  25930. }
  25931. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(Scene.prototype, "beforeRender", {
  25937. /** Sets a function to be executed before rendering this scene */
  25938. set: function (callback) {
  25939. if (this._onBeforeRenderObserver) {
  25940. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25941. }
  25942. if (callback) {
  25943. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25944. }
  25945. },
  25946. enumerable: true,
  25947. configurable: true
  25948. });
  25949. Object.defineProperty(Scene.prototype, "afterRender", {
  25950. /** Sets a function to be executed after rendering this scene */
  25951. set: function (callback) {
  25952. if (this._onAfterRenderObserver) {
  25953. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25954. }
  25955. if (callback) {
  25956. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25957. }
  25958. },
  25959. enumerable: true,
  25960. configurable: true
  25961. });
  25962. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25963. /** Sets a function to be executed before rendering a camera*/
  25964. set: function (callback) {
  25965. if (this._onBeforeCameraRenderObserver) {
  25966. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25967. }
  25968. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25969. },
  25970. enumerable: true,
  25971. configurable: true
  25972. });
  25973. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25974. /** Sets a function to be executed after rendering a camera*/
  25975. set: function (callback) {
  25976. if (this._onAfterCameraRenderObserver) {
  25977. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25978. }
  25979. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25985. /**
  25986. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25987. */
  25988. get: function () {
  25989. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25995. get: function () {
  25996. return this._useRightHandedSystem;
  25997. },
  25998. /**
  25999. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26000. */
  26001. set: function (value) {
  26002. if (this._useRightHandedSystem === value) {
  26003. return;
  26004. }
  26005. this._useRightHandedSystem = value;
  26006. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26007. },
  26008. enumerable: true,
  26009. configurable: true
  26010. });
  26011. /**
  26012. * Sets the step Id used by deterministic lock step
  26013. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26014. * @param newStepId defines the step Id
  26015. */
  26016. Scene.prototype.setStepId = function (newStepId) {
  26017. this._currentStepId = newStepId;
  26018. };
  26019. /**
  26020. * Gets the step Id used by deterministic lock step
  26021. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26022. * @returns the step Id
  26023. */
  26024. Scene.prototype.getStepId = function () {
  26025. return this._currentStepId;
  26026. };
  26027. /**
  26028. * Gets the internal step used by deterministic lock step
  26029. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26030. * @returns the internal step
  26031. */
  26032. Scene.prototype.getInternalStep = function () {
  26033. return this._currentInternalStep;
  26034. };
  26035. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26036. get: function () {
  26037. return this._fogEnabled;
  26038. },
  26039. /**
  26040. * Gets or sets a boolean indicating if fog is enabled on this scene
  26041. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26042. * (Default is true)
  26043. */
  26044. set: function (value) {
  26045. if (this._fogEnabled === value) {
  26046. return;
  26047. }
  26048. this._fogEnabled = value;
  26049. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26050. },
  26051. enumerable: true,
  26052. configurable: true
  26053. });
  26054. Object.defineProperty(Scene.prototype, "fogMode", {
  26055. get: function () {
  26056. return this._fogMode;
  26057. },
  26058. /**
  26059. * Gets or sets the fog mode to use
  26060. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26061. * | mode | value |
  26062. * | --- | --- |
  26063. * | FOGMODE_NONE | 0 |
  26064. * | FOGMODE_EXP | 1 |
  26065. * | FOGMODE_EXP2 | 2 |
  26066. * | FOGMODE_LINEAR | 3 |
  26067. */
  26068. set: function (value) {
  26069. if (this._fogMode === value) {
  26070. return;
  26071. }
  26072. this._fogMode = value;
  26073. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26074. },
  26075. enumerable: true,
  26076. configurable: true
  26077. });
  26078. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26079. get: function () {
  26080. return this._shadowsEnabled;
  26081. },
  26082. /**
  26083. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26084. */
  26085. set: function (value) {
  26086. if (this._shadowsEnabled === value) {
  26087. return;
  26088. }
  26089. this._shadowsEnabled = value;
  26090. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26091. },
  26092. enumerable: true,
  26093. configurable: true
  26094. });
  26095. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26096. get: function () {
  26097. return this._lightsEnabled;
  26098. },
  26099. /**
  26100. * Gets or sets a boolean indicating if lights are enabled on this scene
  26101. */
  26102. set: function (value) {
  26103. if (this._lightsEnabled === value) {
  26104. return;
  26105. }
  26106. this._lightsEnabled = value;
  26107. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26108. },
  26109. enumerable: true,
  26110. configurable: true
  26111. });
  26112. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26113. /** The default material used on meshes when no material is affected */
  26114. get: function () {
  26115. if (!this._defaultMaterial) {
  26116. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26117. }
  26118. return this._defaultMaterial;
  26119. },
  26120. /** The default material used on meshes when no material is affected */
  26121. set: function (value) {
  26122. this._defaultMaterial = value;
  26123. },
  26124. enumerable: true,
  26125. configurable: true
  26126. });
  26127. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26128. get: function () {
  26129. return this._texturesEnabled;
  26130. },
  26131. /**
  26132. * Gets or sets a boolean indicating if textures are enabled on this scene
  26133. */
  26134. set: function (value) {
  26135. if (this._texturesEnabled === value) {
  26136. return;
  26137. }
  26138. this._texturesEnabled = value;
  26139. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26140. },
  26141. enumerable: true,
  26142. configurable: true
  26143. });
  26144. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26145. get: function () {
  26146. return this._skeletonsEnabled;
  26147. },
  26148. /**
  26149. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26150. */
  26151. set: function (value) {
  26152. if (this._skeletonsEnabled === value) {
  26153. return;
  26154. }
  26155. this._skeletonsEnabled = value;
  26156. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26157. },
  26158. enumerable: true,
  26159. configurable: true
  26160. });
  26161. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26162. /** @hidden */
  26163. get: function () {
  26164. return this._alternateRendering;
  26165. },
  26166. enumerable: true,
  26167. configurable: true
  26168. });
  26169. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26170. /**
  26171. * Gets the list of frustum planes (built from the active camera)
  26172. */
  26173. get: function () {
  26174. return this._frustumPlanes;
  26175. },
  26176. enumerable: true,
  26177. configurable: true
  26178. });
  26179. /**
  26180. * Registers the transient components if needed.
  26181. */
  26182. Scene.prototype._registerTransientComponents = function () {
  26183. // Register components that have been associated lately to the scene.
  26184. if (this._transientComponents.length > 0) {
  26185. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26186. var component = _a[_i];
  26187. component.register();
  26188. }
  26189. this._transientComponents = [];
  26190. }
  26191. };
  26192. /**
  26193. * @hidden
  26194. * Add a component to the scene.
  26195. * Note that the ccomponent could be registered on th next frame if this is called after
  26196. * the register component stage.
  26197. * @param component Defines the component to add to the scene
  26198. */
  26199. Scene.prototype._addComponent = function (component) {
  26200. this._components.push(component);
  26201. this._transientComponents.push(component);
  26202. var serializableComponent = component;
  26203. if (serializableComponent.addFromContainer) {
  26204. this._serializableComponents.push(serializableComponent);
  26205. }
  26206. };
  26207. /**
  26208. * @hidden
  26209. * Gets a component from the scene.
  26210. * @param name defines the name of the component to retrieve
  26211. * @returns the component or null if not present
  26212. */
  26213. Scene.prototype._getComponent = function (name) {
  26214. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26215. var component = _a[_i];
  26216. if (component.name === name) {
  26217. return component;
  26218. }
  26219. }
  26220. return null;
  26221. };
  26222. /**
  26223. * @hidden
  26224. */
  26225. Scene.prototype._getDefaultMeshCandidates = function () {
  26226. this._defaultMeshCandidates.data = this.meshes;
  26227. this._defaultMeshCandidates.length = this.meshes.length;
  26228. return this._defaultMeshCandidates;
  26229. };
  26230. /**
  26231. * @hidden
  26232. */
  26233. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26234. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26235. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26236. return this._defaultSubMeshCandidates;
  26237. };
  26238. /**
  26239. * Sets the default candidate providers for the scene.
  26240. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26241. * and getCollidingSubMeshCandidates to their default function
  26242. */
  26243. Scene.prototype.setDefaultCandidateProviders = function () {
  26244. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26245. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26246. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26247. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26248. };
  26249. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26250. /**
  26251. * Gets a boolean indicating if collisions are processed on a web worker
  26252. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26253. */
  26254. get: function () {
  26255. return this._workerCollisions;
  26256. },
  26257. set: function (enabled) {
  26258. if (!BABYLON.CollisionCoordinatorLegacy) {
  26259. return;
  26260. }
  26261. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26262. this._workerCollisions = enabled;
  26263. if (this.collisionCoordinator) {
  26264. this.collisionCoordinator.destroy();
  26265. }
  26266. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26267. this.collisionCoordinator.init(this);
  26268. },
  26269. enumerable: true,
  26270. configurable: true
  26271. });
  26272. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26273. /**
  26274. * Gets the mesh that is currently under the pointer
  26275. */
  26276. get: function () {
  26277. return this._pointerOverMesh;
  26278. },
  26279. enumerable: true,
  26280. configurable: true
  26281. });
  26282. Object.defineProperty(Scene.prototype, "pointerX", {
  26283. /**
  26284. * Gets the current on-screen X position of the pointer
  26285. */
  26286. get: function () {
  26287. return this._pointerX;
  26288. },
  26289. enumerable: true,
  26290. configurable: true
  26291. });
  26292. Object.defineProperty(Scene.prototype, "pointerY", {
  26293. /**
  26294. * Gets the current on-screen Y position of the pointer
  26295. */
  26296. get: function () {
  26297. return this._pointerY;
  26298. },
  26299. enumerable: true,
  26300. configurable: true
  26301. });
  26302. /**
  26303. * Gets the cached material (ie. the latest rendered one)
  26304. * @returns the cached material
  26305. */
  26306. Scene.prototype.getCachedMaterial = function () {
  26307. return this._cachedMaterial;
  26308. };
  26309. /**
  26310. * Gets the cached effect (ie. the latest rendered one)
  26311. * @returns the cached effect
  26312. */
  26313. Scene.prototype.getCachedEffect = function () {
  26314. return this._cachedEffect;
  26315. };
  26316. /**
  26317. * Gets the cached visibility state (ie. the latest rendered one)
  26318. * @returns the cached visibility state
  26319. */
  26320. Scene.prototype.getCachedVisibility = function () {
  26321. return this._cachedVisibility;
  26322. };
  26323. /**
  26324. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26325. * @param material defines the current material
  26326. * @param effect defines the current effect
  26327. * @param visibility defines the current visibility state
  26328. * @returns true if one parameter is not cached
  26329. */
  26330. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26331. if (visibility === void 0) { visibility = 1; }
  26332. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26333. };
  26334. /**
  26335. * Gets the engine associated with the scene
  26336. * @returns an Engine
  26337. */
  26338. Scene.prototype.getEngine = function () {
  26339. return this._engine;
  26340. };
  26341. /**
  26342. * Gets the total number of vertices rendered per frame
  26343. * @returns the total number of vertices rendered per frame
  26344. */
  26345. Scene.prototype.getTotalVertices = function () {
  26346. return this._totalVertices.current;
  26347. };
  26348. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26349. /**
  26350. * Gets the performance counter for total vertices
  26351. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26352. */
  26353. get: function () {
  26354. return this._totalVertices;
  26355. },
  26356. enumerable: true,
  26357. configurable: true
  26358. });
  26359. /**
  26360. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26361. * @returns the total number of active indices rendered per frame
  26362. */
  26363. Scene.prototype.getActiveIndices = function () {
  26364. return this._activeIndices.current;
  26365. };
  26366. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26367. /**
  26368. * Gets the performance counter for active indices
  26369. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26370. */
  26371. get: function () {
  26372. return this._activeIndices;
  26373. },
  26374. enumerable: true,
  26375. configurable: true
  26376. });
  26377. /**
  26378. * Gets the total number of active particles rendered per frame
  26379. * @returns the total number of active particles rendered per frame
  26380. */
  26381. Scene.prototype.getActiveParticles = function () {
  26382. return this._activeParticles.current;
  26383. };
  26384. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26385. /**
  26386. * Gets the performance counter for active particles
  26387. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26388. */
  26389. get: function () {
  26390. return this._activeParticles;
  26391. },
  26392. enumerable: true,
  26393. configurable: true
  26394. });
  26395. /**
  26396. * Gets the total number of active bones rendered per frame
  26397. * @returns the total number of active bones rendered per frame
  26398. */
  26399. Scene.prototype.getActiveBones = function () {
  26400. return this._activeBones.current;
  26401. };
  26402. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26403. /**
  26404. * Gets the performance counter for active bones
  26405. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26406. */
  26407. get: function () {
  26408. return this._activeBones;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. /** @hidden */
  26414. Scene.prototype.getInterFramePerfCounter = function () {
  26415. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26416. return 0;
  26417. };
  26418. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26419. /** @hidden */
  26420. get: function () {
  26421. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26422. return null;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. /** @hidden */
  26428. Scene.prototype.getLastFrameDuration = function () {
  26429. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26430. return 0;
  26431. };
  26432. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26433. /** @hidden */
  26434. get: function () {
  26435. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26436. return null;
  26437. },
  26438. enumerable: true,
  26439. configurable: true
  26440. });
  26441. /** @hidden */
  26442. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26443. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26444. return 0;
  26445. };
  26446. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26447. /** @hidden */
  26448. get: function () {
  26449. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26450. return null;
  26451. },
  26452. enumerable: true,
  26453. configurable: true
  26454. });
  26455. /**
  26456. * Gets the array of active meshes
  26457. * @returns an array of AbstractMesh
  26458. */
  26459. Scene.prototype.getActiveMeshes = function () {
  26460. return this._activeMeshes;
  26461. };
  26462. /** @hidden */
  26463. Scene.prototype.getRenderTargetsDuration = function () {
  26464. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26465. return 0;
  26466. };
  26467. /** @hidden */
  26468. Scene.prototype.getRenderDuration = function () {
  26469. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26470. return 0;
  26471. };
  26472. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26473. /** @hidden */
  26474. get: function () {
  26475. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26476. return null;
  26477. },
  26478. enumerable: true,
  26479. configurable: true
  26480. });
  26481. /** @hidden */
  26482. Scene.prototype.getParticlesDuration = function () {
  26483. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26484. return 0;
  26485. };
  26486. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26487. /** @hidden */
  26488. get: function () {
  26489. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26490. return null;
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. /** @hidden */
  26496. Scene.prototype.getSpritesDuration = function () {
  26497. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26498. return 0;
  26499. };
  26500. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26501. /** @hidden */
  26502. get: function () {
  26503. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26504. return null;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. /**
  26510. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26511. * @returns a number
  26512. */
  26513. Scene.prototype.getAnimationRatio = function () {
  26514. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26515. };
  26516. /**
  26517. * Gets an unique Id for the current render phase
  26518. * @returns a number
  26519. */
  26520. Scene.prototype.getRenderId = function () {
  26521. return this._renderId;
  26522. };
  26523. /**
  26524. * Gets an unique Id for the current frame
  26525. * @returns a number
  26526. */
  26527. Scene.prototype.getFrameId = function () {
  26528. return this._frameId;
  26529. };
  26530. /** Call this function if you want to manually increment the render Id*/
  26531. Scene.prototype.incrementRenderId = function () {
  26532. this._renderId++;
  26533. };
  26534. Scene.prototype._updatePointerPosition = function (evt) {
  26535. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26536. if (!canvasRect) {
  26537. return;
  26538. }
  26539. this._pointerX = evt.clientX - canvasRect.left;
  26540. this._pointerY = evt.clientY - canvasRect.top;
  26541. this._unTranslatedPointerX = this._pointerX;
  26542. this._unTranslatedPointerY = this._pointerY;
  26543. };
  26544. Scene.prototype._createUbo = function () {
  26545. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26546. this._sceneUbo.addUniform("viewProjection", 16);
  26547. this._sceneUbo.addUniform("view", 16);
  26548. };
  26549. Scene.prototype._createAlternateUbo = function () {
  26550. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26551. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26552. this._alternateSceneUbo.addUniform("view", 16);
  26553. };
  26554. // Pointers handling
  26555. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26556. if (pointerInfo.pickInfo) {
  26557. if (!pointerInfo.pickInfo.ray) {
  26558. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26559. }
  26560. }
  26561. };
  26562. /**
  26563. * Use this method to simulate a pointer move on a mesh
  26564. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26565. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26566. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26567. * @returns the current scene
  26568. */
  26569. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26570. var evt = new PointerEvent("pointermove", pointerEventInit);
  26571. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26572. return this;
  26573. }
  26574. return this._processPointerMove(pickResult, evt);
  26575. };
  26576. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26577. var canvas = this._engine.getRenderingCanvas();
  26578. if (!canvas) {
  26579. return this;
  26580. }
  26581. // Restore pointer
  26582. canvas.style.cursor = this.defaultCursor;
  26583. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26584. if (isMeshPicked) {
  26585. this.setPointerOverMesh(pickResult.pickedMesh);
  26586. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26587. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26588. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26589. }
  26590. else {
  26591. canvas.style.cursor = this.hoverCursor;
  26592. }
  26593. }
  26594. }
  26595. else {
  26596. this.setPointerOverMesh(null);
  26597. }
  26598. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26599. var step = _a[_i];
  26600. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26601. }
  26602. if (pickResult) {
  26603. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26604. if (this.onPointerMove) {
  26605. this.onPointerMove(evt, pickResult, type);
  26606. }
  26607. if (this.onPointerObservable.hasObservers()) {
  26608. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26609. this._setRayOnPointerInfo(pi);
  26610. this.onPointerObservable.notifyObservers(pi, type);
  26611. }
  26612. }
  26613. return this;
  26614. };
  26615. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26616. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26617. if (pickResult) {
  26618. pi.ray = pickResult.ray;
  26619. }
  26620. this.onPrePointerObservable.notifyObservers(pi, type);
  26621. if (pi.skipOnPointerObservable) {
  26622. return true;
  26623. }
  26624. else {
  26625. return false;
  26626. }
  26627. };
  26628. /**
  26629. * Use this method to simulate a pointer down on a mesh
  26630. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26631. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26632. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26633. * @returns the current scene
  26634. */
  26635. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26636. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26637. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26638. return this;
  26639. }
  26640. return this._processPointerDown(pickResult, evt);
  26641. };
  26642. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26643. var _this = this;
  26644. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26645. this._pickedDownMesh = pickResult.pickedMesh;
  26646. var actionManager = pickResult.pickedMesh.actionManager;
  26647. if (actionManager) {
  26648. if (actionManager.hasPickTriggers) {
  26649. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26650. switch (evt.button) {
  26651. case 0:
  26652. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26653. break;
  26654. case 1:
  26655. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26656. break;
  26657. case 2:
  26658. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26659. break;
  26660. }
  26661. }
  26662. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26663. window.setTimeout(function () {
  26664. 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);
  26665. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26666. if (_this._totalPointersPressed !== 0 &&
  26667. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26668. !_this._isPointerSwiping()) {
  26669. _this._startingPointerTime = 0;
  26670. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26671. }
  26672. }
  26673. }, Scene.LongPressDelay);
  26674. }
  26675. }
  26676. }
  26677. else {
  26678. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26679. var step = _a[_i];
  26680. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26681. }
  26682. }
  26683. if (pickResult) {
  26684. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26685. if (this.onPointerDown) {
  26686. this.onPointerDown(evt, pickResult, type);
  26687. }
  26688. if (this.onPointerObservable.hasObservers()) {
  26689. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26690. this._setRayOnPointerInfo(pi);
  26691. this.onPointerObservable.notifyObservers(pi, type);
  26692. }
  26693. }
  26694. return this;
  26695. };
  26696. /**
  26697. * Use this method to simulate a pointer up on a mesh
  26698. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26699. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26700. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26701. * @returns the current scene
  26702. */
  26703. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26704. var evt = new PointerEvent("pointerup", pointerEventInit);
  26705. var clickInfo = new ClickInfo();
  26706. clickInfo.singleClick = true;
  26707. clickInfo.ignore = true;
  26708. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26709. return this;
  26710. }
  26711. return this._processPointerUp(pickResult, evt, clickInfo);
  26712. };
  26713. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26714. if (pickResult && pickResult && pickResult.pickedMesh) {
  26715. this._pickedUpMesh = pickResult.pickedMesh;
  26716. if (this._pickedDownMesh === this._pickedUpMesh) {
  26717. if (this.onPointerPick) {
  26718. this.onPointerPick(evt, pickResult);
  26719. }
  26720. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26721. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26722. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26723. this._setRayOnPointerInfo(pi);
  26724. this.onPointerObservable.notifyObservers(pi, type_1);
  26725. }
  26726. }
  26727. if (pickResult.pickedMesh.actionManager) {
  26728. if (clickInfo.ignore) {
  26729. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26730. }
  26731. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26733. }
  26734. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26735. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26736. }
  26737. }
  26738. }
  26739. else {
  26740. if (!clickInfo.ignore) {
  26741. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26742. var step = _a[_i];
  26743. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26744. }
  26745. }
  26746. }
  26747. if (this._pickedDownMesh &&
  26748. this._pickedDownMesh.actionManager &&
  26749. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26750. this._pickedDownMesh !== this._pickedUpMesh) {
  26751. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26752. }
  26753. var type = BABYLON.PointerEventTypes.POINTERUP;
  26754. if (this.onPointerObservable.hasObservers()) {
  26755. if (!clickInfo.ignore) {
  26756. if (!clickInfo.hasSwiped) {
  26757. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26758. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26759. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26760. this._setRayOnPointerInfo(pi);
  26761. this.onPointerObservable.notifyObservers(pi, type_2);
  26762. }
  26763. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26764. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26765. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26766. this._setRayOnPointerInfo(pi);
  26767. this.onPointerObservable.notifyObservers(pi, type_3);
  26768. }
  26769. }
  26770. }
  26771. else {
  26772. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26773. this._setRayOnPointerInfo(pi);
  26774. this.onPointerObservable.notifyObservers(pi, type);
  26775. }
  26776. }
  26777. if (this.onPointerUp && !clickInfo.ignore) {
  26778. this.onPointerUp(evt, pickResult, type);
  26779. }
  26780. return this;
  26781. };
  26782. /**
  26783. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26784. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26785. * @returns true if the pointer was captured
  26786. */
  26787. Scene.prototype.isPointerCaptured = function (pointerId) {
  26788. if (pointerId === void 0) { pointerId = 0; }
  26789. return this._pointerCaptures[pointerId];
  26790. };
  26791. /** @hidden */
  26792. Scene.prototype._isPointerSwiping = function () {
  26793. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26794. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26795. };
  26796. /**
  26797. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26798. * @param attachUp defines if you want to attach events to pointerup
  26799. * @param attachDown defines if you want to attach events to pointerdown
  26800. * @param attachMove defines if you want to attach events to pointermove
  26801. */
  26802. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26803. var _this = this;
  26804. if (attachUp === void 0) { attachUp = true; }
  26805. if (attachDown === void 0) { attachDown = true; }
  26806. if (attachMove === void 0) { attachMove = true; }
  26807. this._initActionManager = function (act, clickInfo) {
  26808. if (!_this._meshPickProceed) {
  26809. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26810. _this._currentPickResult = pickResult;
  26811. if (pickResult) {
  26812. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26813. }
  26814. _this._meshPickProceed = true;
  26815. }
  26816. return act;
  26817. };
  26818. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26819. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26820. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26821. btn !== _this._previousButtonPressed) {
  26822. _this._doubleClickOccured = false;
  26823. clickInfo.singleClick = true;
  26824. clickInfo.ignore = false;
  26825. cb(clickInfo, _this._currentPickResult);
  26826. }
  26827. };
  26828. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26829. var clickInfo = new ClickInfo();
  26830. _this._currentPickResult = null;
  26831. var act = null;
  26832. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26833. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26834. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26835. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26836. act = _this._initActionManager(act, clickInfo);
  26837. if (act) {
  26838. checkPicking = act.hasPickTriggers;
  26839. }
  26840. }
  26841. if (checkPicking) {
  26842. var btn = evt.button;
  26843. clickInfo.hasSwiped = _this._isPointerSwiping();
  26844. if (!clickInfo.hasSwiped) {
  26845. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26846. if (!checkSingleClickImmediately) {
  26847. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26848. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26849. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26850. act = _this._initActionManager(act, clickInfo);
  26851. if (act) {
  26852. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26853. }
  26854. }
  26855. }
  26856. if (checkSingleClickImmediately) {
  26857. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26858. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26859. btn !== _this._previousButtonPressed) {
  26860. clickInfo.singleClick = true;
  26861. cb(clickInfo, _this._currentPickResult);
  26862. }
  26863. }
  26864. // at least one double click is required to be check and exclusive double click is enabled
  26865. else {
  26866. // wait that no double click has been raised during the double click delay
  26867. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26868. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26869. }
  26870. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26871. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26872. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26873. act = _this._initActionManager(act, clickInfo);
  26874. if (act) {
  26875. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26876. }
  26877. }
  26878. if (checkDoubleClick) {
  26879. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26880. if (btn === _this._previousButtonPressed &&
  26881. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26882. !_this._doubleClickOccured) {
  26883. // pointer has not moved for 2 clicks, it's a double click
  26884. if (!clickInfo.hasSwiped &&
  26885. !_this._isPointerSwiping()) {
  26886. _this._previousStartingPointerTime = 0;
  26887. _this._doubleClickOccured = true;
  26888. clickInfo.doubleClick = true;
  26889. clickInfo.ignore = false;
  26890. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26891. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26892. }
  26893. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26894. cb(clickInfo, _this._currentPickResult);
  26895. }
  26896. // if the two successive clicks are too far, it's just two simple clicks
  26897. else {
  26898. _this._doubleClickOccured = false;
  26899. _this._previousStartingPointerTime = _this._startingPointerTime;
  26900. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26901. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26902. _this._previousButtonPressed = btn;
  26903. if (Scene.ExclusiveDoubleClickMode) {
  26904. if (_this._previousDelayedSimpleClickTimeout) {
  26905. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26906. }
  26907. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26908. cb(clickInfo, _this._previousPickResult);
  26909. }
  26910. else {
  26911. cb(clickInfo, _this._currentPickResult);
  26912. }
  26913. }
  26914. }
  26915. // just the first click of the double has been raised
  26916. else {
  26917. _this._doubleClickOccured = false;
  26918. _this._previousStartingPointerTime = _this._startingPointerTime;
  26919. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26920. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26921. _this._previousButtonPressed = btn;
  26922. }
  26923. }
  26924. }
  26925. }
  26926. clickInfo.ignore = true;
  26927. cb(clickInfo, _this._currentPickResult);
  26928. };
  26929. this._onPointerMove = function (evt) {
  26930. _this._updatePointerPosition(evt);
  26931. // PreObservable support
  26932. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26933. return;
  26934. }
  26935. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26936. return;
  26937. }
  26938. if (!_this.pointerMovePredicate) {
  26939. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26940. }
  26941. // Meshes
  26942. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26943. _this._processPointerMove(pickResult, evt);
  26944. };
  26945. this._onPointerDown = function (evt) {
  26946. _this._totalPointersPressed++;
  26947. _this._pickedDownMesh = null;
  26948. _this._meshPickProceed = false;
  26949. _this._updatePointerPosition(evt);
  26950. if (_this.preventDefaultOnPointerDown && canvas) {
  26951. evt.preventDefault();
  26952. canvas.focus();
  26953. }
  26954. // PreObservable support
  26955. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26956. return;
  26957. }
  26958. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26959. return;
  26960. }
  26961. _this._pointerCaptures[evt.pointerId] = true;
  26962. _this._startingPointerPosition.x = _this._pointerX;
  26963. _this._startingPointerPosition.y = _this._pointerY;
  26964. _this._startingPointerTime = Date.now();
  26965. if (!_this.pointerDownPredicate) {
  26966. _this.pointerDownPredicate = function (mesh) {
  26967. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26968. };
  26969. }
  26970. // Meshes
  26971. _this._pickedDownMesh = null;
  26972. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26973. _this._processPointerDown(pickResult, evt);
  26974. };
  26975. this._onPointerUp = function (evt) {
  26976. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26977. return; // So we need to test it the pointer down was pressed before.
  26978. }
  26979. _this._totalPointersPressed--;
  26980. _this._pickedUpMesh = null;
  26981. _this._meshPickProceed = false;
  26982. _this._updatePointerPosition(evt);
  26983. if (_this.preventDefaultOnPointerUp && canvas) {
  26984. evt.preventDefault();
  26985. canvas.focus();
  26986. }
  26987. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26988. // PreObservable support
  26989. if (_this.onPrePointerObservable.hasObservers()) {
  26990. if (!clickInfo.ignore) {
  26991. if (!clickInfo.hasSwiped) {
  26992. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26993. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26994. return;
  26995. }
  26996. }
  26997. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26998. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26999. return;
  27000. }
  27001. }
  27002. }
  27003. }
  27004. else {
  27005. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27006. return;
  27007. }
  27008. }
  27009. }
  27010. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27011. return;
  27012. }
  27013. _this._pointerCaptures[evt.pointerId] = false;
  27014. if (!_this.pointerUpPredicate) {
  27015. _this.pointerUpPredicate = function (mesh) {
  27016. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27017. };
  27018. }
  27019. // Meshes
  27020. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  27021. _this._initActionManager(null, clickInfo);
  27022. }
  27023. if (!pickResult) {
  27024. pickResult = _this._currentPickResult;
  27025. }
  27026. _this._processPointerUp(pickResult, evt, clickInfo);
  27027. _this._previousPickResult = _this._currentPickResult;
  27028. });
  27029. };
  27030. this._onKeyDown = function (evt) {
  27031. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27032. if (_this.onPreKeyboardObservable.hasObservers()) {
  27033. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27034. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27035. if (pi.skipOnPointerObservable) {
  27036. return;
  27037. }
  27038. }
  27039. if (_this.onKeyboardObservable.hasObservers()) {
  27040. var pi = new BABYLON.KeyboardInfo(type, evt);
  27041. _this.onKeyboardObservable.notifyObservers(pi, type);
  27042. }
  27043. if (_this.actionManager) {
  27044. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27045. }
  27046. };
  27047. this._onKeyUp = function (evt) {
  27048. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27049. if (_this.onPreKeyboardObservable.hasObservers()) {
  27050. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27051. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27052. if (pi.skipOnPointerObservable) {
  27053. return;
  27054. }
  27055. }
  27056. if (_this.onKeyboardObservable.hasObservers()) {
  27057. var pi = new BABYLON.KeyboardInfo(type, evt);
  27058. _this.onKeyboardObservable.notifyObservers(pi, type);
  27059. }
  27060. if (_this.actionManager) {
  27061. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27062. }
  27063. };
  27064. var engine = this.getEngine();
  27065. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27066. if (!canvas) {
  27067. return;
  27068. }
  27069. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27070. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27071. });
  27072. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27073. if (!canvas) {
  27074. return;
  27075. }
  27076. canvas.removeEventListener("keydown", _this._onKeyDown);
  27077. canvas.removeEventListener("keyup", _this._onKeyUp);
  27078. });
  27079. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27080. var canvas = this._engine.getRenderingCanvas();
  27081. if (!canvas) {
  27082. return;
  27083. }
  27084. if (attachMove) {
  27085. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27086. // Wheel
  27087. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  27088. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  27089. }
  27090. if (attachDown) {
  27091. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27092. }
  27093. if (attachUp) {
  27094. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27095. }
  27096. canvas.tabIndex = 1;
  27097. };
  27098. /** Detaches all event handlers*/
  27099. Scene.prototype.detachControl = function () {
  27100. var engine = this.getEngine();
  27101. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27102. var canvas = engine.getRenderingCanvas();
  27103. if (!canvas) {
  27104. return;
  27105. }
  27106. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27107. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27108. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27109. if (this._onCanvasBlurObserver) {
  27110. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27111. }
  27112. if (this._onCanvasFocusObserver) {
  27113. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27114. }
  27115. // Wheel
  27116. canvas.removeEventListener('mousewheel', this._onPointerMove);
  27117. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  27118. // Keyboard
  27119. canvas.removeEventListener("keydown", this._onKeyDown);
  27120. canvas.removeEventListener("keyup", this._onKeyUp);
  27121. // Observables
  27122. this.onKeyboardObservable.clear();
  27123. this.onPreKeyboardObservable.clear();
  27124. this.onPointerObservable.clear();
  27125. this.onPrePointerObservable.clear();
  27126. };
  27127. /**
  27128. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27129. * Delay loaded resources are not taking in account
  27130. * @return true if all required resources are ready
  27131. */
  27132. Scene.prototype.isReady = function () {
  27133. if (this._isDisposed) {
  27134. return false;
  27135. }
  27136. var index;
  27137. var engine = this.getEngine();
  27138. // Effects
  27139. if (!engine.areAllEffectsReady()) {
  27140. return false;
  27141. }
  27142. // Pending data
  27143. if (this._pendingData.length > 0) {
  27144. return false;
  27145. }
  27146. // Meshes
  27147. for (index = 0; index < this.meshes.length; index++) {
  27148. var mesh = this.meshes[index];
  27149. if (!mesh.isEnabled()) {
  27150. continue;
  27151. }
  27152. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27153. continue;
  27154. }
  27155. if (!mesh.isReady(true)) {
  27156. return false;
  27157. }
  27158. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27159. // Is Ready For Mesh
  27160. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27161. var step = _a[_i];
  27162. if (!step.action(mesh, hardwareInstancedRendering)) {
  27163. return false;
  27164. }
  27165. }
  27166. }
  27167. // Geometries
  27168. for (index = 0; index < this.geometries.length; index++) {
  27169. var geometry = this.geometries[index];
  27170. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27171. return false;
  27172. }
  27173. }
  27174. // Post-processes
  27175. if (this.activeCameras && this.activeCameras.length > 0) {
  27176. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27177. var camera = _c[_b];
  27178. if (!camera.isReady(true)) {
  27179. return false;
  27180. }
  27181. }
  27182. }
  27183. else if (this.activeCamera) {
  27184. if (!this.activeCamera.isReady(true)) {
  27185. return false;
  27186. }
  27187. }
  27188. // Particles
  27189. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27190. var particleSystem = _e[_d];
  27191. if (!particleSystem.isReady()) {
  27192. return false;
  27193. }
  27194. }
  27195. return true;
  27196. };
  27197. /** Resets all cached information relative to material (including effect and visibility) */
  27198. Scene.prototype.resetCachedMaterial = function () {
  27199. this._cachedMaterial = null;
  27200. this._cachedEffect = null;
  27201. this._cachedVisibility = null;
  27202. };
  27203. /**
  27204. * Registers a function to be called before every frame render
  27205. * @param func defines the function to register
  27206. */
  27207. Scene.prototype.registerBeforeRender = function (func) {
  27208. this.onBeforeRenderObservable.add(func);
  27209. };
  27210. /**
  27211. * Unregisters a function called before every frame render
  27212. * @param func defines the function to unregister
  27213. */
  27214. Scene.prototype.unregisterBeforeRender = function (func) {
  27215. this.onBeforeRenderObservable.removeCallback(func);
  27216. };
  27217. /**
  27218. * Registers a function to be called after every frame render
  27219. * @param func defines the function to register
  27220. */
  27221. Scene.prototype.registerAfterRender = function (func) {
  27222. this.onAfterRenderObservable.add(func);
  27223. };
  27224. /**
  27225. * Unregisters a function called after every frame render
  27226. * @param func defines the function to unregister
  27227. */
  27228. Scene.prototype.unregisterAfterRender = function (func) {
  27229. this.onAfterRenderObservable.removeCallback(func);
  27230. };
  27231. Scene.prototype._executeOnceBeforeRender = function (func) {
  27232. var _this = this;
  27233. var execFunc = function () {
  27234. func();
  27235. setTimeout(function () {
  27236. _this.unregisterBeforeRender(execFunc);
  27237. });
  27238. };
  27239. this.registerBeforeRender(execFunc);
  27240. };
  27241. /**
  27242. * The provided function will run before render once and will be disposed afterwards.
  27243. * A timeout delay can be provided so that the function will be executed in N ms.
  27244. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27245. * @param func The function to be executed.
  27246. * @param timeout optional delay in ms
  27247. */
  27248. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27249. var _this = this;
  27250. if (timeout !== undefined) {
  27251. setTimeout(function () {
  27252. _this._executeOnceBeforeRender(func);
  27253. }, timeout);
  27254. }
  27255. else {
  27256. this._executeOnceBeforeRender(func);
  27257. }
  27258. };
  27259. /** @hidden */
  27260. Scene.prototype._addPendingData = function (data) {
  27261. this._pendingData.push(data);
  27262. };
  27263. /** @hidden */
  27264. Scene.prototype._removePendingData = function (data) {
  27265. var wasLoading = this.isLoading;
  27266. var index = this._pendingData.indexOf(data);
  27267. if (index !== -1) {
  27268. this._pendingData.splice(index, 1);
  27269. }
  27270. if (wasLoading && !this.isLoading) {
  27271. this.onDataLoadedObservable.notifyObservers(this);
  27272. }
  27273. };
  27274. /**
  27275. * Returns the number of items waiting to be loaded
  27276. * @returns the number of items waiting to be loaded
  27277. */
  27278. Scene.prototype.getWaitingItemsCount = function () {
  27279. return this._pendingData.length;
  27280. };
  27281. Object.defineProperty(Scene.prototype, "isLoading", {
  27282. /**
  27283. * Returns a boolean indicating if the scene is still loading data
  27284. */
  27285. get: function () {
  27286. return this._pendingData.length > 0;
  27287. },
  27288. enumerable: true,
  27289. configurable: true
  27290. });
  27291. /**
  27292. * Registers a function to be executed when the scene is ready
  27293. * @param {Function} func - the function to be executed
  27294. */
  27295. Scene.prototype.executeWhenReady = function (func) {
  27296. var _this = this;
  27297. this.onReadyObservable.add(func);
  27298. if (this._executeWhenReadyTimeoutId !== -1) {
  27299. return;
  27300. }
  27301. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27302. _this._checkIsReady();
  27303. }, 150);
  27304. };
  27305. /**
  27306. * Returns a promise that resolves when the scene is ready
  27307. * @returns A promise that resolves when the scene is ready
  27308. */
  27309. Scene.prototype.whenReadyAsync = function () {
  27310. var _this = this;
  27311. return new Promise(function (resolve) {
  27312. _this.executeWhenReady(function () {
  27313. resolve();
  27314. });
  27315. });
  27316. };
  27317. /** @hidden */
  27318. Scene.prototype._checkIsReady = function () {
  27319. var _this = this;
  27320. this._registerTransientComponents();
  27321. if (this.isReady()) {
  27322. this.onReadyObservable.notifyObservers(this);
  27323. this.onReadyObservable.clear();
  27324. this._executeWhenReadyTimeoutId = -1;
  27325. return;
  27326. }
  27327. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27328. _this._checkIsReady();
  27329. }, 150);
  27330. };
  27331. // Animations
  27332. /**
  27333. * Will start the animation sequence of a given target
  27334. * @param target defines the target
  27335. * @param from defines from which frame should animation start
  27336. * @param to defines until which frame should animation run.
  27337. * @param weight defines the weight to apply to the animation (1.0 by default)
  27338. * @param loop defines if the animation loops
  27339. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27340. * @param onAnimationEnd defines the function to be executed when the animation ends
  27341. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27342. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27343. * @returns the animatable object created for this animation
  27344. */
  27345. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27346. if (weight === void 0) { weight = 1.0; }
  27347. if (speedRatio === void 0) { speedRatio = 1.0; }
  27348. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27349. returnedAnimatable.weight = weight;
  27350. return returnedAnimatable;
  27351. };
  27352. /**
  27353. * Will start the animation sequence of a given target
  27354. * @param target defines the target
  27355. * @param from defines from which frame should animation start
  27356. * @param to defines until which frame should animation run.
  27357. * @param loop defines if the animation loops
  27358. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27359. * @param onAnimationEnd defines the function to be executed when the animation ends
  27360. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27361. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27362. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27363. * @returns the animatable object created for this animation
  27364. */
  27365. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27366. if (speedRatio === void 0) { speedRatio = 1.0; }
  27367. if (stopCurrent === void 0) { stopCurrent = true; }
  27368. if (from > to && speedRatio > 0) {
  27369. speedRatio *= -1;
  27370. }
  27371. if (stopCurrent) {
  27372. this.stopAnimation(target, undefined, targetMask);
  27373. }
  27374. if (!animatable) {
  27375. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27376. }
  27377. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27378. // Local animations
  27379. if (target.animations && shouldRunTargetAnimations) {
  27380. animatable.appendAnimations(target, target.animations);
  27381. }
  27382. // Children animations
  27383. if (target.getAnimatables) {
  27384. var animatables = target.getAnimatables();
  27385. for (var index = 0; index < animatables.length; index++) {
  27386. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27387. }
  27388. }
  27389. animatable.reset();
  27390. return animatable;
  27391. };
  27392. /**
  27393. * Begin a new animation on a given node
  27394. * @param target defines the target where the animation will take place
  27395. * @param animations defines the list of animations to start
  27396. * @param from defines the initial value
  27397. * @param to defines the final value
  27398. * @param loop defines if you want animation to loop (off by default)
  27399. * @param speedRatio defines the speed ratio to apply to all animations
  27400. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27401. * @returns the list of created animatables
  27402. */
  27403. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27404. if (speedRatio === undefined) {
  27405. speedRatio = 1.0;
  27406. }
  27407. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27408. return animatable;
  27409. };
  27410. /**
  27411. * Begin a new animation on a given node and its hierarchy
  27412. * @param target defines the root node where the animation will take place
  27413. * @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.
  27414. * @param animations defines the list of animations to start
  27415. * @param from defines the initial value
  27416. * @param to defines the final value
  27417. * @param loop defines if you want animation to loop (off by default)
  27418. * @param speedRatio defines the speed ratio to apply to all animations
  27419. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27420. * @returns the list of animatables created for all nodes
  27421. */
  27422. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27423. var children = target.getDescendants(directDescendantsOnly);
  27424. var result = [];
  27425. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27426. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27427. var child = children_1[_i];
  27428. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27429. }
  27430. return result;
  27431. };
  27432. /**
  27433. * Gets the animatable associated with a specific target
  27434. * @param target defines the target of the animatable
  27435. * @returns the required animatable if found
  27436. */
  27437. Scene.prototype.getAnimatableByTarget = function (target) {
  27438. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27439. if (this._activeAnimatables[index].target === target) {
  27440. return this._activeAnimatables[index];
  27441. }
  27442. }
  27443. return null;
  27444. };
  27445. /**
  27446. * Gets all animatables associated with a given target
  27447. * @param target defines the target to look animatables for
  27448. * @returns an array of Animatables
  27449. */
  27450. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27451. var result = [];
  27452. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27453. if (this._activeAnimatables[index].target === target) {
  27454. result.push(this._activeAnimatables[index]);
  27455. }
  27456. }
  27457. return result;
  27458. };
  27459. Object.defineProperty(Scene.prototype, "animatables", {
  27460. /**
  27461. * Gets all animatable attached to the scene
  27462. */
  27463. get: function () {
  27464. return this._activeAnimatables;
  27465. },
  27466. enumerable: true,
  27467. configurable: true
  27468. });
  27469. /**
  27470. * Will stop the animation of the given target
  27471. * @param target - the target
  27472. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27473. * @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)
  27474. */
  27475. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27476. var animatables = this.getAllAnimatablesByTarget(target);
  27477. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27478. var animatable = animatables_1[_i];
  27479. animatable.stop(animationName, targetMask);
  27480. }
  27481. };
  27482. /**
  27483. * Stops and removes all animations that have been applied to the scene
  27484. */
  27485. Scene.prototype.stopAllAnimations = function () {
  27486. if (this._activeAnimatables) {
  27487. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27488. this._activeAnimatables[i].stop();
  27489. }
  27490. this._activeAnimatables = [];
  27491. }
  27492. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27493. var group = _a[_i];
  27494. group.stop();
  27495. }
  27496. };
  27497. Scene.prototype._animate = function () {
  27498. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27499. return;
  27500. }
  27501. // Getting time
  27502. var now = BABYLON.Tools.Now;
  27503. if (!this._animationTimeLast) {
  27504. if (this._pendingData.length > 0) {
  27505. return;
  27506. }
  27507. this._animationTimeLast = now;
  27508. }
  27509. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27510. this._animationTime += deltaTime;
  27511. this._animationTimeLast = now;
  27512. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27513. this._activeAnimatables[index]._animate(this._animationTime);
  27514. }
  27515. // Late animation bindings
  27516. this._processLateAnimationBindings();
  27517. };
  27518. /** @hidden */
  27519. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27520. var target = runtimeAnimation.target;
  27521. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27522. if (!target._lateAnimationHolders) {
  27523. target._lateAnimationHolders = {};
  27524. }
  27525. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27526. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27527. totalWeight: 0,
  27528. animations: [],
  27529. originalValue: originalValue
  27530. };
  27531. }
  27532. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27533. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27534. };
  27535. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27536. var normalizer = 1.0;
  27537. var finalPosition = BABYLON.Tmp.Vector3[0];
  27538. var finalScaling = BABYLON.Tmp.Vector3[1];
  27539. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27540. var startIndex = 0;
  27541. var originalAnimation = holder.animations[0];
  27542. var originalValue = holder.originalValue;
  27543. var scale = 1;
  27544. if (holder.totalWeight < 1.0) {
  27545. // We need to mix the original value in
  27546. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27547. scale = 1.0 - holder.totalWeight;
  27548. }
  27549. else {
  27550. startIndex = 1;
  27551. // We need to normalize the weights
  27552. normalizer = holder.totalWeight;
  27553. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27554. scale = originalAnimation.weight / normalizer;
  27555. if (scale == 1) {
  27556. return originalAnimation.currentValue;
  27557. }
  27558. }
  27559. finalScaling.scaleInPlace(scale);
  27560. finalPosition.scaleInPlace(scale);
  27561. finalQuaternion.scaleInPlace(scale);
  27562. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27563. var runtimeAnimation = holder.animations[animIndex];
  27564. var scale = runtimeAnimation.weight / normalizer;
  27565. var currentPosition = BABYLON.Tmp.Vector3[2];
  27566. var currentScaling = BABYLON.Tmp.Vector3[3];
  27567. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27568. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27569. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27570. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27571. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27572. }
  27573. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27574. return originalAnimation._workValue;
  27575. };
  27576. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27577. var originalAnimation = holder.animations[0];
  27578. var originalValue = holder.originalValue;
  27579. if (holder.animations.length === 1) {
  27580. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27581. return refQuaternion;
  27582. }
  27583. var normalizer = 1.0;
  27584. var quaternions;
  27585. var weights;
  27586. if (holder.totalWeight < 1.0) {
  27587. var scale = 1.0 - holder.totalWeight;
  27588. quaternions = [];
  27589. weights = [];
  27590. quaternions.push(originalValue);
  27591. weights.push(scale);
  27592. }
  27593. else {
  27594. if (holder.animations.length === 2) { // Slerp as soon as we can
  27595. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27596. return refQuaternion;
  27597. }
  27598. quaternions = [];
  27599. weights = [];
  27600. normalizer = holder.totalWeight;
  27601. }
  27602. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27603. var runtimeAnimation = holder.animations[animIndex];
  27604. quaternions.push(runtimeAnimation.currentValue);
  27605. weights.push(runtimeAnimation.weight / normalizer);
  27606. }
  27607. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27608. var cumulativeAmount = 0;
  27609. var cumulativeQuaternion = null;
  27610. for (var index = 0; index < quaternions.length;) {
  27611. if (!cumulativeQuaternion) {
  27612. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27613. cumulativeQuaternion = refQuaternion;
  27614. cumulativeAmount = weights[index] + weights[index + 1];
  27615. index += 2;
  27616. continue;
  27617. }
  27618. cumulativeAmount += weights[index];
  27619. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27620. index++;
  27621. }
  27622. return cumulativeQuaternion;
  27623. };
  27624. Scene.prototype._processLateAnimationBindings = function () {
  27625. if (!this._registeredForLateAnimationBindings.length) {
  27626. return;
  27627. }
  27628. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27629. var target = this._registeredForLateAnimationBindings.data[index];
  27630. for (var path in target._lateAnimationHolders) {
  27631. var holder = target._lateAnimationHolders[path];
  27632. var originalAnimation = holder.animations[0];
  27633. var originalValue = holder.originalValue;
  27634. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27635. var finalValue = target[path];
  27636. if (matrixDecomposeMode) {
  27637. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27638. }
  27639. else {
  27640. var quaternionMode = originalValue.w !== undefined;
  27641. if (quaternionMode) {
  27642. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27643. }
  27644. else {
  27645. var startIndex = 0;
  27646. var normalizer = 1.0;
  27647. if (holder.totalWeight < 1.0) {
  27648. // We need to mix the original value in
  27649. if (originalValue.scale) {
  27650. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27651. }
  27652. else {
  27653. finalValue = originalValue * (1.0 - holder.totalWeight);
  27654. }
  27655. }
  27656. else {
  27657. // We need to normalize the weights
  27658. normalizer = holder.totalWeight;
  27659. var scale_1 = originalAnimation.weight / normalizer;
  27660. if (scale_1 !== 1) {
  27661. if (originalAnimation.currentValue.scale) {
  27662. finalValue = originalAnimation.currentValue.scale(scale_1);
  27663. }
  27664. else {
  27665. finalValue = originalAnimation.currentValue * scale_1;
  27666. }
  27667. }
  27668. else {
  27669. finalValue = originalAnimation.currentValue;
  27670. }
  27671. startIndex = 1;
  27672. }
  27673. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27674. var runtimeAnimation = holder.animations[animIndex];
  27675. var scale = runtimeAnimation.weight / normalizer;
  27676. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27677. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27678. }
  27679. else {
  27680. finalValue += runtimeAnimation.currentValue * scale;
  27681. }
  27682. }
  27683. }
  27684. }
  27685. target[path] = finalValue;
  27686. }
  27687. target._lateAnimationHolders = {};
  27688. }
  27689. this._registeredForLateAnimationBindings.reset();
  27690. };
  27691. // Matrix
  27692. /** @hidden */
  27693. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27694. this._useAlternateCameraConfiguration = active;
  27695. };
  27696. /**
  27697. * Gets the current view matrix
  27698. * @returns a Matrix
  27699. */
  27700. Scene.prototype.getViewMatrix = function () {
  27701. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27702. };
  27703. /**
  27704. * Gets the current projection matrix
  27705. * @returns a Matrix
  27706. */
  27707. Scene.prototype.getProjectionMatrix = function () {
  27708. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27709. };
  27710. /**
  27711. * Gets the current transform matrix
  27712. * @returns a Matrix made of View * Projection
  27713. */
  27714. Scene.prototype.getTransformMatrix = function () {
  27715. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27716. };
  27717. /**
  27718. * Sets the current transform matrix
  27719. * @param view defines the View matrix to use
  27720. * @param projection defines the Projection matrix to use
  27721. */
  27722. Scene.prototype.setTransformMatrix = function (view, projection) {
  27723. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27724. return;
  27725. }
  27726. this._viewUpdateFlag = view.updateFlag;
  27727. this._projectionUpdateFlag = projection.updateFlag;
  27728. this._viewMatrix = view;
  27729. this._projectionMatrix = projection;
  27730. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27731. // Update frustum
  27732. if (!this._frustumPlanes) {
  27733. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27734. }
  27735. else {
  27736. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27737. }
  27738. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27739. var otherCamera = this.activeCamera._alternateCamera;
  27740. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27741. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27742. }
  27743. if (this._sceneUbo.useUbo) {
  27744. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27745. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27746. this._sceneUbo.update();
  27747. }
  27748. };
  27749. /** @hidden */
  27750. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27751. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27752. return;
  27753. }
  27754. this._alternateViewUpdateFlag = view.updateFlag;
  27755. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27756. this._alternateViewMatrix = view;
  27757. this._alternateProjectionMatrix = projection;
  27758. if (!this._alternateTransformMatrix) {
  27759. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27760. }
  27761. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27762. if (!this._alternateSceneUbo) {
  27763. this._createAlternateUbo();
  27764. }
  27765. if (this._alternateSceneUbo.useUbo) {
  27766. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27767. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27768. this._alternateSceneUbo.update();
  27769. }
  27770. };
  27771. /**
  27772. * Gets the uniform buffer used to store scene data
  27773. * @returns a UniformBuffer
  27774. */
  27775. Scene.prototype.getSceneUniformBuffer = function () {
  27776. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27777. };
  27778. /**
  27779. * Gets an unique (relatively to the current scene) Id
  27780. * @returns an unique number for the scene
  27781. */
  27782. Scene.prototype.getUniqueId = function () {
  27783. var result = Scene._uniqueIdCounter;
  27784. Scene._uniqueIdCounter++;
  27785. return result;
  27786. };
  27787. /**
  27788. * Add a mesh to the list of scene's meshes
  27789. * @param newMesh defines the mesh to add
  27790. * @param recursive if all child meshes should also be added to the scene
  27791. */
  27792. Scene.prototype.addMesh = function (newMesh, recursive) {
  27793. var _this = this;
  27794. if (recursive === void 0) { recursive = false; }
  27795. this.meshes.push(newMesh);
  27796. //notify the collision coordinator
  27797. if (this.collisionCoordinator) {
  27798. this.collisionCoordinator.onMeshAdded(newMesh);
  27799. }
  27800. newMesh._resyncLightSources();
  27801. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27802. if (recursive) {
  27803. newMesh.getChildMeshes().forEach(function (m) {
  27804. _this.addMesh(m);
  27805. });
  27806. }
  27807. };
  27808. /**
  27809. * Remove a mesh for the list of scene's meshes
  27810. * @param toRemove defines the mesh to remove
  27811. * @param recursive if all child meshes should also be removed from the scene
  27812. * @returns the index where the mesh was in the mesh list
  27813. */
  27814. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27815. var _this = this;
  27816. if (recursive === void 0) { recursive = false; }
  27817. var index = this.meshes.indexOf(toRemove);
  27818. if (index !== -1) {
  27819. // Remove from the scene if mesh found
  27820. this.meshes[index] = this.meshes[this.meshes.length - 1];
  27821. this.meshes.pop();
  27822. }
  27823. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27824. if (recursive) {
  27825. toRemove.getChildMeshes().forEach(function (m) {
  27826. _this.removeMesh(m);
  27827. });
  27828. }
  27829. return index;
  27830. };
  27831. /**
  27832. * Add a transform node to the list of scene's transform nodes
  27833. * @param newTransformNode defines the transform node to add
  27834. */
  27835. Scene.prototype.addTransformNode = function (newTransformNode) {
  27836. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  27837. this.transformNodes.push(newTransformNode);
  27838. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27839. };
  27840. /**
  27841. * Remove a transform node for the list of scene's transform nodes
  27842. * @param toRemove defines the transform node to remove
  27843. * @returns the index where the transform node was in the transform node list
  27844. */
  27845. Scene.prototype.removeTransformNode = function (toRemove) {
  27846. var index = toRemove._indexInSceneTransformNodesArray;
  27847. if (index !== -1) {
  27848. if (index !== this.transformNodes.length - 1) {
  27849. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  27850. this.transformNodes[index] = lastNode;
  27851. lastNode._indexInSceneTransformNodesArray = index;
  27852. }
  27853. toRemove._indexInSceneTransformNodesArray = -1;
  27854. this.transformNodes.pop();
  27855. }
  27856. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27857. return index;
  27858. };
  27859. /**
  27860. * Remove a skeleton for the list of scene's skeletons
  27861. * @param toRemove defines the skeleton to remove
  27862. * @returns the index where the skeleton was in the skeleton list
  27863. */
  27864. Scene.prototype.removeSkeleton = function (toRemove) {
  27865. var index = this.skeletons.indexOf(toRemove);
  27866. if (index !== -1) {
  27867. // Remove from the scene if found
  27868. this.skeletons.splice(index, 1);
  27869. }
  27870. return index;
  27871. };
  27872. /**
  27873. * Remove a morph target for the list of scene's morph targets
  27874. * @param toRemove defines the morph target to remove
  27875. * @returns the index where the morph target was in the morph target list
  27876. */
  27877. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27878. var index = this.morphTargetManagers.indexOf(toRemove);
  27879. if (index !== -1) {
  27880. // Remove from the scene if found
  27881. this.morphTargetManagers.splice(index, 1);
  27882. }
  27883. return index;
  27884. };
  27885. /**
  27886. * Remove a light for the list of scene's lights
  27887. * @param toRemove defines the light to remove
  27888. * @returns the index where the light was in the light list
  27889. */
  27890. Scene.prototype.removeLight = function (toRemove) {
  27891. var index = this.lights.indexOf(toRemove);
  27892. if (index !== -1) {
  27893. // Remove from meshes
  27894. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27895. var mesh = _a[_i];
  27896. mesh._removeLightSource(toRemove);
  27897. }
  27898. // Remove from the scene if mesh found
  27899. this.lights.splice(index, 1);
  27900. this.sortLightsByPriority();
  27901. }
  27902. this.onLightRemovedObservable.notifyObservers(toRemove);
  27903. return index;
  27904. };
  27905. /**
  27906. * Remove a camera for the list of scene's cameras
  27907. * @param toRemove defines the camera to remove
  27908. * @returns the index where the camera was in the camera list
  27909. */
  27910. Scene.prototype.removeCamera = function (toRemove) {
  27911. var index = this.cameras.indexOf(toRemove);
  27912. if (index !== -1) {
  27913. // Remove from the scene if mesh found
  27914. this.cameras.splice(index, 1);
  27915. }
  27916. // Remove from activeCameras
  27917. var index2 = this.activeCameras.indexOf(toRemove);
  27918. if (index2 !== -1) {
  27919. // Remove from the scene if mesh found
  27920. this.activeCameras.splice(index2, 1);
  27921. }
  27922. // Reset the activeCamera
  27923. if (this.activeCamera === toRemove) {
  27924. if (this.cameras.length > 0) {
  27925. this.activeCamera = this.cameras[0];
  27926. }
  27927. else {
  27928. this.activeCamera = null;
  27929. }
  27930. }
  27931. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27932. return index;
  27933. };
  27934. /**
  27935. * Remove a particle system for the list of scene's particle systems
  27936. * @param toRemove defines the particle system to remove
  27937. * @returns the index where the particle system was in the particle system list
  27938. */
  27939. Scene.prototype.removeParticleSystem = function (toRemove) {
  27940. var index = this.particleSystems.indexOf(toRemove);
  27941. if (index !== -1) {
  27942. this.particleSystems.splice(index, 1);
  27943. }
  27944. return index;
  27945. };
  27946. /**
  27947. * Remove a animation for the list of scene's animations
  27948. * @param toRemove defines the animation to remove
  27949. * @returns the index where the animation was in the animation list
  27950. */
  27951. Scene.prototype.removeAnimation = function (toRemove) {
  27952. var index = this.animations.indexOf(toRemove);
  27953. if (index !== -1) {
  27954. this.animations.splice(index, 1);
  27955. }
  27956. return index;
  27957. };
  27958. /**
  27959. * Removes the given animation group from this scene.
  27960. * @param toRemove The animation group to remove
  27961. * @returns The index of the removed animation group
  27962. */
  27963. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27964. var index = this.animationGroups.indexOf(toRemove);
  27965. if (index !== -1) {
  27966. this.animationGroups.splice(index, 1);
  27967. }
  27968. return index;
  27969. };
  27970. /**
  27971. * Removes the given multi-material from this scene.
  27972. * @param toRemove The multi-material to remove
  27973. * @returns The index of the removed multi-material
  27974. */
  27975. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27976. var index = this.multiMaterials.indexOf(toRemove);
  27977. if (index !== -1) {
  27978. this.multiMaterials.splice(index, 1);
  27979. }
  27980. return index;
  27981. };
  27982. /**
  27983. * Removes the given material from this scene.
  27984. * @param toRemove The material to remove
  27985. * @returns The index of the removed material
  27986. */
  27987. Scene.prototype.removeMaterial = function (toRemove) {
  27988. var index = toRemove._indexInSceneMaterialArray;
  27989. if (index !== -1) {
  27990. if (index !== this.materials.length - 1) {
  27991. var lastMaterial = this.materials[this.materials.length - 1];
  27992. this.materials[index] = lastMaterial;
  27993. lastMaterial._indexInSceneMaterialArray = index;
  27994. }
  27995. toRemove._indexInSceneMaterialArray = -1;
  27996. this.materials.pop();
  27997. }
  27998. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27999. return index;
  28000. };
  28001. /**
  28002. * Removes the given action manager from this scene.
  28003. * @param toRemove The action manager to remove
  28004. * @returns The index of the removed action manager
  28005. */
  28006. Scene.prototype.removeActionManager = function (toRemove) {
  28007. var index = this.actionManagers.indexOf(toRemove);
  28008. if (index !== -1) {
  28009. this.actionManagers.splice(index, 1);
  28010. }
  28011. return index;
  28012. };
  28013. /**
  28014. * Removes the given texture from this scene.
  28015. * @param toRemove The texture to remove
  28016. * @returns The index of the removed texture
  28017. */
  28018. Scene.prototype.removeTexture = function (toRemove) {
  28019. var index = this.textures.indexOf(toRemove);
  28020. if (index !== -1) {
  28021. this.textures.splice(index, 1);
  28022. }
  28023. this.onTextureRemovedObservable.notifyObservers(toRemove);
  28024. return index;
  28025. };
  28026. /**
  28027. * Adds the given light to this scene
  28028. * @param newLight The light to add
  28029. */
  28030. Scene.prototype.addLight = function (newLight) {
  28031. this.lights.push(newLight);
  28032. this.sortLightsByPriority();
  28033. // Add light to all meshes (To support if the light is removed and then readded)
  28034. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28035. var mesh = _a[_i];
  28036. if (mesh._lightSources.indexOf(newLight) === -1) {
  28037. mesh._lightSources.push(newLight);
  28038. mesh._resyncLightSources();
  28039. }
  28040. }
  28041. this.onNewLightAddedObservable.notifyObservers(newLight);
  28042. };
  28043. /**
  28044. * Sorts the list list based on light priorities
  28045. */
  28046. Scene.prototype.sortLightsByPriority = function () {
  28047. if (this.requireLightSorting) {
  28048. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28049. }
  28050. };
  28051. /**
  28052. * Adds the given camera to this scene
  28053. * @param newCamera The camera to add
  28054. */
  28055. Scene.prototype.addCamera = function (newCamera) {
  28056. this.cameras.push(newCamera);
  28057. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28058. };
  28059. /**
  28060. * Adds the given skeleton to this scene
  28061. * @param newSkeleton The skeleton to add
  28062. */
  28063. Scene.prototype.addSkeleton = function (newSkeleton) {
  28064. this.skeletons.push(newSkeleton);
  28065. };
  28066. /**
  28067. * Adds the given particle system to this scene
  28068. * @param newParticleSystem The particle system to add
  28069. */
  28070. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28071. this.particleSystems.push(newParticleSystem);
  28072. };
  28073. /**
  28074. * Adds the given animation to this scene
  28075. * @param newAnimation The animation to add
  28076. */
  28077. Scene.prototype.addAnimation = function (newAnimation) {
  28078. this.animations.push(newAnimation);
  28079. };
  28080. /**
  28081. * Adds the given animation group to this scene.
  28082. * @param newAnimationGroup The animation group to add
  28083. */
  28084. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28085. this.animationGroups.push(newAnimationGroup);
  28086. };
  28087. /**
  28088. * Adds the given multi-material to this scene
  28089. * @param newMultiMaterial The multi-material to add
  28090. */
  28091. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28092. this.multiMaterials.push(newMultiMaterial);
  28093. };
  28094. /**
  28095. * Adds the given material to this scene
  28096. * @param newMaterial The material to add
  28097. */
  28098. Scene.prototype.addMaterial = function (newMaterial) {
  28099. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28100. this.materials.push(newMaterial);
  28101. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28102. };
  28103. /**
  28104. * Adds the given morph target to this scene
  28105. * @param newMorphTargetManager The morph target to add
  28106. */
  28107. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28108. this.morphTargetManagers.push(newMorphTargetManager);
  28109. };
  28110. /**
  28111. * Adds the given geometry to this scene
  28112. * @param newGeometry The geometry to add
  28113. */
  28114. Scene.prototype.addGeometry = function (newGeometry) {
  28115. if (this.geometriesById) {
  28116. this.geometriesById[newGeometry.id] = this.geometries.length;
  28117. }
  28118. this.geometries.push(newGeometry);
  28119. };
  28120. /**
  28121. * Adds the given action manager to this scene
  28122. * @param newActionManager The action manager to add
  28123. */
  28124. Scene.prototype.addActionManager = function (newActionManager) {
  28125. this.actionManagers.push(newActionManager);
  28126. };
  28127. /**
  28128. * Adds the given texture to this scene.
  28129. * @param newTexture The texture to add
  28130. */
  28131. Scene.prototype.addTexture = function (newTexture) {
  28132. this.textures.push(newTexture);
  28133. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28134. };
  28135. /**
  28136. * Switch active camera
  28137. * @param newCamera defines the new active camera
  28138. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28139. */
  28140. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28141. if (attachControl === void 0) { attachControl = true; }
  28142. var canvas = this._engine.getRenderingCanvas();
  28143. if (!canvas) {
  28144. return;
  28145. }
  28146. if (this.activeCamera) {
  28147. this.activeCamera.detachControl(canvas);
  28148. }
  28149. this.activeCamera = newCamera;
  28150. if (attachControl) {
  28151. newCamera.attachControl(canvas);
  28152. }
  28153. };
  28154. /**
  28155. * sets the active camera of the scene using its ID
  28156. * @param id defines the camera's ID
  28157. * @return the new active camera or null if none found.
  28158. */
  28159. Scene.prototype.setActiveCameraByID = function (id) {
  28160. var camera = this.getCameraByID(id);
  28161. if (camera) {
  28162. this.activeCamera = camera;
  28163. return camera;
  28164. }
  28165. return null;
  28166. };
  28167. /**
  28168. * sets the active camera of the scene using its name
  28169. * @param name defines the camera's name
  28170. * @returns the new active camera or null if none found.
  28171. */
  28172. Scene.prototype.setActiveCameraByName = function (name) {
  28173. var camera = this.getCameraByName(name);
  28174. if (camera) {
  28175. this.activeCamera = camera;
  28176. return camera;
  28177. }
  28178. return null;
  28179. };
  28180. /**
  28181. * get an animation group using its name
  28182. * @param name defines the material's name
  28183. * @return the animation group or null if none found.
  28184. */
  28185. Scene.prototype.getAnimationGroupByName = function (name) {
  28186. for (var index = 0; index < this.animationGroups.length; index++) {
  28187. if (this.animationGroups[index].name === name) {
  28188. return this.animationGroups[index];
  28189. }
  28190. }
  28191. return null;
  28192. };
  28193. /**
  28194. * get a material using its id
  28195. * @param id defines the material's ID
  28196. * @return the material or null if none found.
  28197. */
  28198. Scene.prototype.getMaterialByID = function (id) {
  28199. for (var index = 0; index < this.materials.length; index++) {
  28200. if (this.materials[index].id === id) {
  28201. return this.materials[index];
  28202. }
  28203. }
  28204. return null;
  28205. };
  28206. /**
  28207. * Gets a material using its name
  28208. * @param name defines the material's name
  28209. * @return the material or null if none found.
  28210. */
  28211. Scene.prototype.getMaterialByName = function (name) {
  28212. for (var index = 0; index < this.materials.length; index++) {
  28213. if (this.materials[index].name === name) {
  28214. return this.materials[index];
  28215. }
  28216. }
  28217. return null;
  28218. };
  28219. /**
  28220. * Gets a camera using its id
  28221. * @param id defines the id to look for
  28222. * @returns the camera or null if not found
  28223. */
  28224. Scene.prototype.getCameraByID = function (id) {
  28225. for (var index = 0; index < this.cameras.length; index++) {
  28226. if (this.cameras[index].id === id) {
  28227. return this.cameras[index];
  28228. }
  28229. }
  28230. return null;
  28231. };
  28232. /**
  28233. * Gets a camera using its unique id
  28234. * @param uniqueId defines the unique id to look for
  28235. * @returns the camera or null if not found
  28236. */
  28237. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28238. for (var index = 0; index < this.cameras.length; index++) {
  28239. if (this.cameras[index].uniqueId === uniqueId) {
  28240. return this.cameras[index];
  28241. }
  28242. }
  28243. return null;
  28244. };
  28245. /**
  28246. * Gets a camera using its name
  28247. * @param name defines the camera's name
  28248. * @return the camera or null if none found.
  28249. */
  28250. Scene.prototype.getCameraByName = function (name) {
  28251. for (var index = 0; index < this.cameras.length; index++) {
  28252. if (this.cameras[index].name === name) {
  28253. return this.cameras[index];
  28254. }
  28255. }
  28256. return null;
  28257. };
  28258. /**
  28259. * Gets a bone using its id
  28260. * @param id defines the bone's id
  28261. * @return the bone or null if not found
  28262. */
  28263. Scene.prototype.getBoneByID = function (id) {
  28264. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28265. var skeleton = this.skeletons[skeletonIndex];
  28266. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28267. if (skeleton.bones[boneIndex].id === id) {
  28268. return skeleton.bones[boneIndex];
  28269. }
  28270. }
  28271. }
  28272. return null;
  28273. };
  28274. /**
  28275. * Gets a bone using its id
  28276. * @param name defines the bone's name
  28277. * @return the bone or null if not found
  28278. */
  28279. Scene.prototype.getBoneByName = function (name) {
  28280. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28281. var skeleton = this.skeletons[skeletonIndex];
  28282. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28283. if (skeleton.bones[boneIndex].name === name) {
  28284. return skeleton.bones[boneIndex];
  28285. }
  28286. }
  28287. }
  28288. return null;
  28289. };
  28290. /**
  28291. * Gets a light node using its name
  28292. * @param name defines the the light's name
  28293. * @return the light or null if none found.
  28294. */
  28295. Scene.prototype.getLightByName = function (name) {
  28296. for (var index = 0; index < this.lights.length; index++) {
  28297. if (this.lights[index].name === name) {
  28298. return this.lights[index];
  28299. }
  28300. }
  28301. return null;
  28302. };
  28303. /**
  28304. * Gets a light node using its id
  28305. * @param id defines the light's id
  28306. * @return the light or null if none found.
  28307. */
  28308. Scene.prototype.getLightByID = function (id) {
  28309. for (var index = 0; index < this.lights.length; index++) {
  28310. if (this.lights[index].id === id) {
  28311. return this.lights[index];
  28312. }
  28313. }
  28314. return null;
  28315. };
  28316. /**
  28317. * Gets a light node using its scene-generated unique ID
  28318. * @param uniqueId defines the light's unique id
  28319. * @return the light or null if none found.
  28320. */
  28321. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28322. for (var index = 0; index < this.lights.length; index++) {
  28323. if (this.lights[index].uniqueId === uniqueId) {
  28324. return this.lights[index];
  28325. }
  28326. }
  28327. return null;
  28328. };
  28329. /**
  28330. * Gets a particle system by id
  28331. * @param id defines the particle system id
  28332. * @return the corresponding system or null if none found
  28333. */
  28334. Scene.prototype.getParticleSystemByID = function (id) {
  28335. for (var index = 0; index < this.particleSystems.length; index++) {
  28336. if (this.particleSystems[index].id === id) {
  28337. return this.particleSystems[index];
  28338. }
  28339. }
  28340. return null;
  28341. };
  28342. /**
  28343. * Gets a geometry using its ID
  28344. * @param id defines the geometry's id
  28345. * @return the geometry or null if none found.
  28346. */
  28347. Scene.prototype.getGeometryByID = function (id) {
  28348. if (this.geometriesById) {
  28349. var index_1 = this.geometriesById[id];
  28350. if (index_1 !== undefined) {
  28351. return this.geometries[index_1];
  28352. }
  28353. }
  28354. else {
  28355. for (var index = 0; index < this.geometries.length; index++) {
  28356. if (this.geometries[index].id === id) {
  28357. return this.geometries[index];
  28358. }
  28359. }
  28360. }
  28361. return null;
  28362. };
  28363. /**
  28364. * Add a new geometry to this scene
  28365. * @param geometry defines the geometry to be added to the scene.
  28366. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28367. * @return a boolean defining if the geometry was added or not
  28368. */
  28369. Scene.prototype.pushGeometry = function (geometry, force) {
  28370. if (!force && this.getGeometryByID(geometry.id)) {
  28371. return false;
  28372. }
  28373. this.addGeometry(geometry);
  28374. //notify the collision coordinator
  28375. if (this.collisionCoordinator) {
  28376. this.collisionCoordinator.onGeometryAdded(geometry);
  28377. }
  28378. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28379. return true;
  28380. };
  28381. /**
  28382. * Removes an existing geometry
  28383. * @param geometry defines the geometry to be removed from the scene
  28384. * @return a boolean defining if the geometry was removed or not
  28385. */
  28386. Scene.prototype.removeGeometry = function (geometry) {
  28387. var index;
  28388. if (this.geometriesById) {
  28389. index = this.geometriesById[geometry.id];
  28390. if (index === undefined) {
  28391. return false;
  28392. }
  28393. }
  28394. else {
  28395. index = this.geometries.indexOf(geometry);
  28396. if (index < 0) {
  28397. return false;
  28398. }
  28399. }
  28400. if (index !== this.geometries.length - 1) {
  28401. var lastGeometry = this.geometries[this.geometries.length - 1];
  28402. this.geometries[index] = lastGeometry;
  28403. if (this.geometriesById) {
  28404. this.geometriesById[lastGeometry.id] = index;
  28405. this.geometriesById[geometry.id] = undefined;
  28406. }
  28407. }
  28408. this.geometries.pop();
  28409. //notify the collision coordinator
  28410. if (this.collisionCoordinator) {
  28411. this.collisionCoordinator.onGeometryDeleted(geometry);
  28412. }
  28413. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28414. return true;
  28415. };
  28416. /**
  28417. * Gets the list of geometries attached to the scene
  28418. * @returns an array of Geometry
  28419. */
  28420. Scene.prototype.getGeometries = function () {
  28421. return this.geometries;
  28422. };
  28423. /**
  28424. * Gets the first added mesh found of a given ID
  28425. * @param id defines the id to search for
  28426. * @return the mesh found or null if not found at all
  28427. */
  28428. Scene.prototype.getMeshByID = function (id) {
  28429. for (var index = 0; index < this.meshes.length; index++) {
  28430. if (this.meshes[index].id === id) {
  28431. return this.meshes[index];
  28432. }
  28433. }
  28434. return null;
  28435. };
  28436. /**
  28437. * Gets a list of meshes using their id
  28438. * @param id defines the id to search for
  28439. * @returns a list of meshes
  28440. */
  28441. Scene.prototype.getMeshesByID = function (id) {
  28442. return this.meshes.filter(function (m) {
  28443. return m.id === id;
  28444. });
  28445. };
  28446. /**
  28447. * Gets the first added transform node found of a given ID
  28448. * @param id defines the id to search for
  28449. * @return the found transform node or null if not found at all.
  28450. */
  28451. Scene.prototype.getTransformNodeByID = function (id) {
  28452. for (var index = 0; index < this.transformNodes.length; index++) {
  28453. if (this.transformNodes[index].id === id) {
  28454. return this.transformNodes[index];
  28455. }
  28456. }
  28457. return null;
  28458. };
  28459. /**
  28460. * Gets a list of transform nodes using their id
  28461. * @param id defines the id to search for
  28462. * @returns a list of transform nodes
  28463. */
  28464. Scene.prototype.getTransformNodesByID = function (id) {
  28465. return this.transformNodes.filter(function (m) {
  28466. return m.id === id;
  28467. });
  28468. };
  28469. /**
  28470. * Gets a mesh with its auto-generated unique id
  28471. * @param uniqueId defines the unique id to search for
  28472. * @return the found mesh or null if not found at all.
  28473. */
  28474. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28475. for (var index = 0; index < this.meshes.length; index++) {
  28476. if (this.meshes[index].uniqueId === uniqueId) {
  28477. return this.meshes[index];
  28478. }
  28479. }
  28480. return null;
  28481. };
  28482. /**
  28483. * Gets a the last added mesh using a given id
  28484. * @param id defines the id to search for
  28485. * @return the found mesh or null if not found at all.
  28486. */
  28487. Scene.prototype.getLastMeshByID = function (id) {
  28488. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28489. if (this.meshes[index].id === id) {
  28490. return this.meshes[index];
  28491. }
  28492. }
  28493. return null;
  28494. };
  28495. /**
  28496. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28497. * @param id defines the id to search for
  28498. * @return the found node or null if not found at all
  28499. */
  28500. Scene.prototype.getLastEntryByID = function (id) {
  28501. var index;
  28502. for (index = this.meshes.length - 1; index >= 0; index--) {
  28503. if (this.meshes[index].id === id) {
  28504. return this.meshes[index];
  28505. }
  28506. }
  28507. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28508. if (this.transformNodes[index].id === id) {
  28509. return this.transformNodes[index];
  28510. }
  28511. }
  28512. for (index = this.cameras.length - 1; index >= 0; index--) {
  28513. if (this.cameras[index].id === id) {
  28514. return this.cameras[index];
  28515. }
  28516. }
  28517. for (index = this.lights.length - 1; index >= 0; index--) {
  28518. if (this.lights[index].id === id) {
  28519. return this.lights[index];
  28520. }
  28521. }
  28522. return null;
  28523. };
  28524. /**
  28525. * Gets a node (Mesh, Camera, Light) using a given id
  28526. * @param id defines the id to search for
  28527. * @return the found node or null if not found at all
  28528. */
  28529. Scene.prototype.getNodeByID = function (id) {
  28530. var mesh = this.getMeshByID(id);
  28531. if (mesh) {
  28532. return mesh;
  28533. }
  28534. var light = this.getLightByID(id);
  28535. if (light) {
  28536. return light;
  28537. }
  28538. var camera = this.getCameraByID(id);
  28539. if (camera) {
  28540. return camera;
  28541. }
  28542. var bone = this.getBoneByID(id);
  28543. return bone;
  28544. };
  28545. /**
  28546. * Gets a node (Mesh, Camera, Light) using a given name
  28547. * @param name defines the name to search for
  28548. * @return the found node or null if not found at all.
  28549. */
  28550. Scene.prototype.getNodeByName = function (name) {
  28551. var mesh = this.getMeshByName(name);
  28552. if (mesh) {
  28553. return mesh;
  28554. }
  28555. var light = this.getLightByName(name);
  28556. if (light) {
  28557. return light;
  28558. }
  28559. var camera = this.getCameraByName(name);
  28560. if (camera) {
  28561. return camera;
  28562. }
  28563. var bone = this.getBoneByName(name);
  28564. return bone;
  28565. };
  28566. /**
  28567. * Gets a mesh using a given name
  28568. * @param name defines the name to search for
  28569. * @return the found mesh or null if not found at all.
  28570. */
  28571. Scene.prototype.getMeshByName = function (name) {
  28572. for (var index = 0; index < this.meshes.length; index++) {
  28573. if (this.meshes[index].name === name) {
  28574. return this.meshes[index];
  28575. }
  28576. }
  28577. return null;
  28578. };
  28579. /**
  28580. * Gets a transform node using a given name
  28581. * @param name defines the name to search for
  28582. * @return the found transform node or null if not found at all.
  28583. */
  28584. Scene.prototype.getTransformNodeByName = function (name) {
  28585. for (var index = 0; index < this.transformNodes.length; index++) {
  28586. if (this.transformNodes[index].name === name) {
  28587. return this.transformNodes[index];
  28588. }
  28589. }
  28590. return null;
  28591. };
  28592. /**
  28593. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28594. * @param id defines the id to search for
  28595. * @return the found skeleton or null if not found at all.
  28596. */
  28597. Scene.prototype.getLastSkeletonByID = function (id) {
  28598. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28599. if (this.skeletons[index].id === id) {
  28600. return this.skeletons[index];
  28601. }
  28602. }
  28603. return null;
  28604. };
  28605. /**
  28606. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28607. * @param id defines the id to search for
  28608. * @return the found skeleton or null if not found at all.
  28609. */
  28610. Scene.prototype.getSkeletonById = function (id) {
  28611. for (var index = 0; index < this.skeletons.length; index++) {
  28612. if (this.skeletons[index].id === id) {
  28613. return this.skeletons[index];
  28614. }
  28615. }
  28616. return null;
  28617. };
  28618. /**
  28619. * Gets a skeleton using a given name
  28620. * @param name defines the name to search for
  28621. * @return the found skeleton or null if not found at all.
  28622. */
  28623. Scene.prototype.getSkeletonByName = function (name) {
  28624. for (var index = 0; index < this.skeletons.length; index++) {
  28625. if (this.skeletons[index].name === name) {
  28626. return this.skeletons[index];
  28627. }
  28628. }
  28629. return null;
  28630. };
  28631. /**
  28632. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28633. * @param id defines the id to search for
  28634. * @return the found morph target manager or null if not found at all.
  28635. */
  28636. Scene.prototype.getMorphTargetManagerById = function (id) {
  28637. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28638. if (this.morphTargetManagers[index].uniqueId === id) {
  28639. return this.morphTargetManagers[index];
  28640. }
  28641. }
  28642. return null;
  28643. };
  28644. /**
  28645. * Gets a boolean indicating if the given mesh is active
  28646. * @param mesh defines the mesh to look for
  28647. * @returns true if the mesh is in the active list
  28648. */
  28649. Scene.prototype.isActiveMesh = function (mesh) {
  28650. return (this._activeMeshes.indexOf(mesh) !== -1);
  28651. };
  28652. Object.defineProperty(Scene.prototype, "uid", {
  28653. /**
  28654. * Return a unique id as a string which can serve as an identifier for the scene
  28655. */
  28656. get: function () {
  28657. if (!this._uid) {
  28658. this._uid = BABYLON.Tools.RandomId();
  28659. }
  28660. return this._uid;
  28661. },
  28662. enumerable: true,
  28663. configurable: true
  28664. });
  28665. /**
  28666. * Add an externaly attached data from its key.
  28667. * This method call will fail and return false, if such key already exists.
  28668. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28669. * @param key the unique key that identifies the data
  28670. * @param data the data object to associate to the key for this Engine instance
  28671. * @return true if no such key were already present and the data was added successfully, false otherwise
  28672. */
  28673. Scene.prototype.addExternalData = function (key, data) {
  28674. if (!this._externalData) {
  28675. this._externalData = new BABYLON.StringDictionary();
  28676. }
  28677. return this._externalData.add(key, data);
  28678. };
  28679. /**
  28680. * Get an externaly attached data from its key
  28681. * @param key the unique key that identifies the data
  28682. * @return the associated data, if present (can be null), or undefined if not present
  28683. */
  28684. Scene.prototype.getExternalData = function (key) {
  28685. if (!this._externalData) {
  28686. return null;
  28687. }
  28688. return this._externalData.get(key);
  28689. };
  28690. /**
  28691. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28692. * @param key the unique key that identifies the data
  28693. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28694. * @return the associated data, can be null if the factory returned null.
  28695. */
  28696. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28697. if (!this._externalData) {
  28698. this._externalData = new BABYLON.StringDictionary();
  28699. }
  28700. return this._externalData.getOrAddWithFactory(key, factory);
  28701. };
  28702. /**
  28703. * Remove an externaly attached data from the Engine instance
  28704. * @param key the unique key that identifies the data
  28705. * @return true if the data was successfully removed, false if it doesn't exist
  28706. */
  28707. Scene.prototype.removeExternalData = function (key) {
  28708. return this._externalData.remove(key);
  28709. };
  28710. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28711. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28712. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28713. var step = _a[_i];
  28714. step.action(mesh, subMesh);
  28715. }
  28716. var material = subMesh.getMaterial();
  28717. if (material !== null && material !== undefined) {
  28718. // Render targets
  28719. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28720. if (this._processedMaterials.indexOf(material) === -1) {
  28721. this._processedMaterials.push(material);
  28722. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28723. }
  28724. }
  28725. // Dispatch
  28726. this._activeIndices.addCount(subMesh.indexCount, false);
  28727. this._renderingManager.dispatch(subMesh, mesh, material);
  28728. }
  28729. }
  28730. };
  28731. /**
  28732. * Clear the processed materials smart array preventing retention point in material dispose.
  28733. */
  28734. Scene.prototype.freeProcessedMaterials = function () {
  28735. this._processedMaterials.dispose();
  28736. };
  28737. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  28738. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  28739. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  28740. * when disposing several meshes in a row or a hierarchy of meshes.
  28741. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  28742. */
  28743. get: function () {
  28744. return this._preventFreeActiveMeshesAndRenderingGroups;
  28745. },
  28746. set: function (value) {
  28747. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  28748. return;
  28749. }
  28750. if (value) {
  28751. this.freeActiveMeshes();
  28752. this.freeRenderingGroups();
  28753. }
  28754. this._preventFreeActiveMeshesAndRenderingGroups = value;
  28755. },
  28756. enumerable: true,
  28757. configurable: true
  28758. });
  28759. /**
  28760. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28761. */
  28762. Scene.prototype.freeActiveMeshes = function () {
  28763. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28764. return;
  28765. }
  28766. this._activeMeshes.dispose();
  28767. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28768. this.activeCamera._activeMeshes.dispose();
  28769. }
  28770. if (this.activeCameras) {
  28771. for (var i = 0; i < this.activeCameras.length; i++) {
  28772. var activeCamera = this.activeCameras[i];
  28773. if (activeCamera && activeCamera._activeMeshes) {
  28774. activeCamera._activeMeshes.dispose();
  28775. }
  28776. }
  28777. }
  28778. };
  28779. /**
  28780. * Clear the info related to rendering groups preventing retention points during dispose.
  28781. */
  28782. Scene.prototype.freeRenderingGroups = function () {
  28783. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28784. return;
  28785. }
  28786. if (this._renderingManager) {
  28787. this._renderingManager.freeRenderingGroups();
  28788. }
  28789. if (this.textures) {
  28790. for (var i = 0; i < this.textures.length; i++) {
  28791. var texture = this.textures[i];
  28792. if (texture && texture.renderList) {
  28793. texture.freeRenderingGroups();
  28794. }
  28795. }
  28796. }
  28797. };
  28798. /** @hidden */
  28799. Scene.prototype._isInIntermediateRendering = function () {
  28800. return this._intermediateRendering;
  28801. };
  28802. /**
  28803. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28804. * @returns the current scene
  28805. */
  28806. Scene.prototype.freezeActiveMeshes = function () {
  28807. if (!this.activeCamera) {
  28808. return this;
  28809. }
  28810. if (!this._frustumPlanes) {
  28811. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28812. }
  28813. this._evaluateActiveMeshes();
  28814. this._activeMeshesFrozen = true;
  28815. return this;
  28816. };
  28817. /**
  28818. * Use this function to restart evaluating active meshes on every frame
  28819. * @returns the current scene
  28820. */
  28821. Scene.prototype.unfreezeActiveMeshes = function () {
  28822. this._activeMeshesFrozen = false;
  28823. return this;
  28824. };
  28825. Scene.prototype._evaluateActiveMeshes = function () {
  28826. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28827. return;
  28828. }
  28829. if (!this.activeCamera) {
  28830. return;
  28831. }
  28832. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28833. this.activeCamera._activeMeshes.reset();
  28834. this._activeMeshes.reset();
  28835. this._renderingManager.reset();
  28836. this._processedMaterials.reset();
  28837. this._activeParticleSystems.reset();
  28838. this._activeSkeletons.reset();
  28839. this._softwareSkinnedMeshes.reset();
  28840. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28841. var step = _a[_i];
  28842. step.action();
  28843. }
  28844. // Determine mesh candidates
  28845. var meshes = this.getActiveMeshCandidates();
  28846. // Check each mesh
  28847. var len = meshes.length;
  28848. for (var i = 0; i < len; i++) {
  28849. var mesh = meshes.data[i];
  28850. if (mesh.isBlocked) {
  28851. continue;
  28852. }
  28853. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28854. if (!mesh.isReady() || !mesh.isEnabled()) {
  28855. continue;
  28856. }
  28857. mesh.computeWorldMatrix();
  28858. // Intersections
  28859. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28860. this._meshesForIntersections.pushNoDuplicate(mesh);
  28861. }
  28862. // Switch to current LOD
  28863. var meshLOD = mesh.getLOD(this.activeCamera);
  28864. if (meshLOD === undefined || meshLOD === null) {
  28865. continue;
  28866. }
  28867. mesh._preActivate();
  28868. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  28869. this._activeMeshes.push(mesh);
  28870. this.activeCamera._activeMeshes.push(mesh);
  28871. mesh._activate(this._renderId);
  28872. if (meshLOD !== mesh) {
  28873. meshLOD._activate(this._renderId);
  28874. }
  28875. this._activeMesh(mesh, meshLOD);
  28876. }
  28877. }
  28878. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28879. // Particle systems
  28880. if (this.particlesEnabled) {
  28881. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28882. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28883. var particleSystem = this.particleSystems[particleIndex];
  28884. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28885. continue;
  28886. }
  28887. var emitter = particleSystem.emitter;
  28888. if (!emitter.position || emitter.isEnabled()) {
  28889. this._activeParticleSystems.push(particleSystem);
  28890. particleSystem.animate();
  28891. this._renderingManager.dispatchParticles(particleSystem);
  28892. }
  28893. }
  28894. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28895. }
  28896. };
  28897. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28898. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28899. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28900. mesh.skeleton.prepare();
  28901. }
  28902. if (!mesh.computeBonesUsingShaders) {
  28903. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28904. }
  28905. }
  28906. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28907. var step = _a[_i];
  28908. step.action(sourceMesh, mesh);
  28909. }
  28910. if (mesh !== undefined && mesh !== null
  28911. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28912. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28913. var len = subMeshes.length;
  28914. for (var i = 0; i < len; i++) {
  28915. var subMesh = subMeshes.data[i];
  28916. this._evaluateSubMesh(subMesh, mesh);
  28917. }
  28918. }
  28919. };
  28920. /**
  28921. * Update the transform matrix to update from the current active camera
  28922. * @param force defines a boolean used to force the update even if cache is up to date
  28923. */
  28924. Scene.prototype.updateTransformMatrix = function (force) {
  28925. if (!this.activeCamera) {
  28926. return;
  28927. }
  28928. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28929. };
  28930. /**
  28931. * 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)
  28932. * @param alternateCamera defines the camera to use
  28933. */
  28934. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28935. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28936. };
  28937. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28938. if (camera && camera._skipRendering) {
  28939. return;
  28940. }
  28941. var engine = this._engine;
  28942. this.activeCamera = camera;
  28943. if (!this.activeCamera) {
  28944. throw new Error("Active camera not set");
  28945. }
  28946. // Viewport
  28947. engine.setViewport(this.activeCamera.viewport);
  28948. // Camera
  28949. this.resetCachedMaterial();
  28950. this._renderId++;
  28951. this.updateTransformMatrix();
  28952. if (camera._alternateCamera) {
  28953. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28954. this._alternateRendering = true;
  28955. }
  28956. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28957. // Meshes
  28958. this._evaluateActiveMeshes();
  28959. // Software skinning
  28960. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28961. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28962. mesh.applySkeleton(mesh.skeleton);
  28963. }
  28964. // Render targets
  28965. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28966. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28967. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28968. }
  28969. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28970. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28971. }
  28972. // Collects render targets from external components.
  28973. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28974. var step = _a[_i];
  28975. step.action(this._renderTargets);
  28976. }
  28977. if (this.renderTargetsEnabled) {
  28978. this._intermediateRendering = true;
  28979. if (this._renderTargets.length > 0) {
  28980. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28981. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28982. var renderTarget = this._renderTargets.data[renderIndex];
  28983. if (renderTarget._shouldRender()) {
  28984. this._renderId++;
  28985. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28986. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28987. }
  28988. }
  28989. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28990. this._renderId++;
  28991. }
  28992. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28993. var step = _c[_b];
  28994. step.action(this.activeCamera);
  28995. }
  28996. this._intermediateRendering = false;
  28997. if (this.activeCamera.customDefaultRenderTarget) {
  28998. var internalTexture = this.activeCamera.customDefaultRenderTarget.getInternalTexture();
  28999. if (internalTexture) {
  29000. engine.bindFramebuffer(internalTexture);
  29001. }
  29002. else {
  29003. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  29004. }
  29005. }
  29006. else {
  29007. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  29008. }
  29009. }
  29010. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29011. // Prepare Frame
  29012. if (this.postProcessManager) {
  29013. this.postProcessManager._prepareFrame();
  29014. }
  29015. // Before Camera Draw
  29016. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  29017. var step = _e[_d];
  29018. step.action(this.activeCamera);
  29019. }
  29020. // Render
  29021. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  29022. this._renderingManager.render(null, null, true, true);
  29023. this.onAfterDrawPhaseObservable.notifyObservers(this);
  29024. // After Camera Draw
  29025. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  29026. var step = _g[_f];
  29027. step.action(this.activeCamera);
  29028. }
  29029. // Finalize frame
  29030. if (this.postProcessManager) {
  29031. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29032. }
  29033. // Reset some special arrays
  29034. this._renderTargets.reset();
  29035. this._alternateRendering = false;
  29036. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29037. };
  29038. Scene.prototype._processSubCameras = function (camera) {
  29039. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29040. this._renderForCamera(camera);
  29041. return;
  29042. }
  29043. // rig cameras
  29044. for (var index = 0; index < camera._rigCameras.length; index++) {
  29045. this._renderForCamera(camera._rigCameras[index], camera);
  29046. }
  29047. this.activeCamera = camera;
  29048. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29049. };
  29050. Scene.prototype._checkIntersections = function () {
  29051. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29052. var sourceMesh = this._meshesForIntersections.data[index];
  29053. if (!sourceMesh.actionManager) {
  29054. continue;
  29055. }
  29056. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29057. var action = sourceMesh.actionManager.actions[actionIndex];
  29058. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29059. var parameters = action.getTriggerParameter();
  29060. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29061. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29062. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29063. if (areIntersecting && currentIntersectionInProgress === -1) {
  29064. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29065. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29066. sourceMesh._intersectionsInProgress.push(otherMesh);
  29067. }
  29068. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29069. sourceMesh._intersectionsInProgress.push(otherMesh);
  29070. }
  29071. }
  29072. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29073. //They intersected, and now they don't.
  29074. //is this trigger an exit trigger? execute an event.
  29075. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29076. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29077. }
  29078. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29079. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29080. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29081. return otherMesh === parameterMesh;
  29082. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29083. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29084. }
  29085. }
  29086. }
  29087. }
  29088. }
  29089. };
  29090. /** @hidden */
  29091. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29092. // Do nothing. Code will be replaced if physics engine component is referenced
  29093. };
  29094. /**
  29095. * Render the scene
  29096. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29097. */
  29098. Scene.prototype.render = function (updateCameras) {
  29099. if (updateCameras === void 0) { updateCameras = true; }
  29100. if (this.isDisposed) {
  29101. return;
  29102. }
  29103. this._frameId++;
  29104. // Register components that have been associated lately to the scene.
  29105. this._registerTransientComponents();
  29106. this._activeParticles.fetchNewFrame();
  29107. this._totalVertices.fetchNewFrame();
  29108. this._activeIndices.fetchNewFrame();
  29109. this._activeBones.fetchNewFrame();
  29110. this._meshesForIntersections.reset();
  29111. this.resetCachedMaterial();
  29112. this.onBeforeAnimationsObservable.notifyObservers(this);
  29113. // Actions
  29114. if (this.actionManager) {
  29115. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29116. }
  29117. if (this._engine.isDeterministicLockStep()) {
  29118. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29119. var defaultFPS = (60.0 / 1000.0);
  29120. var defaultFrameTime = this.getDeterministicFrameTime();
  29121. var stepsTaken = 0;
  29122. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29123. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29124. internalSteps = Math.min(internalSteps, maxSubSteps);
  29125. do {
  29126. this.onBeforeStepObservable.notifyObservers(this);
  29127. // Animations
  29128. this._animationRatio = defaultFrameTime * defaultFPS;
  29129. this._animate();
  29130. this.onAfterAnimationsObservable.notifyObservers(this);
  29131. // Physics
  29132. this._advancePhysicsEngineStep(defaultFrameTime);
  29133. this.onAfterStepObservable.notifyObservers(this);
  29134. this._currentStepId++;
  29135. stepsTaken++;
  29136. deltaTime -= defaultFrameTime;
  29137. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29138. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29139. }
  29140. else {
  29141. // Animations
  29142. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29143. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29144. this._animate();
  29145. this.onAfterAnimationsObservable.notifyObservers(this);
  29146. // Physics
  29147. this._advancePhysicsEngineStep(deltaTime);
  29148. }
  29149. // Before camera update steps
  29150. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29151. var step = _a[_i];
  29152. step.action();
  29153. }
  29154. // Update Cameras
  29155. if (updateCameras) {
  29156. if (this.activeCameras.length > 0) {
  29157. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29158. var camera = this.activeCameras[cameraIndex];
  29159. camera.update();
  29160. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29161. // rig cameras
  29162. for (var index = 0; index < camera._rigCameras.length; index++) {
  29163. camera._rigCameras[index].update();
  29164. }
  29165. }
  29166. }
  29167. }
  29168. else if (this.activeCamera) {
  29169. this.activeCamera.update();
  29170. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29171. // rig cameras
  29172. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29173. this.activeCamera._rigCameras[index].update();
  29174. }
  29175. }
  29176. }
  29177. }
  29178. // Before render
  29179. this.onBeforeRenderObservable.notifyObservers(this);
  29180. // Customs render targets
  29181. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29182. var engine = this.getEngine();
  29183. var currentActiveCamera = this.activeCamera;
  29184. if (this.renderTargetsEnabled) {
  29185. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29186. this._intermediateRendering = true;
  29187. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29188. var renderTarget = this.customRenderTargets[customIndex];
  29189. if (renderTarget._shouldRender()) {
  29190. this._renderId++;
  29191. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29192. if (!this.activeCamera) {
  29193. throw new Error("Active camera not set");
  29194. }
  29195. // Viewport
  29196. engine.setViewport(this.activeCamera.viewport);
  29197. // Camera
  29198. this.updateTransformMatrix();
  29199. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29200. }
  29201. }
  29202. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29203. this._intermediateRendering = false;
  29204. this._renderId++;
  29205. }
  29206. // Restore back buffer
  29207. if (this.customRenderTargets.length > 0) {
  29208. engine.restoreDefaultFramebuffer();
  29209. }
  29210. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29211. this.activeCamera = currentActiveCamera;
  29212. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29213. var step = _c[_b];
  29214. step.action();
  29215. }
  29216. // Clear
  29217. if (this.autoClearDepthAndStencil || this.autoClear) {
  29218. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29219. }
  29220. // Collects render targets from external components.
  29221. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29222. var step = _e[_d];
  29223. step.action(this._renderTargets);
  29224. }
  29225. // Multi-cameras?
  29226. if (this.activeCameras.length > 0) {
  29227. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29228. if (cameraIndex > 0) {
  29229. this._engine.clear(null, false, true, true);
  29230. }
  29231. this._processSubCameras(this.activeCameras[cameraIndex]);
  29232. }
  29233. }
  29234. else {
  29235. if (!this.activeCamera) {
  29236. throw new Error("No camera defined");
  29237. }
  29238. this._processSubCameras(this.activeCamera);
  29239. }
  29240. // Intersection checks
  29241. this._checkIntersections();
  29242. // Executes the after render stage actions.
  29243. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29244. var step = _g[_f];
  29245. step.action();
  29246. }
  29247. // After render
  29248. if (this.afterRender) {
  29249. this.afterRender();
  29250. }
  29251. this.onAfterRenderObservable.notifyObservers(this);
  29252. // Cleaning
  29253. if (this._toBeDisposed.length) {
  29254. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29255. var data = this._toBeDisposed[index];
  29256. if (data) {
  29257. data.dispose();
  29258. }
  29259. }
  29260. this._toBeDisposed = [];
  29261. }
  29262. if (this.dumpNextRenderTargets) {
  29263. this.dumpNextRenderTargets = false;
  29264. }
  29265. this._activeBones.addCount(0, true);
  29266. this._activeIndices.addCount(0, true);
  29267. this._activeParticles.addCount(0, true);
  29268. };
  29269. /**
  29270. * Freeze all materials
  29271. * A frozen material will not be updatable but should be faster to render
  29272. */
  29273. Scene.prototype.freezeMaterials = function () {
  29274. for (var i = 0; i < this.materials.length; i++) {
  29275. this.materials[i].freeze();
  29276. }
  29277. };
  29278. /**
  29279. * Unfreeze all materials
  29280. * A frozen material will not be updatable but should be faster to render
  29281. */
  29282. Scene.prototype.unfreezeMaterials = function () {
  29283. for (var i = 0; i < this.materials.length; i++) {
  29284. this.materials[i].unfreeze();
  29285. }
  29286. };
  29287. /**
  29288. * Releases all held ressources
  29289. */
  29290. Scene.prototype.dispose = function () {
  29291. this.beforeRender = null;
  29292. this.afterRender = null;
  29293. this.skeletons = [];
  29294. this.morphTargetManagers = [];
  29295. this._transientComponents = [];
  29296. this._isReadyForMeshStage.clear();
  29297. this._beforeEvaluateActiveMeshStage.clear();
  29298. this._evaluateSubMeshStage.clear();
  29299. this._activeMeshStage.clear();
  29300. this._cameraDrawRenderTargetStage.clear();
  29301. this._beforeCameraDrawStage.clear();
  29302. this._beforeRenderingGroupDrawStage.clear();
  29303. this._beforeRenderingMeshStage.clear();
  29304. this._afterRenderingMeshStage.clear();
  29305. this._afterRenderingGroupDrawStage.clear();
  29306. this._afterCameraDrawStage.clear();
  29307. this._afterRenderStage.clear();
  29308. this._beforeCameraUpdateStage.clear();
  29309. this._beforeClearStage.clear();
  29310. this._gatherRenderTargetsStage.clear();
  29311. this._gatherActiveCameraRenderTargetsStage.clear();
  29312. this._pointerMoveStage.clear();
  29313. this._pointerDownStage.clear();
  29314. this._pointerUpStage.clear();
  29315. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29316. var component = _a[_i];
  29317. component.dispose();
  29318. }
  29319. this.importedMeshesFiles = new Array();
  29320. this.stopAllAnimations();
  29321. this.resetCachedMaterial();
  29322. // Smart arrays
  29323. if (this.activeCamera) {
  29324. this.activeCamera._activeMeshes.dispose();
  29325. this.activeCamera = null;
  29326. }
  29327. this._activeMeshes.dispose();
  29328. this._renderingManager.dispose();
  29329. this._processedMaterials.dispose();
  29330. this._activeParticleSystems.dispose();
  29331. this._activeSkeletons.dispose();
  29332. this._softwareSkinnedMeshes.dispose();
  29333. this._renderTargets.dispose();
  29334. this._registeredForLateAnimationBindings.dispose();
  29335. this._meshesForIntersections.dispose();
  29336. this._toBeDisposed = [];
  29337. // Abort active requests
  29338. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29339. var request = _c[_b];
  29340. request.abort();
  29341. }
  29342. // Events
  29343. this.onDisposeObservable.notifyObservers(this);
  29344. this.onDisposeObservable.clear();
  29345. this.onBeforeRenderObservable.clear();
  29346. this.onAfterRenderObservable.clear();
  29347. this.onBeforeRenderTargetsRenderObservable.clear();
  29348. this.onAfterRenderTargetsRenderObservable.clear();
  29349. this.onAfterStepObservable.clear();
  29350. this.onBeforeStepObservable.clear();
  29351. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29352. this.onAfterActiveMeshesEvaluationObservable.clear();
  29353. this.onBeforeParticlesRenderingObservable.clear();
  29354. this.onAfterParticlesRenderingObservable.clear();
  29355. this.onBeforeDrawPhaseObservable.clear();
  29356. this.onAfterDrawPhaseObservable.clear();
  29357. this.onBeforeAnimationsObservable.clear();
  29358. this.onAfterAnimationsObservable.clear();
  29359. this.onDataLoadedObservable.clear();
  29360. this.onBeforeRenderingGroupObservable.clear();
  29361. this.onAfterRenderingGroupObservable.clear();
  29362. this.onMeshImportedObservable.clear();
  29363. this.onBeforeCameraRenderObservable.clear();
  29364. this.onAfterCameraRenderObservable.clear();
  29365. this.onReadyObservable.clear();
  29366. this.onNewCameraAddedObservable.clear();
  29367. this.onCameraRemovedObservable.clear();
  29368. this.onNewLightAddedObservable.clear();
  29369. this.onLightRemovedObservable.clear();
  29370. this.onNewGeometryAddedObservable.clear();
  29371. this.onGeometryRemovedObservable.clear();
  29372. this.onNewTransformNodeAddedObservable.clear();
  29373. this.onTransformNodeRemovedObservable.clear();
  29374. this.onNewMeshAddedObservable.clear();
  29375. this.onMeshRemovedObservable.clear();
  29376. this.onNewMaterialAddedObservable.clear();
  29377. this.onMaterialRemovedObservable.clear();
  29378. this.onNewTextureAddedObservable.clear();
  29379. this.onTextureRemovedObservable.clear();
  29380. this.onPrePointerObservable.clear();
  29381. this.onPointerObservable.clear();
  29382. this.onPreKeyboardObservable.clear();
  29383. this.onKeyboardObservable.clear();
  29384. this.detachControl();
  29385. // Detach cameras
  29386. var canvas = this._engine.getRenderingCanvas();
  29387. if (canvas) {
  29388. var index;
  29389. for (index = 0; index < this.cameras.length; index++) {
  29390. this.cameras[index].detachControl(canvas);
  29391. }
  29392. }
  29393. // Release animation groups
  29394. while (this.animationGroups.length) {
  29395. this.animationGroups[0].dispose();
  29396. }
  29397. // Release lights
  29398. while (this.lights.length) {
  29399. this.lights[0].dispose();
  29400. }
  29401. // Release meshes
  29402. while (this.meshes.length) {
  29403. this.meshes[0].dispose(true);
  29404. }
  29405. while (this.transformNodes.length) {
  29406. this.removeTransformNode(this.transformNodes[0]);
  29407. }
  29408. // Release cameras
  29409. while (this.cameras.length) {
  29410. this.cameras[0].dispose();
  29411. }
  29412. // Release materials
  29413. if (this.defaultMaterial) {
  29414. this.defaultMaterial.dispose();
  29415. }
  29416. while (this.multiMaterials.length) {
  29417. this.multiMaterials[0].dispose();
  29418. }
  29419. while (this.materials.length) {
  29420. this.materials[0].dispose();
  29421. }
  29422. // Release particles
  29423. while (this.particleSystems.length) {
  29424. this.particleSystems[0].dispose();
  29425. }
  29426. // Release postProcesses
  29427. while (this.postProcesses.length) {
  29428. this.postProcesses[0].dispose();
  29429. }
  29430. // Release textures
  29431. while (this.textures.length) {
  29432. this.textures[0].dispose();
  29433. }
  29434. // Release UBO
  29435. this._sceneUbo.dispose();
  29436. if (this._alternateSceneUbo) {
  29437. this._alternateSceneUbo.dispose();
  29438. }
  29439. // Post-processes
  29440. this.postProcessManager.dispose();
  29441. // Remove from engine
  29442. index = this._engine.scenes.indexOf(this);
  29443. if (index > -1) {
  29444. this._engine.scenes.splice(index, 1);
  29445. }
  29446. this._engine.wipeCaches(true);
  29447. this._isDisposed = true;
  29448. };
  29449. Object.defineProperty(Scene.prototype, "isDisposed", {
  29450. /**
  29451. * Gets if the scene is already disposed
  29452. */
  29453. get: function () {
  29454. return this._isDisposed;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. /**
  29460. * Call this function to reduce memory footprint of the scene.
  29461. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29462. */
  29463. Scene.prototype.clearCachedVertexData = function () {
  29464. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29465. var mesh = this.meshes[meshIndex];
  29466. var geometry = mesh.geometry;
  29467. if (geometry) {
  29468. geometry._indices = [];
  29469. for (var vbName in geometry._vertexBuffers) {
  29470. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29471. continue;
  29472. }
  29473. geometry._vertexBuffers[vbName]._buffer._data = null;
  29474. }
  29475. }
  29476. }
  29477. };
  29478. /**
  29479. * This function will remove the local cached buffer data from texture.
  29480. * It will save memory but will prevent the texture from being rebuilt
  29481. */
  29482. Scene.prototype.cleanCachedTextureBuffer = function () {
  29483. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29484. var baseTexture = _a[_i];
  29485. var buffer = baseTexture._buffer;
  29486. if (buffer) {
  29487. baseTexture._buffer = null;
  29488. }
  29489. }
  29490. };
  29491. /**
  29492. * Get the world extend vectors with an optional filter
  29493. *
  29494. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29495. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29496. */
  29497. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29498. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29499. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29500. filterPredicate = filterPredicate || (function () { return true; });
  29501. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29502. mesh.computeWorldMatrix(true);
  29503. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29504. return;
  29505. }
  29506. var boundingInfo = mesh.getBoundingInfo();
  29507. var minBox = boundingInfo.boundingBox.minimumWorld;
  29508. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29509. BABYLON.Tools.CheckExtends(minBox, min, max);
  29510. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29511. });
  29512. return {
  29513. min: min,
  29514. max: max
  29515. };
  29516. };
  29517. // Picking
  29518. /**
  29519. * Creates a ray that can be used to pick in the scene
  29520. * @param x defines the x coordinate of the origin (on-screen)
  29521. * @param y defines the y coordinate of the origin (on-screen)
  29522. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29523. * @param camera defines the camera to use for the picking
  29524. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29525. * @returns a Ray
  29526. */
  29527. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29528. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29529. var result = BABYLON.Ray.Zero();
  29530. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29531. return result;
  29532. };
  29533. /**
  29534. * Creates a ray that can be used to pick in the scene
  29535. * @param x defines the x coordinate of the origin (on-screen)
  29536. * @param y defines the y coordinate of the origin (on-screen)
  29537. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29538. * @param result defines the ray where to store the picking ray
  29539. * @param camera defines the camera to use for the picking
  29540. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29541. * @returns the current scene
  29542. */
  29543. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29544. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29545. var engine = this._engine;
  29546. if (!camera) {
  29547. if (!this.activeCamera) {
  29548. throw new Error("Active camera not set");
  29549. }
  29550. camera = this.activeCamera;
  29551. }
  29552. var cameraViewport = camera.viewport;
  29553. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29554. // Moving coordinates to local viewport world
  29555. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29556. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29557. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29558. return this;
  29559. };
  29560. /**
  29561. * Creates a ray that can be used to pick in the scene
  29562. * @param x defines the x coordinate of the origin (on-screen)
  29563. * @param y defines the y coordinate of the origin (on-screen)
  29564. * @param camera defines the camera to use for the picking
  29565. * @returns a Ray
  29566. */
  29567. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29568. var result = BABYLON.Ray.Zero();
  29569. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29570. return result;
  29571. };
  29572. /**
  29573. * Creates a ray that can be used to pick in the scene
  29574. * @param x defines the x coordinate of the origin (on-screen)
  29575. * @param y defines the y coordinate of the origin (on-screen)
  29576. * @param result defines the ray where to store the picking ray
  29577. * @param camera defines the camera to use for the picking
  29578. * @returns the current scene
  29579. */
  29580. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29581. if (!BABYLON.PickingInfo) {
  29582. return this;
  29583. }
  29584. var engine = this._engine;
  29585. if (!camera) {
  29586. if (!this.activeCamera) {
  29587. throw new Error("Active camera not set");
  29588. }
  29589. camera = this.activeCamera;
  29590. }
  29591. var cameraViewport = camera.viewport;
  29592. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29593. var identity = BABYLON.Matrix.Identity();
  29594. // Moving coordinates to local viewport world
  29595. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29596. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29597. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29598. return this;
  29599. };
  29600. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29601. if (!BABYLON.PickingInfo) {
  29602. return null;
  29603. }
  29604. var pickingInfo = null;
  29605. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29606. var mesh = this.meshes[meshIndex];
  29607. if (predicate) {
  29608. if (!predicate(mesh)) {
  29609. continue;
  29610. }
  29611. }
  29612. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29613. continue;
  29614. }
  29615. var world = mesh.getWorldMatrix();
  29616. var ray = rayFunction(world);
  29617. var result = mesh.intersects(ray, fastCheck);
  29618. if (!result || !result.hit) {
  29619. continue;
  29620. }
  29621. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29622. continue;
  29623. }
  29624. pickingInfo = result;
  29625. if (fastCheck) {
  29626. break;
  29627. }
  29628. }
  29629. return pickingInfo || new BABYLON.PickingInfo();
  29630. };
  29631. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29632. if (!BABYLON.PickingInfo) {
  29633. return null;
  29634. }
  29635. var pickingInfos = new Array();
  29636. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29637. var mesh = this.meshes[meshIndex];
  29638. if (predicate) {
  29639. if (!predicate(mesh)) {
  29640. continue;
  29641. }
  29642. }
  29643. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29644. continue;
  29645. }
  29646. var world = mesh.getWorldMatrix();
  29647. var ray = rayFunction(world);
  29648. var result = mesh.intersects(ray, false);
  29649. if (!result || !result.hit) {
  29650. continue;
  29651. }
  29652. pickingInfos.push(result);
  29653. }
  29654. return pickingInfos;
  29655. };
  29656. /** Launch a ray to try to pick a mesh in the scene
  29657. * @param x position on screen
  29658. * @param y position on screen
  29659. * @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
  29660. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29661. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29662. * @returns a PickingInfo
  29663. */
  29664. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29665. var _this = this;
  29666. if (!BABYLON.PickingInfo) {
  29667. return null;
  29668. }
  29669. var result = this._internalPick(function (world) {
  29670. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29671. return _this._tempPickingRay;
  29672. }, predicate, fastCheck);
  29673. if (result) {
  29674. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29675. }
  29676. return result;
  29677. };
  29678. /** Use the given ray to pick a mesh in the scene
  29679. * @param ray The ray to use to pick meshes
  29680. * @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
  29681. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29682. * @returns a PickingInfo
  29683. */
  29684. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29685. var _this = this;
  29686. var result = this._internalPick(function (world) {
  29687. if (!_this._pickWithRayInverseMatrix) {
  29688. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29689. }
  29690. world.invertToRef(_this._pickWithRayInverseMatrix);
  29691. if (!_this._cachedRayForTransform) {
  29692. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29693. }
  29694. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29695. return _this._cachedRayForTransform;
  29696. }, predicate, fastCheck);
  29697. if (result) {
  29698. result.ray = ray;
  29699. }
  29700. return result;
  29701. };
  29702. /**
  29703. * Launch a ray to try to pick a mesh in the scene
  29704. * @param x X position on screen
  29705. * @param y Y position on screen
  29706. * @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
  29707. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29708. * @returns an array of PickingInfo
  29709. */
  29710. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29711. var _this = this;
  29712. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29713. };
  29714. /**
  29715. * Launch a ray to try to pick a mesh in the scene
  29716. * @param ray Ray to use
  29717. * @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
  29718. * @returns an array of PickingInfo
  29719. */
  29720. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29721. var _this = this;
  29722. return this._internalMultiPick(function (world) {
  29723. if (!_this._pickWithRayInverseMatrix) {
  29724. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29725. }
  29726. world.invertToRef(_this._pickWithRayInverseMatrix);
  29727. if (!_this._cachedRayForTransform) {
  29728. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29729. }
  29730. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29731. return _this._cachedRayForTransform;
  29732. }, predicate);
  29733. };
  29734. /**
  29735. * Force the value of meshUnderPointer
  29736. * @param mesh defines the mesh to use
  29737. */
  29738. Scene.prototype.setPointerOverMesh = function (mesh) {
  29739. if (this._pointerOverMesh === mesh) {
  29740. return;
  29741. }
  29742. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29743. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29744. }
  29745. this._pointerOverMesh = mesh;
  29746. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29747. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29748. }
  29749. };
  29750. /**
  29751. * Gets the mesh under the pointer
  29752. * @returns a Mesh or null if no mesh is under the pointer
  29753. */
  29754. Scene.prototype.getPointerOverMesh = function () {
  29755. return this._pointerOverMesh;
  29756. };
  29757. // Misc.
  29758. /** @hidden */
  29759. Scene.prototype._rebuildGeometries = function () {
  29760. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29761. var geometry = _a[_i];
  29762. geometry._rebuild();
  29763. }
  29764. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29765. var mesh = _c[_b];
  29766. mesh._rebuild();
  29767. }
  29768. if (this.postProcessManager) {
  29769. this.postProcessManager._rebuild();
  29770. }
  29771. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29772. var component = _e[_d];
  29773. component.rebuild();
  29774. }
  29775. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29776. var system = _g[_f];
  29777. system.rebuild();
  29778. }
  29779. };
  29780. /** @hidden */
  29781. Scene.prototype._rebuildTextures = function () {
  29782. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29783. var texture = _a[_i];
  29784. texture._rebuild();
  29785. }
  29786. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29787. };
  29788. // Tags
  29789. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29790. if (tagsQuery === undefined) {
  29791. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29792. return list;
  29793. }
  29794. var listByTags = [];
  29795. forEach = forEach || (function (item) { return; });
  29796. for (var i in list) {
  29797. var item = list[i];
  29798. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29799. listByTags.push(item);
  29800. forEach(item);
  29801. }
  29802. }
  29803. return listByTags;
  29804. };
  29805. /**
  29806. * Get a list of meshes by tags
  29807. * @param tagsQuery defines the tags query to use
  29808. * @param forEach defines a predicate used to filter results
  29809. * @returns an array of Mesh
  29810. */
  29811. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29812. return this._getByTags(this.meshes, tagsQuery, forEach);
  29813. };
  29814. /**
  29815. * Get a list of cameras by tags
  29816. * @param tagsQuery defines the tags query to use
  29817. * @param forEach defines a predicate used to filter results
  29818. * @returns an array of Camera
  29819. */
  29820. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29821. return this._getByTags(this.cameras, tagsQuery, forEach);
  29822. };
  29823. /**
  29824. * Get a list of lights by tags
  29825. * @param tagsQuery defines the tags query to use
  29826. * @param forEach defines a predicate used to filter results
  29827. * @returns an array of Light
  29828. */
  29829. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29830. return this._getByTags(this.lights, tagsQuery, forEach);
  29831. };
  29832. /**
  29833. * Get a list of materials by tags
  29834. * @param tagsQuery defines the tags query to use
  29835. * @param forEach defines a predicate used to filter results
  29836. * @returns an array of Material
  29837. */
  29838. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29839. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29840. };
  29841. /**
  29842. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29843. * This allowed control for front to back rendering or reversly depending of the special needs.
  29844. *
  29845. * @param renderingGroupId The rendering group id corresponding to its index
  29846. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29847. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29848. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29849. */
  29850. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29851. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29852. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29853. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29854. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29855. };
  29856. /**
  29857. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29858. *
  29859. * @param renderingGroupId The rendering group id corresponding to its index
  29860. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29861. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29862. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29863. */
  29864. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29865. if (depth === void 0) { depth = true; }
  29866. if (stencil === void 0) { stencil = true; }
  29867. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29868. };
  29869. /**
  29870. * Gets the current auto clear configuration for one rendering group of the rendering
  29871. * manager.
  29872. * @param index the rendering group index to get the information for
  29873. * @returns The auto clear setup for the requested rendering group
  29874. */
  29875. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29876. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29877. };
  29878. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29879. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29880. get: function () {
  29881. return this._blockMaterialDirtyMechanism;
  29882. },
  29883. set: function (value) {
  29884. if (this._blockMaterialDirtyMechanism === value) {
  29885. return;
  29886. }
  29887. this._blockMaterialDirtyMechanism = value;
  29888. if (!value) { // Do a complete update
  29889. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29890. }
  29891. },
  29892. enumerable: true,
  29893. configurable: true
  29894. });
  29895. /**
  29896. * Will flag all materials as dirty to trigger new shader compilation
  29897. * @param flag defines the flag used to specify which material part must be marked as dirty
  29898. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29899. */
  29900. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29901. if (this._blockMaterialDirtyMechanism) {
  29902. return;
  29903. }
  29904. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29905. var material = _a[_i];
  29906. if (predicate && !predicate(material)) {
  29907. continue;
  29908. }
  29909. material.markAsDirty(flag);
  29910. }
  29911. };
  29912. /** @hidden */
  29913. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  29914. var _this = this;
  29915. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  29916. this._activeRequests.push(request);
  29917. request.onCompleteObservable.add(function (request) {
  29918. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29919. });
  29920. return request;
  29921. };
  29922. /** @hidden */
  29923. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  29924. var _this = this;
  29925. return new Promise(function (resolve, reject) {
  29926. _this._loadFile(url, function (data) {
  29927. resolve(data);
  29928. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  29929. reject(exception);
  29930. });
  29931. });
  29932. };
  29933. // Statics
  29934. Scene._uniqueIdCounter = 0;
  29935. /** The fog is deactivated */
  29936. Scene.FOGMODE_NONE = 0;
  29937. /** The fog density is following an exponential function */
  29938. Scene.FOGMODE_EXP = 1;
  29939. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29940. Scene.FOGMODE_EXP2 = 2;
  29941. /** The fog density is following a linear function. */
  29942. Scene.FOGMODE_LINEAR = 3;
  29943. /**
  29944. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29945. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29946. */
  29947. Scene.MinDeltaTime = 1.0;
  29948. /**
  29949. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29950. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29951. */
  29952. Scene.MaxDeltaTime = 1000.0;
  29953. /** The distance in pixel that you have to move to prevent some events */
  29954. Scene.DragMovementThreshold = 10; // in pixels
  29955. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29956. Scene.LongPressDelay = 500; // in milliseconds
  29957. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29958. Scene.DoubleClickDelay = 300; // in milliseconds
  29959. /** If you need to check double click without raising a single click at first click, enable this flag */
  29960. Scene.ExclusiveDoubleClickMode = false;
  29961. return Scene;
  29962. }(BABYLON.AbstractScene));
  29963. BABYLON.Scene = Scene;
  29964. })(BABYLON || (BABYLON = {}));
  29965. //# sourceMappingURL=babylon.scene.js.map
  29966. var BABYLON;
  29967. (function (BABYLON) {
  29968. /**
  29969. * Set of assets to keep when moving a scene into an asset container.
  29970. */
  29971. var KeepAssets = /** @class */ (function (_super) {
  29972. __extends(KeepAssets, _super);
  29973. function KeepAssets() {
  29974. return _super !== null && _super.apply(this, arguments) || this;
  29975. }
  29976. return KeepAssets;
  29977. }(BABYLON.AbstractScene));
  29978. BABYLON.KeepAssets = KeepAssets;
  29979. /**
  29980. * Container with a set of assets that can be added or removed from a scene.
  29981. */
  29982. var AssetContainer = /** @class */ (function (_super) {
  29983. __extends(AssetContainer, _super);
  29984. /**
  29985. * Instantiates an AssetContainer.
  29986. * @param scene The scene the AssetContainer belongs to.
  29987. */
  29988. function AssetContainer(scene) {
  29989. var _this = _super.call(this) || this;
  29990. _this.scene = scene;
  29991. return _this;
  29992. }
  29993. /**
  29994. * Adds all the assets from the container to the scene.
  29995. */
  29996. AssetContainer.prototype.addAllToScene = function () {
  29997. var _this = this;
  29998. this.cameras.forEach(function (o) {
  29999. _this.scene.addCamera(o);
  30000. });
  30001. this.lights.forEach(function (o) {
  30002. _this.scene.addLight(o);
  30003. });
  30004. this.meshes.forEach(function (o) {
  30005. _this.scene.addMesh(o);
  30006. });
  30007. this.skeletons.forEach(function (o) {
  30008. _this.scene.addSkeleton(o);
  30009. });
  30010. this.animations.forEach(function (o) {
  30011. _this.scene.addAnimation(o);
  30012. });
  30013. this.animationGroups.forEach(function (o) {
  30014. _this.scene.addAnimationGroup(o);
  30015. });
  30016. this.multiMaterials.forEach(function (o) {
  30017. _this.scene.addMultiMaterial(o);
  30018. });
  30019. this.materials.forEach(function (o) {
  30020. _this.scene.addMaterial(o);
  30021. });
  30022. this.morphTargetManagers.forEach(function (o) {
  30023. _this.scene.addMorphTargetManager(o);
  30024. });
  30025. this.geometries.forEach(function (o) {
  30026. _this.scene.addGeometry(o);
  30027. });
  30028. this.transformNodes.forEach(function (o) {
  30029. _this.scene.addTransformNode(o);
  30030. });
  30031. this.actionManagers.forEach(function (o) {
  30032. _this.scene.addActionManager(o);
  30033. });
  30034. this.textures.forEach(function (o) {
  30035. _this.scene.addTexture(o);
  30036. });
  30037. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30038. var component = _a[_i];
  30039. component.addFromContainer(this.scene);
  30040. }
  30041. };
  30042. /**
  30043. * Removes all the assets in the container from the scene
  30044. */
  30045. AssetContainer.prototype.removeAllFromScene = function () {
  30046. var _this = this;
  30047. this.cameras.forEach(function (o) {
  30048. _this.scene.removeCamera(o);
  30049. });
  30050. this.lights.forEach(function (o) {
  30051. _this.scene.removeLight(o);
  30052. });
  30053. this.meshes.forEach(function (o) {
  30054. _this.scene.removeMesh(o);
  30055. });
  30056. this.skeletons.forEach(function (o) {
  30057. _this.scene.removeSkeleton(o);
  30058. });
  30059. this.animations.forEach(function (o) {
  30060. _this.scene.removeAnimation(o);
  30061. });
  30062. this.animationGroups.forEach(function (o) {
  30063. _this.scene.removeAnimationGroup(o);
  30064. });
  30065. this.multiMaterials.forEach(function (o) {
  30066. _this.scene.removeMultiMaterial(o);
  30067. });
  30068. this.materials.forEach(function (o) {
  30069. _this.scene.removeMaterial(o);
  30070. });
  30071. this.morphTargetManagers.forEach(function (o) {
  30072. _this.scene.removeMorphTargetManager(o);
  30073. });
  30074. this.geometries.forEach(function (o) {
  30075. _this.scene.removeGeometry(o);
  30076. });
  30077. this.transformNodes.forEach(function (o) {
  30078. _this.scene.removeTransformNode(o);
  30079. });
  30080. this.actionManagers.forEach(function (o) {
  30081. _this.scene.removeActionManager(o);
  30082. });
  30083. this.textures.forEach(function (o) {
  30084. _this.scene.removeTexture(o);
  30085. });
  30086. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30087. var component = _a[_i];
  30088. component.removeFromContainer(this.scene);
  30089. }
  30090. };
  30091. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30092. if (!sourceAssets) {
  30093. return;
  30094. }
  30095. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30096. var asset = sourceAssets_1[_i];
  30097. var move = true;
  30098. if (keepAssets) {
  30099. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30100. var keepAsset = keepAssets_1[_a];
  30101. if (asset === keepAsset) {
  30102. move = false;
  30103. break;
  30104. }
  30105. }
  30106. }
  30107. if (move) {
  30108. targetAssets.push(asset);
  30109. }
  30110. }
  30111. };
  30112. /**
  30113. * Removes all the assets contained in the scene and adds them to the container.
  30114. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30115. */
  30116. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30117. if (keepAssets === undefined) {
  30118. keepAssets = new KeepAssets();
  30119. }
  30120. for (var key in this) {
  30121. if (this.hasOwnProperty(key)) {
  30122. this[key] = this[key] || [];
  30123. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30124. }
  30125. }
  30126. this.removeAllFromScene();
  30127. };
  30128. /**
  30129. * 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.
  30130. * @returns the root mesh
  30131. */
  30132. AssetContainer.prototype.createRootMesh = function () {
  30133. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30134. this.meshes.forEach(function (m) {
  30135. if (!m.parent) {
  30136. rootMesh.addChild(m);
  30137. }
  30138. });
  30139. this.meshes.unshift(rootMesh);
  30140. return rootMesh;
  30141. };
  30142. return AssetContainer;
  30143. }(BABYLON.AbstractScene));
  30144. BABYLON.AssetContainer = AssetContainer;
  30145. })(BABYLON || (BABYLON = {}));
  30146. //# sourceMappingURL=babylon.assetContainer.js.map
  30147. var BABYLON;
  30148. (function (BABYLON) {
  30149. /**
  30150. * Class used to store data that will be store in GPU memory
  30151. */
  30152. var Buffer = /** @class */ (function () {
  30153. /**
  30154. * Constructor
  30155. * @param engine the engine
  30156. * @param data the data to use for this buffer
  30157. * @param updatable whether the data is updatable
  30158. * @param stride the stride (optional)
  30159. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30160. * @param instanced whether the buffer is instanced (optional)
  30161. * @param useBytes set to true if the stride in in bytes (optional)
  30162. */
  30163. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30164. if (stride === void 0) { stride = 0; }
  30165. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30166. if (instanced === void 0) { instanced = false; }
  30167. if (useBytes === void 0) { useBytes = false; }
  30168. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30169. this._engine = engine.getScene().getEngine();
  30170. }
  30171. else {
  30172. this._engine = engine;
  30173. }
  30174. this._updatable = updatable;
  30175. this._instanced = instanced;
  30176. this._data = data;
  30177. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30178. if (!postponeInternalCreation) { // by default
  30179. this.create();
  30180. }
  30181. }
  30182. /**
  30183. * Create a new VertexBuffer based on the current buffer
  30184. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30185. * @param offset defines offset in the buffer (0 by default)
  30186. * @param size defines the size in floats of attributes (position is 3 for instance)
  30187. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30188. * @param instanced defines if the vertex buffer contains indexed data
  30189. * @param useBytes defines if the offset and stride are in bytes
  30190. * @returns the new vertex buffer
  30191. */
  30192. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30193. if (useBytes === void 0) { useBytes = false; }
  30194. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30195. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30196. // a lot of these parameters are ignored as they are overriden by the buffer
  30197. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30198. };
  30199. // Properties
  30200. /**
  30201. * Gets a boolean indicating if the Buffer is updatable?
  30202. * @returns true if the buffer is updatable
  30203. */
  30204. Buffer.prototype.isUpdatable = function () {
  30205. return this._updatable;
  30206. };
  30207. /**
  30208. * Gets current buffer's data
  30209. * @returns a DataArray or null
  30210. */
  30211. Buffer.prototype.getData = function () {
  30212. return this._data;
  30213. };
  30214. /**
  30215. * Gets underlying native buffer
  30216. * @returns underlying native buffer
  30217. */
  30218. Buffer.prototype.getBuffer = function () {
  30219. return this._buffer;
  30220. };
  30221. /**
  30222. * Gets the stride in float32 units (i.e. byte stride / 4).
  30223. * May not be an integer if the byte stride is not divisible by 4.
  30224. * DEPRECATED. Use byteStride instead.
  30225. * @returns the stride in float32 units
  30226. */
  30227. Buffer.prototype.getStrideSize = function () {
  30228. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30229. };
  30230. // Methods
  30231. /**
  30232. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30233. * @param data defines the data to store
  30234. */
  30235. Buffer.prototype.create = function (data) {
  30236. if (data === void 0) { data = null; }
  30237. if (!data && this._buffer) {
  30238. return; // nothing to do
  30239. }
  30240. data = data || this._data;
  30241. if (!data) {
  30242. return;
  30243. }
  30244. if (!this._buffer) { // create buffer
  30245. if (this._updatable) {
  30246. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30247. this._data = data;
  30248. }
  30249. else {
  30250. this._buffer = this._engine.createVertexBuffer(data);
  30251. }
  30252. }
  30253. else if (this._updatable) { // update buffer
  30254. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30255. this._data = data;
  30256. }
  30257. };
  30258. /** @hidden */
  30259. Buffer.prototype._rebuild = function () {
  30260. this._buffer = null;
  30261. this.create(this._data);
  30262. };
  30263. /**
  30264. * Update current buffer data
  30265. * @param data defines the data to store
  30266. */
  30267. Buffer.prototype.update = function (data) {
  30268. this.create(data);
  30269. };
  30270. /**
  30271. * Updates the data directly.
  30272. * @param data the new data
  30273. * @param offset the new offset
  30274. * @param vertexCount the vertex count (optional)
  30275. * @param useBytes set to true if the offset is in bytes
  30276. */
  30277. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30278. if (useBytes === void 0) { useBytes = false; }
  30279. if (!this._buffer) {
  30280. return;
  30281. }
  30282. if (this._updatable) { // update buffer
  30283. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30284. this._data = null;
  30285. }
  30286. };
  30287. /**
  30288. * Release all resources
  30289. */
  30290. Buffer.prototype.dispose = function () {
  30291. if (!this._buffer) {
  30292. return;
  30293. }
  30294. if (this._engine._releaseBuffer(this._buffer)) {
  30295. this._buffer = null;
  30296. }
  30297. };
  30298. return Buffer;
  30299. }());
  30300. BABYLON.Buffer = Buffer;
  30301. })(BABYLON || (BABYLON = {}));
  30302. //# sourceMappingURL=babylon.buffer.js.map
  30303. var BABYLON;
  30304. (function (BABYLON) {
  30305. /**
  30306. * Specialized buffer used to store vertex data
  30307. */
  30308. var VertexBuffer = /** @class */ (function () {
  30309. /**
  30310. * Constructor
  30311. * @param engine the engine
  30312. * @param data the data to use for this vertex buffer
  30313. * @param kind the vertex buffer kind
  30314. * @param updatable whether the data is updatable
  30315. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30316. * @param stride the stride (optional)
  30317. * @param instanced whether the buffer is instanced (optional)
  30318. * @param offset the offset of the data (optional)
  30319. * @param size the number of components (optional)
  30320. * @param type the type of the component (optional)
  30321. * @param normalized whether the data contains normalized data (optional)
  30322. * @param useBytes set to true if stride and offset are in bytes (optional)
  30323. */
  30324. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30325. if (normalized === void 0) { normalized = false; }
  30326. if (useBytes === void 0) { useBytes = false; }
  30327. if (data instanceof BABYLON.Buffer) {
  30328. this._buffer = data;
  30329. this._ownsBuffer = false;
  30330. }
  30331. else {
  30332. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30333. this._ownsBuffer = true;
  30334. }
  30335. this._kind = kind;
  30336. if (type == undefined) {
  30337. var data_1 = this.getData();
  30338. this.type = VertexBuffer.FLOAT;
  30339. if (data_1 instanceof Int8Array) {
  30340. this.type = VertexBuffer.BYTE;
  30341. }
  30342. else if (data_1 instanceof Uint8Array) {
  30343. this.type = VertexBuffer.UNSIGNED_BYTE;
  30344. }
  30345. else if (data_1 instanceof Int16Array) {
  30346. this.type = VertexBuffer.SHORT;
  30347. }
  30348. else if (data_1 instanceof Uint16Array) {
  30349. this.type = VertexBuffer.UNSIGNED_SHORT;
  30350. }
  30351. else if (data_1 instanceof Int32Array) {
  30352. this.type = VertexBuffer.INT;
  30353. }
  30354. else if (data_1 instanceof Uint32Array) {
  30355. this.type = VertexBuffer.UNSIGNED_INT;
  30356. }
  30357. }
  30358. else {
  30359. this.type = type;
  30360. }
  30361. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30362. if (useBytes) {
  30363. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30364. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30365. this.byteOffset = offset || 0;
  30366. }
  30367. else {
  30368. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30369. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30370. this.byteOffset = (offset || 0) * typeByteLength;
  30371. }
  30372. this.normalized = normalized;
  30373. this._instanced = instanced !== undefined ? instanced : false;
  30374. this._instanceDivisor = instanced ? 1 : 0;
  30375. }
  30376. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30377. /**
  30378. * Gets or sets the instance divisor when in instanced mode
  30379. */
  30380. get: function () {
  30381. return this._instanceDivisor;
  30382. },
  30383. set: function (value) {
  30384. this._instanceDivisor = value;
  30385. if (value == 0) {
  30386. this._instanced = false;
  30387. }
  30388. else {
  30389. this._instanced = true;
  30390. }
  30391. },
  30392. enumerable: true,
  30393. configurable: true
  30394. });
  30395. /** @hidden */
  30396. VertexBuffer.prototype._rebuild = function () {
  30397. if (!this._buffer) {
  30398. return;
  30399. }
  30400. this._buffer._rebuild();
  30401. };
  30402. /**
  30403. * Returns the kind of the VertexBuffer (string)
  30404. * @returns a string
  30405. */
  30406. VertexBuffer.prototype.getKind = function () {
  30407. return this._kind;
  30408. };
  30409. // Properties
  30410. /**
  30411. * Gets a boolean indicating if the VertexBuffer is updatable?
  30412. * @returns true if the buffer is updatable
  30413. */
  30414. VertexBuffer.prototype.isUpdatable = function () {
  30415. return this._buffer.isUpdatable();
  30416. };
  30417. /**
  30418. * Gets current buffer's data
  30419. * @returns a DataArray or null
  30420. */
  30421. VertexBuffer.prototype.getData = function () {
  30422. return this._buffer.getData();
  30423. };
  30424. /**
  30425. * Gets underlying native buffer
  30426. * @returns underlying native buffer
  30427. */
  30428. VertexBuffer.prototype.getBuffer = function () {
  30429. return this._buffer.getBuffer();
  30430. };
  30431. /**
  30432. * Gets the stride in float32 units (i.e. byte stride / 4).
  30433. * May not be an integer if the byte stride is not divisible by 4.
  30434. * DEPRECATED. Use byteStride instead.
  30435. * @returns the stride in float32 units
  30436. */
  30437. VertexBuffer.prototype.getStrideSize = function () {
  30438. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30439. };
  30440. /**
  30441. * Returns the offset as a multiple of the type byte length.
  30442. * DEPRECATED. Use byteOffset instead.
  30443. * @returns the offset in bytes
  30444. */
  30445. VertexBuffer.prototype.getOffset = function () {
  30446. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30447. };
  30448. /**
  30449. * Returns the number of components per vertex attribute (integer)
  30450. * @returns the size in float
  30451. */
  30452. VertexBuffer.prototype.getSize = function () {
  30453. return this._size;
  30454. };
  30455. /**
  30456. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30457. * @returns true if this buffer is instanced
  30458. */
  30459. VertexBuffer.prototype.getIsInstanced = function () {
  30460. return this._instanced;
  30461. };
  30462. /**
  30463. * Returns the instancing divisor, zero for non-instanced (integer).
  30464. * @returns a number
  30465. */
  30466. VertexBuffer.prototype.getInstanceDivisor = function () {
  30467. return this._instanceDivisor;
  30468. };
  30469. // Methods
  30470. /**
  30471. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30472. * @param data defines the data to store
  30473. */
  30474. VertexBuffer.prototype.create = function (data) {
  30475. this._buffer.create(data);
  30476. };
  30477. /**
  30478. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30479. * This function will create a new buffer if the current one is not updatable
  30480. * @param data defines the data to store
  30481. */
  30482. VertexBuffer.prototype.update = function (data) {
  30483. this._buffer.update(data);
  30484. };
  30485. /**
  30486. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30487. * Returns the directly updated WebGLBuffer.
  30488. * @param data the new data
  30489. * @param offset the new offset
  30490. * @param useBytes set to true if the offset is in bytes
  30491. */
  30492. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30493. if (useBytes === void 0) { useBytes = false; }
  30494. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30495. };
  30496. /**
  30497. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30498. */
  30499. VertexBuffer.prototype.dispose = function () {
  30500. if (this._ownsBuffer) {
  30501. this._buffer.dispose();
  30502. }
  30503. };
  30504. /**
  30505. * Enumerates each value of this vertex buffer as numbers.
  30506. * @param count the number of values to enumerate
  30507. * @param callback the callback function called for each value
  30508. */
  30509. VertexBuffer.prototype.forEach = function (count, callback) {
  30510. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30511. };
  30512. /**
  30513. * Deduces the stride given a kind.
  30514. * @param kind The kind string to deduce
  30515. * @returns The deduced stride
  30516. */
  30517. VertexBuffer.DeduceStride = function (kind) {
  30518. switch (kind) {
  30519. case VertexBuffer.UVKind:
  30520. case VertexBuffer.UV2Kind:
  30521. case VertexBuffer.UV3Kind:
  30522. case VertexBuffer.UV4Kind:
  30523. case VertexBuffer.UV5Kind:
  30524. case VertexBuffer.UV6Kind:
  30525. return 2;
  30526. case VertexBuffer.NormalKind:
  30527. case VertexBuffer.PositionKind:
  30528. return 3;
  30529. case VertexBuffer.ColorKind:
  30530. case VertexBuffer.MatricesIndicesKind:
  30531. case VertexBuffer.MatricesIndicesExtraKind:
  30532. case VertexBuffer.MatricesWeightsKind:
  30533. case VertexBuffer.MatricesWeightsExtraKind:
  30534. case VertexBuffer.TangentKind:
  30535. return 4;
  30536. default:
  30537. throw new Error("Invalid kind '" + kind + "'");
  30538. }
  30539. };
  30540. /**
  30541. * Gets the byte length of the given type.
  30542. * @param type the type
  30543. * @returns the number of bytes
  30544. */
  30545. VertexBuffer.GetTypeByteLength = function (type) {
  30546. switch (type) {
  30547. case VertexBuffer.BYTE:
  30548. case VertexBuffer.UNSIGNED_BYTE:
  30549. return 1;
  30550. case VertexBuffer.SHORT:
  30551. case VertexBuffer.UNSIGNED_SHORT:
  30552. return 2;
  30553. case VertexBuffer.INT:
  30554. case VertexBuffer.FLOAT:
  30555. return 4;
  30556. default:
  30557. throw new Error("Invalid type '" + type + "'");
  30558. }
  30559. };
  30560. /**
  30561. * Enumerates each value of the given parameters as numbers.
  30562. * @param data the data to enumerate
  30563. * @param byteOffset the byte offset of the data
  30564. * @param byteStride the byte stride of the data
  30565. * @param componentCount the number of components per element
  30566. * @param componentType the type of the component
  30567. * @param count the total number of components
  30568. * @param normalized whether the data is normalized
  30569. * @param callback the callback function called for each value
  30570. */
  30571. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30572. if (data instanceof Array) {
  30573. var offset = byteOffset / 4;
  30574. var stride = byteStride / 4;
  30575. for (var index = 0; index < count; index += componentCount) {
  30576. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30577. callback(data[offset + componentIndex], index + componentIndex);
  30578. }
  30579. offset += stride;
  30580. }
  30581. }
  30582. else {
  30583. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30584. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30585. for (var index = 0; index < count; index += componentCount) {
  30586. var componentByteOffset = byteOffset;
  30587. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30588. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30589. callback(value, index + componentIndex);
  30590. componentByteOffset += componentByteLength;
  30591. }
  30592. byteOffset += byteStride;
  30593. }
  30594. }
  30595. };
  30596. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30597. switch (type) {
  30598. case VertexBuffer.BYTE: {
  30599. var value = dataView.getInt8(byteOffset);
  30600. if (normalized) {
  30601. value = Math.max(value / 127, -1);
  30602. }
  30603. return value;
  30604. }
  30605. case VertexBuffer.UNSIGNED_BYTE: {
  30606. var value = dataView.getUint8(byteOffset);
  30607. if (normalized) {
  30608. value = value / 255;
  30609. }
  30610. return value;
  30611. }
  30612. case VertexBuffer.SHORT: {
  30613. var value = dataView.getInt16(byteOffset, true);
  30614. if (normalized) {
  30615. value = Math.max(value / 16383, -1);
  30616. }
  30617. return value;
  30618. }
  30619. case VertexBuffer.UNSIGNED_SHORT: {
  30620. var value = dataView.getUint16(byteOffset, true);
  30621. if (normalized) {
  30622. value = value / 65535;
  30623. }
  30624. return value;
  30625. }
  30626. case VertexBuffer.FLOAT: {
  30627. return dataView.getFloat32(byteOffset, true);
  30628. }
  30629. default: {
  30630. throw new Error("Invalid component type " + type);
  30631. }
  30632. }
  30633. };
  30634. /**
  30635. * The byte type.
  30636. */
  30637. VertexBuffer.BYTE = 5120;
  30638. /**
  30639. * The unsigned byte type.
  30640. */
  30641. VertexBuffer.UNSIGNED_BYTE = 5121;
  30642. /**
  30643. * The short type.
  30644. */
  30645. VertexBuffer.SHORT = 5122;
  30646. /**
  30647. * The unsigned short type.
  30648. */
  30649. VertexBuffer.UNSIGNED_SHORT = 5123;
  30650. /**
  30651. * The integer type.
  30652. */
  30653. VertexBuffer.INT = 5124;
  30654. /**
  30655. * The unsigned integer type.
  30656. */
  30657. VertexBuffer.UNSIGNED_INT = 5125;
  30658. /**
  30659. * The float type.
  30660. */
  30661. VertexBuffer.FLOAT = 5126;
  30662. // Enums
  30663. /**
  30664. * Positions
  30665. */
  30666. VertexBuffer.PositionKind = "position";
  30667. /**
  30668. * Normals
  30669. */
  30670. VertexBuffer.NormalKind = "normal";
  30671. /**
  30672. * Tangents
  30673. */
  30674. VertexBuffer.TangentKind = "tangent";
  30675. /**
  30676. * Texture coordinates
  30677. */
  30678. VertexBuffer.UVKind = "uv";
  30679. /**
  30680. * Texture coordinates 2
  30681. */
  30682. VertexBuffer.UV2Kind = "uv2";
  30683. /**
  30684. * Texture coordinates 3
  30685. */
  30686. VertexBuffer.UV3Kind = "uv3";
  30687. /**
  30688. * Texture coordinates 4
  30689. */
  30690. VertexBuffer.UV4Kind = "uv4";
  30691. /**
  30692. * Texture coordinates 5
  30693. */
  30694. VertexBuffer.UV5Kind = "uv5";
  30695. /**
  30696. * Texture coordinates 6
  30697. */
  30698. VertexBuffer.UV6Kind = "uv6";
  30699. /**
  30700. * Colors
  30701. */
  30702. VertexBuffer.ColorKind = "color";
  30703. /**
  30704. * Matrix indices (for bones)
  30705. */
  30706. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30707. /**
  30708. * Matrix weights (for bones)
  30709. */
  30710. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30711. /**
  30712. * Additional matrix indices (for bones)
  30713. */
  30714. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30715. /**
  30716. * Additional matrix weights (for bones)
  30717. */
  30718. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30719. return VertexBuffer;
  30720. }());
  30721. BABYLON.VertexBuffer = VertexBuffer;
  30722. })(BABYLON || (BABYLON = {}));
  30723. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30724. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30725. var BABYLON;
  30726. (function (BABYLON) {
  30727. /**
  30728. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30729. */
  30730. var DummyInternalTextureTracker = /** @class */ (function () {
  30731. function DummyInternalTextureTracker() {
  30732. /**
  30733. * Gets or set the previous tracker in the list
  30734. */
  30735. this.previous = null;
  30736. /**
  30737. * Gets or set the next tracker in the list
  30738. */
  30739. this.next = null;
  30740. }
  30741. return DummyInternalTextureTracker;
  30742. }());
  30743. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30744. })(BABYLON || (BABYLON = {}));
  30745. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30746. var BABYLON;
  30747. (function (BABYLON) {
  30748. /**
  30749. * Class used to store data associated with WebGL texture data for the engine
  30750. * This class should not be used directly
  30751. */
  30752. var InternalTexture = /** @class */ (function () {
  30753. /**
  30754. * Creates a new InternalTexture
  30755. * @param engine defines the engine to use
  30756. * @param dataSource defines the type of data that will be used
  30757. */
  30758. function InternalTexture(engine, dataSource) {
  30759. /**
  30760. * Observable called when the texture is loaded
  30761. */
  30762. this.onLoadedObservable = new BABYLON.Observable();
  30763. /**
  30764. * Gets or set the previous tracker in the list
  30765. */
  30766. this.previous = null;
  30767. /**
  30768. * Gets or set the next tracker in the list
  30769. */
  30770. this.next = null;
  30771. // Private
  30772. /** @hidden */
  30773. this._initialSlot = -1;
  30774. /** @hidden */
  30775. this._designatedSlot = -1;
  30776. /** @hidden */
  30777. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30778. /** @hidden */
  30779. this._comparisonFunction = 0;
  30780. /** @hidden */
  30781. this._sphericalPolynomial = null;
  30782. /** @hidden */
  30783. this._lodGenerationScale = 0;
  30784. /** @hidden */
  30785. this._lodGenerationOffset = 0;
  30786. /** @hidden */
  30787. this._isRGBD = false;
  30788. /** @hidden */
  30789. this._references = 1;
  30790. this._engine = engine;
  30791. this._dataSource = dataSource;
  30792. this._webGLTexture = engine._createTexture();
  30793. }
  30794. /**
  30795. * Gets the Engine the texture belongs to.
  30796. * @returns The babylon engine
  30797. */
  30798. InternalTexture.prototype.getEngine = function () {
  30799. return this._engine;
  30800. };
  30801. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30802. /**
  30803. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30804. */
  30805. get: function () {
  30806. return this._dataSource;
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. /**
  30812. * Increments the number of references (ie. the number of Texture that point to it)
  30813. */
  30814. InternalTexture.prototype.incrementReferences = function () {
  30815. this._references++;
  30816. };
  30817. /**
  30818. * Change the size of the texture (not the size of the content)
  30819. * @param width defines the new width
  30820. * @param height defines the new height
  30821. * @param depth defines the new depth (1 by default)
  30822. */
  30823. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30824. if (depth === void 0) { depth = 1; }
  30825. this.width = width;
  30826. this.height = height;
  30827. this.depth = depth;
  30828. this.baseWidth = width;
  30829. this.baseHeight = height;
  30830. this.baseDepth = depth;
  30831. this._size = width * height * depth;
  30832. };
  30833. /** @hidden */
  30834. InternalTexture.prototype._rebuild = function () {
  30835. var _this = this;
  30836. var proxy;
  30837. this.isReady = false;
  30838. this._cachedCoordinatesMode = null;
  30839. this._cachedWrapU = null;
  30840. this._cachedWrapV = null;
  30841. this._cachedAnisotropicFilteringLevel = null;
  30842. switch (this._dataSource) {
  30843. case InternalTexture.DATASOURCE_TEMP:
  30844. return;
  30845. case InternalTexture.DATASOURCE_URL:
  30846. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30847. _this.isReady = true;
  30848. }, null, this._buffer, undefined, this.format);
  30849. proxy._swapAndDie(this);
  30850. return;
  30851. case InternalTexture.DATASOURCE_RAW:
  30852. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30853. proxy._swapAndDie(this);
  30854. this.isReady = true;
  30855. return;
  30856. case InternalTexture.DATASOURCE_RAW3D:
  30857. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30858. proxy._swapAndDie(this);
  30859. this.isReady = true;
  30860. return;
  30861. case InternalTexture.DATASOURCE_DYNAMIC:
  30862. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30863. proxy._swapAndDie(this);
  30864. // The engine will make sure to update content so no need to flag it as isReady = true
  30865. return;
  30866. case InternalTexture.DATASOURCE_RENDERTARGET:
  30867. var options = new BABYLON.RenderTargetCreationOptions();
  30868. options.generateDepthBuffer = this._generateDepthBuffer;
  30869. options.generateMipMaps = this.generateMipMaps;
  30870. options.generateStencilBuffer = this._generateStencilBuffer;
  30871. options.samplingMode = this.samplingMode;
  30872. options.type = this.type;
  30873. if (this.isCube) {
  30874. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30875. }
  30876. else {
  30877. var size = {
  30878. width: this.width,
  30879. height: this.height
  30880. };
  30881. proxy = this._engine.createRenderTargetTexture(size, options);
  30882. }
  30883. proxy._swapAndDie(this);
  30884. this.isReady = true;
  30885. return;
  30886. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30887. var depthTextureOptions = {
  30888. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30889. comparisonFunction: this._comparisonFunction,
  30890. generateStencil: this._generateStencilBuffer,
  30891. isCube: this.isCube
  30892. };
  30893. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30894. proxy._swapAndDie(this);
  30895. this.isReady = true;
  30896. return;
  30897. case InternalTexture.DATASOURCE_CUBE:
  30898. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30899. _this.isReady = true;
  30900. }, null, this.format, this._extension);
  30901. proxy._swapAndDie(this);
  30902. return;
  30903. case InternalTexture.DATASOURCE_CUBERAW:
  30904. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30905. proxy._swapAndDie(this);
  30906. this.isReady = true;
  30907. return;
  30908. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30909. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30910. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30911. _this.isReady = true;
  30912. });
  30913. proxy._swapAndDie(this);
  30914. return;
  30915. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30916. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30917. if (proxy) {
  30918. proxy._swapAndDie(_this);
  30919. }
  30920. _this.isReady = true;
  30921. }, null, this.format, this._extension);
  30922. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30923. return;
  30924. }
  30925. };
  30926. /** @hidden */
  30927. InternalTexture.prototype._swapAndDie = function (target) {
  30928. target._webGLTexture = this._webGLTexture;
  30929. if (this._framebuffer) {
  30930. target._framebuffer = this._framebuffer;
  30931. }
  30932. if (this._depthStencilBuffer) {
  30933. target._depthStencilBuffer = this._depthStencilBuffer;
  30934. }
  30935. if (this._lodTextureHigh) {
  30936. if (target._lodTextureHigh) {
  30937. target._lodTextureHigh.dispose();
  30938. }
  30939. target._lodTextureHigh = this._lodTextureHigh;
  30940. }
  30941. if (this._lodTextureMid) {
  30942. if (target._lodTextureMid) {
  30943. target._lodTextureMid.dispose();
  30944. }
  30945. target._lodTextureMid = this._lodTextureMid;
  30946. }
  30947. if (this._lodTextureLow) {
  30948. if (target._lodTextureLow) {
  30949. target._lodTextureLow.dispose();
  30950. }
  30951. target._lodTextureLow = this._lodTextureLow;
  30952. }
  30953. var cache = this._engine.getLoadedTexturesCache();
  30954. var index = cache.indexOf(this);
  30955. if (index !== -1) {
  30956. cache.splice(index, 1);
  30957. }
  30958. };
  30959. /**
  30960. * Dispose the current allocated resources
  30961. */
  30962. InternalTexture.prototype.dispose = function () {
  30963. if (!this._webGLTexture) {
  30964. return;
  30965. }
  30966. this._references--;
  30967. if (this._references === 0) {
  30968. this._engine._releaseTexture(this);
  30969. this._webGLTexture = null;
  30970. this.previous = null;
  30971. this.next = null;
  30972. }
  30973. };
  30974. /**
  30975. * The source of the texture data is unknown
  30976. */
  30977. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30978. /**
  30979. * Texture data comes from an URL
  30980. */
  30981. InternalTexture.DATASOURCE_URL = 1;
  30982. /**
  30983. * Texture data is only used for temporary storage
  30984. */
  30985. InternalTexture.DATASOURCE_TEMP = 2;
  30986. /**
  30987. * Texture data comes from raw data (ArrayBuffer)
  30988. */
  30989. InternalTexture.DATASOURCE_RAW = 3;
  30990. /**
  30991. * Texture content is dynamic (video or dynamic texture)
  30992. */
  30993. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30994. /**
  30995. * Texture content is generated by rendering to it
  30996. */
  30997. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30998. /**
  30999. * Texture content is part of a multi render target process
  31000. */
  31001. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  31002. /**
  31003. * Texture data comes from a cube data file
  31004. */
  31005. InternalTexture.DATASOURCE_CUBE = 7;
  31006. /**
  31007. * Texture data comes from a raw cube data
  31008. */
  31009. InternalTexture.DATASOURCE_CUBERAW = 8;
  31010. /**
  31011. * Texture data come from a prefiltered cube data file
  31012. */
  31013. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  31014. /**
  31015. * Texture content is raw 3D data
  31016. */
  31017. InternalTexture.DATASOURCE_RAW3D = 10;
  31018. /**
  31019. * Texture content is a depth texture
  31020. */
  31021. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31022. /**
  31023. * Texture data comes from a raw cube data encoded with RGBD
  31024. */
  31025. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31026. return InternalTexture;
  31027. }());
  31028. BABYLON.InternalTexture = InternalTexture;
  31029. })(BABYLON || (BABYLON = {}));
  31030. //# sourceMappingURL=babylon.internalTexture.js.map
  31031. var BABYLON;
  31032. (function (BABYLON) {
  31033. /**
  31034. * Base class of all the textures in babylon.
  31035. * It groups all the common properties the materials, post process, lights... might need
  31036. * in order to make a correct use of the texture.
  31037. */
  31038. var BaseTexture = /** @class */ (function () {
  31039. /**
  31040. * Instantiates a new BaseTexture.
  31041. * Base class of all the textures in babylon.
  31042. * It groups all the common properties the materials, post process, lights... might need
  31043. * in order to make a correct use of the texture.
  31044. * @param scene Define the scene the texture blongs to
  31045. */
  31046. function BaseTexture(scene) {
  31047. this._hasAlpha = false;
  31048. /**
  31049. * Defines if the alpha value should be determined via the rgb values.
  31050. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31051. */
  31052. this.getAlphaFromRGB = false;
  31053. /**
  31054. * Intensity or strength of the texture.
  31055. * It is commonly used by materials to fine tune the intensity of the texture
  31056. */
  31057. this.level = 1;
  31058. /**
  31059. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31060. * This is part of the texture as textures usually maps to one uv set.
  31061. */
  31062. this.coordinatesIndex = 0;
  31063. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31064. /**
  31065. * | Value | Type | Description |
  31066. * | ----- | ------------------ | ----------- |
  31067. * | 0 | CLAMP_ADDRESSMODE | |
  31068. * | 1 | WRAP_ADDRESSMODE | |
  31069. * | 2 | MIRROR_ADDRESSMODE | |
  31070. */
  31071. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31072. /**
  31073. * | Value | Type | Description |
  31074. * | ----- | ------------------ | ----------- |
  31075. * | 0 | CLAMP_ADDRESSMODE | |
  31076. * | 1 | WRAP_ADDRESSMODE | |
  31077. * | 2 | MIRROR_ADDRESSMODE | |
  31078. */
  31079. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31080. /**
  31081. * | Value | Type | Description |
  31082. * | ----- | ------------------ | ----------- |
  31083. * | 0 | CLAMP_ADDRESSMODE | |
  31084. * | 1 | WRAP_ADDRESSMODE | |
  31085. * | 2 | MIRROR_ADDRESSMODE | |
  31086. */
  31087. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31088. /**
  31089. * With compliant hardware and browser (supporting anisotropic filtering)
  31090. * this defines the level of anisotropic filtering in the texture.
  31091. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31092. */
  31093. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31094. /**
  31095. * Define if the texture is a cube texture or if false a 2d texture.
  31096. */
  31097. this.isCube = false;
  31098. /**
  31099. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31100. */
  31101. this.is3D = false;
  31102. /**
  31103. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31104. * HDR texture are usually stored in linear space.
  31105. * This only impacts the PBR and Background materials
  31106. */
  31107. this.gammaSpace = true;
  31108. /**
  31109. * Is Z inverted in the texture (useful in a cube texture).
  31110. */
  31111. this.invertZ = false;
  31112. /**
  31113. * @hidden
  31114. */
  31115. this.lodLevelInAlpha = false;
  31116. /**
  31117. * Define if the texture is a render target.
  31118. */
  31119. this.isRenderTarget = false;
  31120. /**
  31121. * Define the list of animation attached to the texture.
  31122. */
  31123. this.animations = new Array();
  31124. /**
  31125. * An event triggered when the texture is disposed.
  31126. */
  31127. this.onDisposeObservable = new BABYLON.Observable();
  31128. /**
  31129. * Define the current state of the loading sequence when in delayed load mode.
  31130. */
  31131. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31132. this._cachedSize = BABYLON.Size.Zero();
  31133. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31134. if (this._scene) {
  31135. this._scene.textures.push(this);
  31136. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31137. }
  31138. this._uid = null;
  31139. }
  31140. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31141. get: function () {
  31142. return this._hasAlpha;
  31143. },
  31144. /**
  31145. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31146. */
  31147. set: function (value) {
  31148. if (this._hasAlpha === value) {
  31149. return;
  31150. }
  31151. this._hasAlpha = value;
  31152. if (this._scene) {
  31153. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31154. }
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31160. get: function () {
  31161. return this._coordinatesMode;
  31162. },
  31163. /**
  31164. * How a texture is mapped.
  31165. *
  31166. * | Value | Type | Description |
  31167. * | ----- | ----------------------------------- | ----------- |
  31168. * | 0 | EXPLICIT_MODE | |
  31169. * | 1 | SPHERICAL_MODE | |
  31170. * | 2 | PLANAR_MODE | |
  31171. * | 3 | CUBIC_MODE | |
  31172. * | 4 | PROJECTION_MODE | |
  31173. * | 5 | SKYBOX_MODE | |
  31174. * | 6 | INVCUBIC_MODE | |
  31175. * | 7 | EQUIRECTANGULAR_MODE | |
  31176. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31177. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31178. */
  31179. set: function (value) {
  31180. if (this._coordinatesMode === value) {
  31181. return;
  31182. }
  31183. this._coordinatesMode = value;
  31184. if (this._scene) {
  31185. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31186. }
  31187. },
  31188. enumerable: true,
  31189. configurable: true
  31190. });
  31191. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31192. /**
  31193. * Gets whether or not the texture contains RGBD data.
  31194. */
  31195. get: function () {
  31196. return this._texture != null && this._texture._isRGBD;
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31202. /**
  31203. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31204. */
  31205. get: function () {
  31206. if (this._texture) {
  31207. return this._texture._lodGenerationOffset;
  31208. }
  31209. return 0.0;
  31210. },
  31211. set: function (value) {
  31212. if (this._texture) {
  31213. this._texture._lodGenerationOffset = value;
  31214. }
  31215. },
  31216. enumerable: true,
  31217. configurable: true
  31218. });
  31219. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31220. /**
  31221. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31222. */
  31223. get: function () {
  31224. if (this._texture) {
  31225. return this._texture._lodGenerationScale;
  31226. }
  31227. return 0.0;
  31228. },
  31229. set: function (value) {
  31230. if (this._texture) {
  31231. this._texture._lodGenerationScale = value;
  31232. }
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. Object.defineProperty(BaseTexture.prototype, "uid", {
  31238. /**
  31239. * Define the unique id of the texture in the scene.
  31240. */
  31241. get: function () {
  31242. if (!this._uid) {
  31243. this._uid = BABYLON.Tools.RandomId();
  31244. }
  31245. return this._uid;
  31246. },
  31247. enumerable: true,
  31248. configurable: true
  31249. });
  31250. /**
  31251. * Return a string representation of the texture.
  31252. * @returns the texture as a string
  31253. */
  31254. BaseTexture.prototype.toString = function () {
  31255. return this.name;
  31256. };
  31257. /**
  31258. * Get the class name of the texture.
  31259. * @returns "BaseTexture"
  31260. */
  31261. BaseTexture.prototype.getClassName = function () {
  31262. return "BaseTexture";
  31263. };
  31264. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31265. /**
  31266. * Callback triggered when the texture has been disposed.
  31267. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31268. */
  31269. set: function (callback) {
  31270. if (this._onDisposeObserver) {
  31271. this.onDisposeObservable.remove(this._onDisposeObserver);
  31272. }
  31273. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31279. /**
  31280. * Define if the texture is preventinga material to render or not.
  31281. * If not and the texture is not ready, the engine will use a default black texture instead.
  31282. */
  31283. get: function () {
  31284. return true;
  31285. },
  31286. enumerable: true,
  31287. configurable: true
  31288. });
  31289. /**
  31290. * Get the scene the texture belongs to.
  31291. * @returns the scene or null if undefined
  31292. */
  31293. BaseTexture.prototype.getScene = function () {
  31294. return this._scene;
  31295. };
  31296. /**
  31297. * Get the texture transform matrix used to offset tile the texture for istance.
  31298. * @returns the transformation matrix
  31299. */
  31300. BaseTexture.prototype.getTextureMatrix = function () {
  31301. return BABYLON.Matrix.IdentityReadOnly;
  31302. };
  31303. /**
  31304. * Get the texture reflection matrix used to rotate/transform the reflection.
  31305. * @returns the reflection matrix
  31306. */
  31307. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31308. return BABYLON.Matrix.IdentityReadOnly;
  31309. };
  31310. /**
  31311. * Get the underlying lower level texture from Babylon.
  31312. * @returns the insternal texture
  31313. */
  31314. BaseTexture.prototype.getInternalTexture = function () {
  31315. return this._texture;
  31316. };
  31317. /**
  31318. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31319. * @returns true if ready or not blocking
  31320. */
  31321. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31322. return !this.isBlocking || this.isReady();
  31323. };
  31324. /**
  31325. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31326. * @returns true if fully ready
  31327. */
  31328. BaseTexture.prototype.isReady = function () {
  31329. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31330. this.delayLoad();
  31331. return false;
  31332. }
  31333. if (this._texture) {
  31334. return this._texture.isReady;
  31335. }
  31336. return false;
  31337. };
  31338. /**
  31339. * Get the size of the texture.
  31340. * @returns the texture size.
  31341. */
  31342. BaseTexture.prototype.getSize = function () {
  31343. if (this._texture) {
  31344. if (this._texture.width) {
  31345. this._cachedSize.width = this._texture.width;
  31346. this._cachedSize.height = this._texture.height;
  31347. return this._cachedSize;
  31348. }
  31349. if (this._texture._size) {
  31350. this._cachedSize.width = this._texture._size;
  31351. this._cachedSize.height = this._texture._size;
  31352. return this._cachedSize;
  31353. }
  31354. }
  31355. return this._cachedSize;
  31356. };
  31357. /**
  31358. * Get the base size of the texture.
  31359. * It can be different from the size if the texture has been resized for POT for instance
  31360. * @returns the base size
  31361. */
  31362. BaseTexture.prototype.getBaseSize = function () {
  31363. if (!this.isReady() || !this._texture) {
  31364. return BABYLON.Size.Zero();
  31365. }
  31366. if (this._texture._size) {
  31367. return new BABYLON.Size(this._texture._size, this._texture._size);
  31368. }
  31369. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31370. };
  31371. /**
  31372. * Scales the texture if is `canRescale()`
  31373. * @param ratio the resize factor we want to use to rescale
  31374. */
  31375. BaseTexture.prototype.scale = function (ratio) {
  31376. };
  31377. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31378. /**
  31379. * Get if the texture can rescale.
  31380. */
  31381. get: function () {
  31382. return false;
  31383. },
  31384. enumerable: true,
  31385. configurable: true
  31386. });
  31387. /** @hidden */
  31388. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31389. if (!this._scene) {
  31390. return null;
  31391. }
  31392. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31393. for (var index = 0; index < texturesCache.length; index++) {
  31394. var texturesCacheEntry = texturesCache[index];
  31395. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31396. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31397. texturesCacheEntry.incrementReferences();
  31398. return texturesCacheEntry;
  31399. }
  31400. }
  31401. }
  31402. return null;
  31403. };
  31404. /** @hidden */
  31405. BaseTexture.prototype._rebuild = function () {
  31406. };
  31407. /**
  31408. * Triggers the load sequence in delayed load mode.
  31409. */
  31410. BaseTexture.prototype.delayLoad = function () {
  31411. };
  31412. /**
  31413. * Clones the texture.
  31414. * @returns the cloned texture
  31415. */
  31416. BaseTexture.prototype.clone = function () {
  31417. return null;
  31418. };
  31419. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31420. /**
  31421. * Get the texture underlying type (INT, FLOAT...)
  31422. */
  31423. get: function () {
  31424. if (!this._texture) {
  31425. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31426. }
  31427. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31428. },
  31429. enumerable: true,
  31430. configurable: true
  31431. });
  31432. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31433. /**
  31434. * Get the texture underlying format (RGB, RGBA...)
  31435. */
  31436. get: function () {
  31437. if (!this._texture) {
  31438. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31439. }
  31440. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31441. },
  31442. enumerable: true,
  31443. configurable: true
  31444. });
  31445. /**
  31446. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31447. * This will returns an RGBA array buffer containing either in values (0-255) or
  31448. * float values (0-1) depending of the underlying buffer type.
  31449. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31450. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31451. * @param buffer defines a user defined buffer to fill with data (can be null)
  31452. * @returns The Array buffer containing the pixels data.
  31453. */
  31454. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31455. if (faceIndex === void 0) { faceIndex = 0; }
  31456. if (level === void 0) { level = 0; }
  31457. if (buffer === void 0) { buffer = null; }
  31458. if (!this._texture) {
  31459. return null;
  31460. }
  31461. var size = this.getSize();
  31462. var width = size.width;
  31463. var height = size.height;
  31464. var scene = this.getScene();
  31465. if (!scene) {
  31466. return null;
  31467. }
  31468. var engine = scene.getEngine();
  31469. if (level != 0) {
  31470. width = width / Math.pow(2, level);
  31471. height = height / Math.pow(2, level);
  31472. width = Math.round(width);
  31473. height = Math.round(height);
  31474. }
  31475. if (this._texture.isCube) {
  31476. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31477. }
  31478. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31479. };
  31480. /**
  31481. * Release and destroy the underlying lower level texture aka internalTexture.
  31482. */
  31483. BaseTexture.prototype.releaseInternalTexture = function () {
  31484. if (this._texture) {
  31485. this._texture.dispose();
  31486. this._texture = null;
  31487. }
  31488. };
  31489. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31490. /**
  31491. * Get the polynomial representation of the texture data.
  31492. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31493. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31494. */
  31495. get: function () {
  31496. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31497. return null;
  31498. }
  31499. if (!this._texture._sphericalPolynomial) {
  31500. this._texture._sphericalPolynomial =
  31501. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31502. }
  31503. return this._texture._sphericalPolynomial;
  31504. },
  31505. set: function (value) {
  31506. if (this._texture) {
  31507. this._texture._sphericalPolynomial = value;
  31508. }
  31509. },
  31510. enumerable: true,
  31511. configurable: true
  31512. });
  31513. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31514. /** @hidden */
  31515. get: function () {
  31516. if (this._texture) {
  31517. return this._texture._lodTextureHigh;
  31518. }
  31519. return null;
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31525. /** @hidden */
  31526. get: function () {
  31527. if (this._texture) {
  31528. return this._texture._lodTextureMid;
  31529. }
  31530. return null;
  31531. },
  31532. enumerable: true,
  31533. configurable: true
  31534. });
  31535. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31536. /** @hidden */
  31537. get: function () {
  31538. if (this._texture) {
  31539. return this._texture._lodTextureLow;
  31540. }
  31541. return null;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. /**
  31547. * Dispose the texture and release its associated resources.
  31548. */
  31549. BaseTexture.prototype.dispose = function () {
  31550. if (!this._scene) {
  31551. return;
  31552. }
  31553. // Animations
  31554. this._scene.stopAnimation(this);
  31555. // Remove from scene
  31556. this._scene._removePendingData(this);
  31557. var index = this._scene.textures.indexOf(this);
  31558. if (index >= 0) {
  31559. this._scene.textures.splice(index, 1);
  31560. }
  31561. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31562. if (this._texture === undefined) {
  31563. return;
  31564. }
  31565. // Release
  31566. this.releaseInternalTexture();
  31567. // Callback
  31568. this.onDisposeObservable.notifyObservers(this);
  31569. this.onDisposeObservable.clear();
  31570. };
  31571. /**
  31572. * Serialize the texture into a JSON representation that can be parsed later on.
  31573. * @returns the JSON representation of the texture
  31574. */
  31575. BaseTexture.prototype.serialize = function () {
  31576. if (!this.name) {
  31577. return null;
  31578. }
  31579. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31580. // Animations
  31581. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31582. return serializationObject;
  31583. };
  31584. /**
  31585. * Helper function to be called back once a list of texture contains only ready textures.
  31586. * @param textures Define the list of textures to wait for
  31587. * @param callback Define the callback triggered once the entire list will be ready
  31588. */
  31589. BaseTexture.WhenAllReady = function (textures, callback) {
  31590. var numRemaining = textures.length;
  31591. if (numRemaining === 0) {
  31592. callback();
  31593. return;
  31594. }
  31595. var _loop_1 = function () {
  31596. texture = textures[i];
  31597. if (texture.isReady()) {
  31598. if (--numRemaining === 0) {
  31599. callback();
  31600. }
  31601. }
  31602. else {
  31603. onLoadObservable = texture.onLoadObservable;
  31604. var onLoadCallback_1 = function () {
  31605. onLoadObservable.removeCallback(onLoadCallback_1);
  31606. if (--numRemaining === 0) {
  31607. callback();
  31608. }
  31609. };
  31610. onLoadObservable.add(onLoadCallback_1);
  31611. }
  31612. };
  31613. var texture, onLoadObservable;
  31614. for (var i = 0; i < textures.length; i++) {
  31615. _loop_1();
  31616. }
  31617. };
  31618. /**
  31619. * Default anisotropic filtering level for the application.
  31620. * It is set to 4 as a good tradeoff between perf and quality.
  31621. */
  31622. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31623. __decorate([
  31624. BABYLON.serialize()
  31625. ], BaseTexture.prototype, "name", void 0);
  31626. __decorate([
  31627. BABYLON.serialize("hasAlpha")
  31628. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31629. __decorate([
  31630. BABYLON.serialize()
  31631. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31632. __decorate([
  31633. BABYLON.serialize()
  31634. ], BaseTexture.prototype, "level", void 0);
  31635. __decorate([
  31636. BABYLON.serialize()
  31637. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31638. __decorate([
  31639. BABYLON.serialize("coordinatesMode")
  31640. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31641. __decorate([
  31642. BABYLON.serialize()
  31643. ], BaseTexture.prototype, "wrapU", void 0);
  31644. __decorate([
  31645. BABYLON.serialize()
  31646. ], BaseTexture.prototype, "wrapV", void 0);
  31647. __decorate([
  31648. BABYLON.serialize()
  31649. ], BaseTexture.prototype, "wrapR", void 0);
  31650. __decorate([
  31651. BABYLON.serialize()
  31652. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31653. __decorate([
  31654. BABYLON.serialize()
  31655. ], BaseTexture.prototype, "isCube", void 0);
  31656. __decorate([
  31657. BABYLON.serialize()
  31658. ], BaseTexture.prototype, "is3D", void 0);
  31659. __decorate([
  31660. BABYLON.serialize()
  31661. ], BaseTexture.prototype, "gammaSpace", void 0);
  31662. __decorate([
  31663. BABYLON.serialize()
  31664. ], BaseTexture.prototype, "invertZ", void 0);
  31665. __decorate([
  31666. BABYLON.serialize()
  31667. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31668. __decorate([
  31669. BABYLON.serialize()
  31670. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31671. __decorate([
  31672. BABYLON.serialize()
  31673. ], BaseTexture.prototype, "lodGenerationScale", null);
  31674. __decorate([
  31675. BABYLON.serialize()
  31676. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31677. return BaseTexture;
  31678. }());
  31679. BABYLON.BaseTexture = BaseTexture;
  31680. })(BABYLON || (BABYLON = {}));
  31681. //# sourceMappingURL=babylon.baseTexture.js.map
  31682. var BABYLON;
  31683. (function (BABYLON) {
  31684. /**
  31685. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31686. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31687. */
  31688. var Texture = /** @class */ (function (_super) {
  31689. __extends(Texture, _super);
  31690. /**
  31691. * Instantiates a new texture.
  31692. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31693. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31694. * @param url define the url of the picture to load as a texture
  31695. * @param scene define the scene the texture will belong to
  31696. * @param noMipmap define if the texture will require mip maps or not
  31697. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31698. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31699. * @param onLoad define a callback triggered when the texture has been loaded
  31700. * @param onError define a callback triggered when an error occurred during the loading session
  31701. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31702. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31703. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31704. */
  31705. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31706. if (noMipmap === void 0) { noMipmap = false; }
  31707. if (invertY === void 0) { invertY = true; }
  31708. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31709. if (onLoad === void 0) { onLoad = null; }
  31710. if (onError === void 0) { onError = null; }
  31711. if (buffer === void 0) { buffer = null; }
  31712. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31713. var _this = _super.call(this, scene) || this;
  31714. /**
  31715. * Define an offset on the texture to offset the u coordinates of the UVs
  31716. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31717. */
  31718. _this.uOffset = 0;
  31719. /**
  31720. * Define an offset on the texture to offset the v coordinates of the UVs
  31721. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31722. */
  31723. _this.vOffset = 0;
  31724. /**
  31725. * Define an offset on the texture to scale the u coordinates of the UVs
  31726. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31727. */
  31728. _this.uScale = 1.0;
  31729. /**
  31730. * Define an offset on the texture to scale the v coordinates of the UVs
  31731. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31732. */
  31733. _this.vScale = 1.0;
  31734. /**
  31735. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31736. * @see http://doc.babylonjs.com/how_to/more_materials
  31737. */
  31738. _this.uAng = 0;
  31739. /**
  31740. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31741. * @see http://doc.babylonjs.com/how_to/more_materials
  31742. */
  31743. _this.vAng = 0;
  31744. /**
  31745. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31746. * @see http://doc.babylonjs.com/how_to/more_materials
  31747. */
  31748. _this.wAng = 0;
  31749. /**
  31750. * Defines the center of rotation (U)
  31751. */
  31752. _this.uRotationCenter = 0.5;
  31753. /**
  31754. * Defines the center of rotation (V)
  31755. */
  31756. _this.vRotationCenter = 0.5;
  31757. /**
  31758. * Defines the center of rotation (W)
  31759. */
  31760. _this.wRotationCenter = 0.5;
  31761. /**
  31762. * Observable triggered once the texture has been loaded.
  31763. */
  31764. _this.onLoadObservable = new BABYLON.Observable();
  31765. _this._isBlocking = true;
  31766. _this.name = url || "";
  31767. _this.url = url;
  31768. _this._noMipmap = noMipmap;
  31769. _this._invertY = invertY;
  31770. _this._samplingMode = samplingMode;
  31771. _this._buffer = buffer;
  31772. _this._deleteBuffer = deleteBuffer;
  31773. if (format) {
  31774. _this._format = format;
  31775. }
  31776. scene = _this.getScene();
  31777. if (!scene) {
  31778. return _this;
  31779. }
  31780. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31781. var load = function () {
  31782. if (_this.onLoadObservable.hasObservers()) {
  31783. _this.onLoadObservable.notifyObservers(_this);
  31784. }
  31785. if (onLoad) {
  31786. onLoad();
  31787. }
  31788. if (!_this.isBlocking && scene) {
  31789. scene.resetCachedMaterial();
  31790. }
  31791. };
  31792. if (!_this.url) {
  31793. _this._delayedOnLoad = load;
  31794. _this._delayedOnError = onError;
  31795. return _this;
  31796. }
  31797. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31798. if (!_this._texture) {
  31799. if (!scene.useDelayedTextureLoading) {
  31800. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31801. if (deleteBuffer) {
  31802. delete _this._buffer;
  31803. }
  31804. }
  31805. else {
  31806. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31807. _this._delayedOnLoad = load;
  31808. _this._delayedOnError = onError;
  31809. }
  31810. }
  31811. else {
  31812. if (_this._texture.isReady) {
  31813. BABYLON.Tools.SetImmediate(function () { return load(); });
  31814. }
  31815. else {
  31816. _this._texture.onLoadedObservable.add(load);
  31817. }
  31818. }
  31819. return _this;
  31820. }
  31821. Object.defineProperty(Texture.prototype, "noMipmap", {
  31822. /**
  31823. * Are mip maps generated for this texture or not.
  31824. */
  31825. get: function () {
  31826. return this._noMipmap;
  31827. },
  31828. enumerable: true,
  31829. configurable: true
  31830. });
  31831. Object.defineProperty(Texture.prototype, "isBlocking", {
  31832. get: function () {
  31833. return this._isBlocking;
  31834. },
  31835. /**
  31836. * Is the texture preventing material to render while loading.
  31837. * If false, a default texture will be used instead of the loading one during the preparation step.
  31838. */
  31839. set: function (value) {
  31840. this._isBlocking = value;
  31841. },
  31842. enumerable: true,
  31843. configurable: true
  31844. });
  31845. Object.defineProperty(Texture.prototype, "samplingMode", {
  31846. /**
  31847. * Get the current sampling mode associated with the texture.
  31848. */
  31849. get: function () {
  31850. return this._samplingMode;
  31851. },
  31852. enumerable: true,
  31853. configurable: true
  31854. });
  31855. /**
  31856. * Update the url (and optional buffer) of this texture if url was null during construction.
  31857. * @param url the url of the texture
  31858. * @param buffer the buffer of the texture (defaults to null)
  31859. */
  31860. Texture.prototype.updateURL = function (url, buffer) {
  31861. if (buffer === void 0) { buffer = null; }
  31862. if (this.url) {
  31863. throw new Error("URL is already set");
  31864. }
  31865. this.url = url;
  31866. this._buffer = buffer;
  31867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31868. this.delayLoad();
  31869. };
  31870. /**
  31871. * Finish the loading sequence of a texture flagged as delayed load.
  31872. * @hidden
  31873. */
  31874. Texture.prototype.delayLoad = function () {
  31875. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31876. return;
  31877. }
  31878. var scene = this.getScene();
  31879. if (!scene) {
  31880. return;
  31881. }
  31882. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31883. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31884. if (!this._texture) {
  31885. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31886. if (this._deleteBuffer) {
  31887. delete this._buffer;
  31888. }
  31889. }
  31890. else {
  31891. if (this._delayedOnLoad) {
  31892. if (this._texture.isReady) {
  31893. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31894. }
  31895. else {
  31896. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31897. }
  31898. }
  31899. }
  31900. this._delayedOnLoad = null;
  31901. this._delayedOnError = null;
  31902. };
  31903. /**
  31904. * Update the sampling mode of the texture.
  31905. * Default is Trilinear mode.
  31906. *
  31907. * | Value | Type | Description |
  31908. * | ----- | ------------------ | ----------- |
  31909. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31910. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31911. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31912. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31913. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31914. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31915. * | 7 | NEAREST_LINEAR | |
  31916. * | 8 | NEAREST_NEAREST | |
  31917. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31918. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31919. * | 11 | LINEAR_LINEAR | |
  31920. * | 12 | LINEAR_NEAREST | |
  31921. *
  31922. * > _mag_: magnification filter (close to the viewer)
  31923. * > _min_: minification filter (far from the viewer)
  31924. * > _mip_: filter used between mip map levels
  31925. *@param samplingMode Define the new sampling mode of the texture
  31926. */
  31927. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31928. if (!this._texture) {
  31929. return;
  31930. }
  31931. var scene = this.getScene();
  31932. if (!scene) {
  31933. return;
  31934. }
  31935. this._samplingMode = samplingMode;
  31936. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31937. };
  31938. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31939. x *= this.uScale;
  31940. y *= this.vScale;
  31941. x -= this.uRotationCenter * this.uScale;
  31942. y -= this.vRotationCenter * this.vScale;
  31943. z -= this.wRotationCenter;
  31944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31945. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31946. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31947. t.z += this.wRotationCenter;
  31948. };
  31949. /**
  31950. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31951. * @returns the transform matrix of the texture.
  31952. */
  31953. Texture.prototype.getTextureMatrix = function () {
  31954. var _this = this;
  31955. if (this.uOffset === this._cachedUOffset &&
  31956. this.vOffset === this._cachedVOffset &&
  31957. this.uScale === this._cachedUScale &&
  31958. this.vScale === this._cachedVScale &&
  31959. this.uAng === this._cachedUAng &&
  31960. this.vAng === this._cachedVAng &&
  31961. this.wAng === this._cachedWAng) {
  31962. return this._cachedTextureMatrix;
  31963. }
  31964. this._cachedUOffset = this.uOffset;
  31965. this._cachedVOffset = this.vOffset;
  31966. this._cachedUScale = this.uScale;
  31967. this._cachedVScale = this.vScale;
  31968. this._cachedUAng = this.uAng;
  31969. this._cachedVAng = this.vAng;
  31970. this._cachedWAng = this.wAng;
  31971. if (!this._cachedTextureMatrix) {
  31972. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31973. this._rowGenerationMatrix = new BABYLON.Matrix();
  31974. this._t0 = BABYLON.Vector3.Zero();
  31975. this._t1 = BABYLON.Vector3.Zero();
  31976. this._t2 = BABYLON.Vector3.Zero();
  31977. }
  31978. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31979. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31980. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31981. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31982. this._t1.subtractInPlace(this._t0);
  31983. this._t2.subtractInPlace(this._t0);
  31984. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31985. this._cachedTextureMatrix.m[0] = this._t1.x;
  31986. this._cachedTextureMatrix.m[1] = this._t1.y;
  31987. this._cachedTextureMatrix.m[2] = this._t1.z;
  31988. this._cachedTextureMatrix.m[4] = this._t2.x;
  31989. this._cachedTextureMatrix.m[5] = this._t2.y;
  31990. this._cachedTextureMatrix.m[6] = this._t2.z;
  31991. this._cachedTextureMatrix.m[8] = this._t0.x;
  31992. this._cachedTextureMatrix.m[9] = this._t0.y;
  31993. this._cachedTextureMatrix.m[10] = this._t0.z;
  31994. var scene = this.getScene();
  31995. if (!scene) {
  31996. return this._cachedTextureMatrix;
  31997. }
  31998. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31999. return mat.hasTexture(_this);
  32000. });
  32001. return this._cachedTextureMatrix;
  32002. };
  32003. /**
  32004. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  32005. * @returns The reflection texture transform
  32006. */
  32007. Texture.prototype.getReflectionTextureMatrix = function () {
  32008. var _this = this;
  32009. var scene = this.getScene();
  32010. if (!scene) {
  32011. return this._cachedTextureMatrix;
  32012. }
  32013. if (this.uOffset === this._cachedUOffset &&
  32014. this.vOffset === this._cachedVOffset &&
  32015. this.uScale === this._cachedUScale &&
  32016. this.vScale === this._cachedVScale &&
  32017. this.coordinatesMode === this._cachedCoordinatesMode) {
  32018. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  32019. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  32020. return this._cachedTextureMatrix;
  32021. }
  32022. }
  32023. else {
  32024. return this._cachedTextureMatrix;
  32025. }
  32026. }
  32027. if (!this._cachedTextureMatrix) {
  32028. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32029. }
  32030. if (!this._projectionModeMatrix) {
  32031. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32032. }
  32033. this._cachedUOffset = this.uOffset;
  32034. this._cachedVOffset = this.vOffset;
  32035. this._cachedUScale = this.uScale;
  32036. this._cachedVScale = this.vScale;
  32037. this._cachedCoordinatesMode = this.coordinatesMode;
  32038. switch (this.coordinatesMode) {
  32039. case Texture.PLANAR_MODE:
  32040. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32041. this._cachedTextureMatrix[0] = this.uScale;
  32042. this._cachedTextureMatrix[5] = this.vScale;
  32043. this._cachedTextureMatrix[12] = this.uOffset;
  32044. this._cachedTextureMatrix[13] = this.vOffset;
  32045. break;
  32046. case Texture.PROJECTION_MODE:
  32047. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  32048. this._projectionModeMatrix.m[0] = 0.5;
  32049. this._projectionModeMatrix.m[5] = -0.5;
  32050. this._projectionModeMatrix.m[10] = 0.0;
  32051. this._projectionModeMatrix.m[12] = 0.5;
  32052. this._projectionModeMatrix.m[13] = 0.5;
  32053. this._projectionModeMatrix.m[14] = 1.0;
  32054. this._projectionModeMatrix.m[15] = 1.0;
  32055. var projectionMatrix = scene.getProjectionMatrix();
  32056. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32057. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32058. break;
  32059. default:
  32060. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32061. break;
  32062. }
  32063. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32064. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32065. });
  32066. return this._cachedTextureMatrix;
  32067. };
  32068. /**
  32069. * Clones the texture.
  32070. * @returns the cloned texture
  32071. */
  32072. Texture.prototype.clone = function () {
  32073. var _this = this;
  32074. return BABYLON.SerializationHelper.Clone(function () {
  32075. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  32076. }, this);
  32077. };
  32078. /**
  32079. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32080. * @returns The JSON representation of the texture
  32081. */
  32082. Texture.prototype.serialize = function () {
  32083. var serializationObject = _super.prototype.serialize.call(this);
  32084. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32085. serializationObject.base64String = this._buffer;
  32086. serializationObject.name = serializationObject.name.replace("data:", "");
  32087. }
  32088. serializationObject.invertY = this._invertY;
  32089. serializationObject.samplingMode = this.samplingMode;
  32090. return serializationObject;
  32091. };
  32092. /**
  32093. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32094. * @returns "Texture"
  32095. */
  32096. Texture.prototype.getClassName = function () {
  32097. return "Texture";
  32098. };
  32099. /**
  32100. * Dispose the texture and release its associated resources.
  32101. */
  32102. Texture.prototype.dispose = function () {
  32103. _super.prototype.dispose.call(this);
  32104. this.onLoadObservable.clear();
  32105. this._delayedOnLoad = null;
  32106. this._delayedOnError = null;
  32107. };
  32108. /**
  32109. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32110. * @param parsedTexture Define the JSON representation of the texture
  32111. * @param scene Define the scene the parsed texture should be instantiated in
  32112. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32113. * @returns The parsed texture if successful
  32114. */
  32115. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32116. if (parsedTexture.customType) {
  32117. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32118. // Update Sampling Mode
  32119. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32120. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32121. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32122. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32123. }
  32124. }
  32125. return parsedCustomTexture;
  32126. }
  32127. if (parsedTexture.isCube) {
  32128. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32129. }
  32130. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32131. return null;
  32132. }
  32133. var texture = BABYLON.SerializationHelper.Parse(function () {
  32134. var generateMipMaps = true;
  32135. if (parsedTexture.noMipmap) {
  32136. generateMipMaps = false;
  32137. }
  32138. if (parsedTexture.mirrorPlane) {
  32139. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32140. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32141. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32142. return mirrorTexture;
  32143. }
  32144. else if (parsedTexture.isRenderTarget) {
  32145. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32146. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32147. return renderTargetTexture;
  32148. }
  32149. else {
  32150. var texture;
  32151. if (parsedTexture.base64String) {
  32152. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32153. }
  32154. else {
  32155. var url = rootUrl + parsedTexture.name;
  32156. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32157. url = parsedTexture.url;
  32158. }
  32159. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32160. }
  32161. return texture;
  32162. }
  32163. }, parsedTexture, scene);
  32164. // Update Sampling Mode
  32165. if (parsedTexture.samplingMode) {
  32166. var sampling = parsedTexture.samplingMode;
  32167. if (texture._samplingMode !== sampling) {
  32168. texture.updateSamplingMode(sampling);
  32169. }
  32170. }
  32171. // Animations
  32172. if (parsedTexture.animations) {
  32173. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32174. var parsedAnimation = parsedTexture.animations[animationIndex];
  32175. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32176. }
  32177. }
  32178. return texture;
  32179. };
  32180. /**
  32181. * Creates a texture from its base 64 representation.
  32182. * @param data Define the base64 payload without the data: prefix
  32183. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32184. * @param scene Define the scene the texture should belong to
  32185. * @param noMipmap Forces the texture to not create mip map information if true
  32186. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32187. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32188. * @param onLoad define a callback triggered when the texture has been loaded
  32189. * @param onError define a callback triggered when an error occurred during the loading session
  32190. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32191. * @returns the created texture
  32192. */
  32193. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32194. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32195. if (onLoad === void 0) { onLoad = null; }
  32196. if (onError === void 0) { onError = null; }
  32197. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32198. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32199. };
  32200. /**
  32201. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32202. * @param data Define the base64 payload without the data: prefix
  32203. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32204. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32205. * @param scene Define the scene the texture should belong to
  32206. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32207. * @param noMipmap Forces the texture to not create mip map information if true
  32208. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32209. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32210. * @param onLoad define a callback triggered when the texture has been loaded
  32211. * @param onError define a callback triggered when an error occurred during the loading session
  32212. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32213. * @returns the created texture
  32214. */
  32215. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32216. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32217. if (noMipmap === void 0) { noMipmap = false; }
  32218. if (invertY === void 0) { invertY = true; }
  32219. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32220. if (onLoad === void 0) { onLoad = null; }
  32221. if (onError === void 0) { onError = null; }
  32222. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32223. if (name.substr(0, 5) !== "data:") {
  32224. name = "data:" + name;
  32225. }
  32226. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32227. };
  32228. /** nearest is mag = nearest and min = nearest and mip = linear */
  32229. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32230. /** nearest is mag = nearest and min = nearest and mip = linear */
  32231. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32232. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32233. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32234. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32235. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32236. /** Trilinear is mag = linear and min = linear and mip = linear */
  32237. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32238. /** Trilinear is mag = linear and min = linear and mip = linear */
  32239. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32240. /** mag = nearest and min = nearest and mip = nearest */
  32241. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32242. /** mag = nearest and min = linear and mip = nearest */
  32243. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32244. /** mag = nearest and min = linear and mip = linear */
  32245. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32246. /** mag = nearest and min = linear and mip = none */
  32247. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32248. /** mag = nearest and min = nearest and mip = none */
  32249. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32250. /** mag = linear and min = nearest and mip = nearest */
  32251. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32252. /** mag = linear and min = nearest and mip = linear */
  32253. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32254. /** mag = linear and min = linear and mip = none */
  32255. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32256. /** mag = linear and min = nearest and mip = none */
  32257. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32258. /** Explicit coordinates mode */
  32259. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32260. /** Spherical coordinates mode */
  32261. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32262. /** Planar coordinates mode */
  32263. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32264. /** Cubic coordinates mode */
  32265. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32266. /** Projection coordinates mode */
  32267. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32268. /** Inverse Cubic coordinates mode */
  32269. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32270. /** Inverse Cubic coordinates mode */
  32271. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32272. /** Equirectangular coordinates mode */
  32273. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32274. /** Equirectangular Fixed coordinates mode */
  32275. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32276. /** Equirectangular Fixed Mirrored coordinates mode */
  32277. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32278. /** Texture is not repeating outside of 0..1 UVs */
  32279. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32280. /** Texture is repeating outside of 0..1 UVs */
  32281. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32282. /** Texture is repeating and mirrored */
  32283. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32284. /**
  32285. * 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
  32286. */
  32287. Texture.UseSerializedUrlIfAny = false;
  32288. __decorate([
  32289. BABYLON.serialize()
  32290. ], Texture.prototype, "url", void 0);
  32291. __decorate([
  32292. BABYLON.serialize()
  32293. ], Texture.prototype, "uOffset", void 0);
  32294. __decorate([
  32295. BABYLON.serialize()
  32296. ], Texture.prototype, "vOffset", void 0);
  32297. __decorate([
  32298. BABYLON.serialize()
  32299. ], Texture.prototype, "uScale", void 0);
  32300. __decorate([
  32301. BABYLON.serialize()
  32302. ], Texture.prototype, "vScale", void 0);
  32303. __decorate([
  32304. BABYLON.serialize()
  32305. ], Texture.prototype, "uAng", void 0);
  32306. __decorate([
  32307. BABYLON.serialize()
  32308. ], Texture.prototype, "vAng", void 0);
  32309. __decorate([
  32310. BABYLON.serialize()
  32311. ], Texture.prototype, "wAng", void 0);
  32312. __decorate([
  32313. BABYLON.serialize()
  32314. ], Texture.prototype, "uRotationCenter", void 0);
  32315. __decorate([
  32316. BABYLON.serialize()
  32317. ], Texture.prototype, "vRotationCenter", void 0);
  32318. __decorate([
  32319. BABYLON.serialize()
  32320. ], Texture.prototype, "wRotationCenter", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], Texture.prototype, "isBlocking", null);
  32324. return Texture;
  32325. }(BABYLON.BaseTexture));
  32326. BABYLON.Texture = Texture;
  32327. })(BABYLON || (BABYLON = {}));
  32328. //# sourceMappingURL=babylon.texture.js.map
  32329. var BABYLON;
  32330. (function (BABYLON) {
  32331. /**
  32332. * @hidden
  32333. **/
  32334. var _CreationDataStorage = /** @class */ (function () {
  32335. function _CreationDataStorage() {
  32336. }
  32337. return _CreationDataStorage;
  32338. }());
  32339. BABYLON._CreationDataStorage = _CreationDataStorage;
  32340. /**
  32341. * @hidden
  32342. **/
  32343. var _InstanceDataStorage = /** @class */ (function () {
  32344. function _InstanceDataStorage() {
  32345. this.visibleInstances = {};
  32346. this.renderIdForInstances = new Array();
  32347. this.batchCache = new _InstancesBatch();
  32348. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32349. }
  32350. return _InstanceDataStorage;
  32351. }());
  32352. /**
  32353. * @hidden
  32354. **/
  32355. var _InstancesBatch = /** @class */ (function () {
  32356. function _InstancesBatch() {
  32357. this.mustReturn = false;
  32358. this.visibleInstances = new Array();
  32359. this.renderSelf = new Array();
  32360. }
  32361. return _InstancesBatch;
  32362. }());
  32363. BABYLON._InstancesBatch = _InstancesBatch;
  32364. /**
  32365. * Class used to represent renderable models
  32366. */
  32367. var Mesh = /** @class */ (function (_super) {
  32368. __extends(Mesh, _super);
  32369. /**
  32370. * @constructor
  32371. * @param name The value used by scene.getMeshByName() to do a lookup.
  32372. * @param scene The scene to add this mesh to.
  32373. * @param parent The parent of this mesh, if it has one
  32374. * @param source An optional Mesh from which geometry is shared, cloned.
  32375. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32376. * When false, achieved by calling a clone(), also passing False.
  32377. * This will make creation of children, recursive.
  32378. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32379. */
  32380. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32381. if (scene === void 0) { scene = null; }
  32382. if (parent === void 0) { parent = null; }
  32383. if (source === void 0) { source = null; }
  32384. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32385. var _this = _super.call(this, name, scene) || this;
  32386. // Members
  32387. /**
  32388. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32389. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32390. */
  32391. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32392. /**
  32393. * Gets the list of instances created from this mesh
  32394. * it is not supposed to be modified manually.
  32395. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32396. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32397. */
  32398. _this.instances = new Array();
  32399. _this._LODLevels = new Array();
  32400. /** @hidden */
  32401. _this._instanceDataStorage = new _InstanceDataStorage();
  32402. // Use by builder only to know what orientation were the mesh build in.
  32403. /** @hidden */
  32404. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32405. /**
  32406. * Use this property to change the original side orientation defined at construction time
  32407. */
  32408. _this.overrideMaterialSideOrientation = null;
  32409. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32410. // Will be used to save a source mesh reference, If any
  32411. _this._source = null;
  32412. scene = _this.getScene();
  32413. if (source) {
  32414. // Geometry
  32415. if (source._geometry) {
  32416. source._geometry.applyToMesh(_this);
  32417. }
  32418. // Deep copy
  32419. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32420. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32421. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32422. ], ["_poseMatrix"]);
  32423. // Source mesh
  32424. _this._source = source;
  32425. if (scene.useClonedMeshhMap) {
  32426. if (!source.meshMap) {
  32427. source.meshMap = {};
  32428. }
  32429. source.meshMap[_this.uniqueId] = _this;
  32430. }
  32431. // Construction Params
  32432. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32433. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32434. _this._creationDataStorage = source._creationDataStorage;
  32435. // Animation ranges
  32436. if (_this._source._ranges) {
  32437. var ranges = _this._source._ranges;
  32438. for (var name in ranges) {
  32439. if (!ranges.hasOwnProperty(name)) {
  32440. continue;
  32441. }
  32442. if (!ranges[name]) {
  32443. continue;
  32444. }
  32445. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32446. }
  32447. }
  32448. // Metadata
  32449. if (source.metadata && source.metadata.clone) {
  32450. _this.metadata = source.metadata.clone();
  32451. }
  32452. else {
  32453. _this.metadata = source.metadata;
  32454. }
  32455. // Tags
  32456. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32457. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32458. }
  32459. // Parent
  32460. _this.parent = source.parent;
  32461. // Pivot
  32462. _this.setPivotMatrix(source.getPivotMatrix());
  32463. _this.id = name + "." + source.id;
  32464. // Material
  32465. _this.material = source.material;
  32466. var index;
  32467. if (!doNotCloneChildren) {
  32468. // Children
  32469. var directDescendants = source.getDescendants(true);
  32470. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32471. var child = directDescendants[index_1];
  32472. if (child.clone) {
  32473. child.clone(name + "." + child.name, _this);
  32474. }
  32475. }
  32476. }
  32477. // Physics clone
  32478. var physicsEngine = _this.getScene().getPhysicsEngine();
  32479. if (clonePhysicsImpostor && physicsEngine) {
  32480. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32481. if (impostor) {
  32482. _this.physicsImpostor = impostor.clone(_this);
  32483. }
  32484. }
  32485. // Particles
  32486. for (index = 0; index < scene.particleSystems.length; index++) {
  32487. var system = scene.particleSystems[index];
  32488. if (system.emitter === source) {
  32489. system.clone(system.name, _this);
  32490. }
  32491. }
  32492. _this.refreshBoundingInfo();
  32493. _this.computeWorldMatrix(true);
  32494. }
  32495. // Parent
  32496. if (parent !== null) {
  32497. _this.parent = parent;
  32498. }
  32499. return _this;
  32500. }
  32501. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32502. /**
  32503. * An event triggered before rendering the mesh
  32504. */
  32505. get: function () {
  32506. if (!this._onBeforeRenderObservable) {
  32507. this._onBeforeRenderObservable = new BABYLON.Observable();
  32508. }
  32509. return this._onBeforeRenderObservable;
  32510. },
  32511. enumerable: true,
  32512. configurable: true
  32513. });
  32514. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32515. /**
  32516. * An event triggered after rendering the mesh
  32517. */
  32518. get: function () {
  32519. if (!this._onAfterRenderObservable) {
  32520. this._onAfterRenderObservable = new BABYLON.Observable();
  32521. }
  32522. return this._onAfterRenderObservable;
  32523. },
  32524. enumerable: true,
  32525. configurable: true
  32526. });
  32527. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32528. /**
  32529. * An event triggered before drawing the mesh
  32530. */
  32531. get: function () {
  32532. if (!this._onBeforeDrawObservable) {
  32533. this._onBeforeDrawObservable = new BABYLON.Observable();
  32534. }
  32535. return this._onBeforeDrawObservable;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32541. /**
  32542. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32543. */
  32544. set: function (callback) {
  32545. if (this._onBeforeDrawObserver) {
  32546. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32547. }
  32548. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32554. /**
  32555. * Gets or sets the morph target manager
  32556. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32557. */
  32558. get: function () {
  32559. return this._morphTargetManager;
  32560. },
  32561. set: function (value) {
  32562. if (this._morphTargetManager === value) {
  32563. return;
  32564. }
  32565. this._morphTargetManager = value;
  32566. this._syncGeometryWithMorphTargetManager();
  32567. },
  32568. enumerable: true,
  32569. configurable: true
  32570. });
  32571. Object.defineProperty(Mesh.prototype, "source", {
  32572. /**
  32573. * Gets the source mesh (the one used to clone this one from)
  32574. */
  32575. get: function () {
  32576. return this._source;
  32577. },
  32578. enumerable: true,
  32579. configurable: true
  32580. });
  32581. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32582. /**
  32583. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32584. */
  32585. get: function () {
  32586. return this._unIndexed;
  32587. },
  32588. set: function (value) {
  32589. if (this._unIndexed !== value) {
  32590. this._unIndexed = value;
  32591. this._markSubMeshesAsAttributesDirty();
  32592. }
  32593. },
  32594. enumerable: true,
  32595. configurable: true
  32596. });
  32597. // Methods
  32598. /**
  32599. * Gets the class name
  32600. * @returns the string "Mesh".
  32601. */
  32602. Mesh.prototype.getClassName = function () {
  32603. return "Mesh";
  32604. };
  32605. /**
  32606. * Returns a description of this mesh
  32607. * @param fullDetails define if full details about this mesh must be used
  32608. * @returns a descriptive string representing this mesh
  32609. */
  32610. Mesh.prototype.toString = function (fullDetails) {
  32611. var ret = _super.prototype.toString.call(this, fullDetails);
  32612. ret += ", n vertices: " + this.getTotalVertices();
  32613. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32614. if (this.animations) {
  32615. for (var i = 0; i < this.animations.length; i++) {
  32616. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32617. }
  32618. }
  32619. if (fullDetails) {
  32620. if (this._geometry) {
  32621. var ib = this.getIndices();
  32622. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32623. if (vb && ib) {
  32624. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32625. }
  32626. }
  32627. else {
  32628. ret += ", flat shading: UNKNOWN";
  32629. }
  32630. }
  32631. return ret;
  32632. };
  32633. /** @hidden */
  32634. Mesh.prototype._unBindEffect = function () {
  32635. _super.prototype._unBindEffect.call(this);
  32636. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32637. var instance = _a[_i];
  32638. instance._unBindEffect();
  32639. }
  32640. };
  32641. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32642. /**
  32643. * Gets a boolean indicating if this mesh has LOD
  32644. */
  32645. get: function () {
  32646. return this._LODLevels.length > 0;
  32647. },
  32648. enumerable: true,
  32649. configurable: true
  32650. });
  32651. /**
  32652. * Gets the list of MeshLODLevel associated with the current mesh
  32653. * @returns an array of MeshLODLevel
  32654. */
  32655. Mesh.prototype.getLODLevels = function () {
  32656. return this._LODLevels;
  32657. };
  32658. Mesh.prototype._sortLODLevels = function () {
  32659. this._LODLevels.sort(function (a, b) {
  32660. if (a.distance < b.distance) {
  32661. return 1;
  32662. }
  32663. if (a.distance > b.distance) {
  32664. return -1;
  32665. }
  32666. return 0;
  32667. });
  32668. };
  32669. /**
  32670. * Add a mesh as LOD level triggered at the given distance.
  32671. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32672. * @param distance The distance from the center of the object to show this level
  32673. * @param mesh The mesh to be added as LOD level (can be null)
  32674. * @return This mesh (for chaining)
  32675. */
  32676. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32677. if (mesh && mesh._masterMesh) {
  32678. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32679. return this;
  32680. }
  32681. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32682. this._LODLevels.push(level);
  32683. if (mesh) {
  32684. mesh._masterMesh = this;
  32685. }
  32686. this._sortLODLevels();
  32687. return this;
  32688. };
  32689. /**
  32690. * Returns the LOD level mesh at the passed distance or null if not found.
  32691. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32692. * @param distance The distance from the center of the object to show this level
  32693. * @returns a Mesh or `null`
  32694. */
  32695. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32696. for (var index = 0; index < this._LODLevels.length; index++) {
  32697. var level = this._LODLevels[index];
  32698. if (level.distance === distance) {
  32699. return level.mesh;
  32700. }
  32701. }
  32702. return null;
  32703. };
  32704. /**
  32705. * Remove a mesh from the LOD array
  32706. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32707. * @param mesh defines the mesh to be removed
  32708. * @return This mesh (for chaining)
  32709. */
  32710. Mesh.prototype.removeLODLevel = function (mesh) {
  32711. for (var index = 0; index < this._LODLevels.length; index++) {
  32712. if (this._LODLevels[index].mesh === mesh) {
  32713. this._LODLevels.splice(index, 1);
  32714. if (mesh) {
  32715. mesh._masterMesh = null;
  32716. }
  32717. }
  32718. }
  32719. this._sortLODLevels();
  32720. return this;
  32721. };
  32722. /**
  32723. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32724. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32725. * @param camera defines the camera to use to compute distance
  32726. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32727. * @return This mesh (for chaining)
  32728. */
  32729. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32730. if (!this._LODLevels || this._LODLevels.length === 0) {
  32731. return this;
  32732. }
  32733. var bSphere;
  32734. if (boundingSphere) {
  32735. bSphere = boundingSphere;
  32736. }
  32737. else {
  32738. var boundingInfo = this.getBoundingInfo();
  32739. bSphere = boundingInfo.boundingSphere;
  32740. }
  32741. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32742. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32743. if (this.onLODLevelSelection) {
  32744. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32745. }
  32746. return this;
  32747. }
  32748. for (var index = 0; index < this._LODLevels.length; index++) {
  32749. var level = this._LODLevels[index];
  32750. if (level.distance < distanceToCamera) {
  32751. if (level.mesh) {
  32752. level.mesh._preActivate();
  32753. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32754. }
  32755. if (this.onLODLevelSelection) {
  32756. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32757. }
  32758. return level.mesh;
  32759. }
  32760. }
  32761. if (this.onLODLevelSelection) {
  32762. this.onLODLevelSelection(distanceToCamera, this, this);
  32763. }
  32764. return this;
  32765. };
  32766. Object.defineProperty(Mesh.prototype, "geometry", {
  32767. /**
  32768. * Gets the mesh internal Geometry object
  32769. */
  32770. get: function () {
  32771. return this._geometry;
  32772. },
  32773. enumerable: true,
  32774. configurable: true
  32775. });
  32776. /**
  32777. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32778. * @returns the total number of vertices
  32779. */
  32780. Mesh.prototype.getTotalVertices = function () {
  32781. if (this._geometry === null || this._geometry === undefined) {
  32782. return 0;
  32783. }
  32784. return this._geometry.getTotalVertices();
  32785. };
  32786. /**
  32787. * Returns the content of an associated vertex buffer
  32788. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32789. * - BABYLON.VertexBuffer.PositionKind
  32790. * - BABYLON.VertexBuffer.UVKind
  32791. * - BABYLON.VertexBuffer.UV2Kind
  32792. * - BABYLON.VertexBuffer.UV3Kind
  32793. * - BABYLON.VertexBuffer.UV4Kind
  32794. * - BABYLON.VertexBuffer.UV5Kind
  32795. * - BABYLON.VertexBuffer.UV6Kind
  32796. * - BABYLON.VertexBuffer.ColorKind
  32797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32801. * @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
  32802. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32803. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32804. */
  32805. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32806. if (!this._geometry) {
  32807. return null;
  32808. }
  32809. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32810. };
  32811. /**
  32812. * Returns the mesh VertexBuffer object from the requested `kind`
  32813. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32814. * - BABYLON.VertexBuffer.PositionKind
  32815. * - BABYLON.VertexBuffer.UVKind
  32816. * - BABYLON.VertexBuffer.UV2Kind
  32817. * - BABYLON.VertexBuffer.UV3Kind
  32818. * - BABYLON.VertexBuffer.UV4Kind
  32819. * - BABYLON.VertexBuffer.UV5Kind
  32820. * - BABYLON.VertexBuffer.UV6Kind
  32821. * - BABYLON.VertexBuffer.ColorKind
  32822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32826. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32827. */
  32828. Mesh.prototype.getVertexBuffer = function (kind) {
  32829. if (!this._geometry) {
  32830. return null;
  32831. }
  32832. return this._geometry.getVertexBuffer(kind);
  32833. };
  32834. /**
  32835. * Tests if a specific vertex buffer is associated with this mesh
  32836. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32837. * - BABYLON.VertexBuffer.PositionKind
  32838. * - BABYLON.VertexBuffer.UVKind
  32839. * - BABYLON.VertexBuffer.UV2Kind
  32840. * - BABYLON.VertexBuffer.UV3Kind
  32841. * - BABYLON.VertexBuffer.UV4Kind
  32842. * - BABYLON.VertexBuffer.UV5Kind
  32843. * - BABYLON.VertexBuffer.UV6Kind
  32844. * - BABYLON.VertexBuffer.ColorKind
  32845. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32846. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32847. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32848. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32849. * @returns a boolean
  32850. */
  32851. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32852. if (!this._geometry) {
  32853. if (this._delayInfo) {
  32854. return this._delayInfo.indexOf(kind) !== -1;
  32855. }
  32856. return false;
  32857. }
  32858. return this._geometry.isVerticesDataPresent(kind);
  32859. };
  32860. /**
  32861. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32862. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32863. * - BABYLON.VertexBuffer.PositionKind
  32864. * - BABYLON.VertexBuffer.UVKind
  32865. * - BABYLON.VertexBuffer.UV2Kind
  32866. * - BABYLON.VertexBuffer.UV3Kind
  32867. * - BABYLON.VertexBuffer.UV4Kind
  32868. * - BABYLON.VertexBuffer.UV5Kind
  32869. * - BABYLON.VertexBuffer.UV6Kind
  32870. * - BABYLON.VertexBuffer.ColorKind
  32871. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32872. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32873. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32874. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32875. * @returns a boolean
  32876. */
  32877. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32878. if (!this._geometry) {
  32879. if (this._delayInfo) {
  32880. return this._delayInfo.indexOf(kind) !== -1;
  32881. }
  32882. return false;
  32883. }
  32884. return this._geometry.isVertexBufferUpdatable(kind);
  32885. };
  32886. /**
  32887. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32888. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32889. * - BABYLON.VertexBuffer.PositionKind
  32890. * - BABYLON.VertexBuffer.UVKind
  32891. * - BABYLON.VertexBuffer.UV2Kind
  32892. * - BABYLON.VertexBuffer.UV3Kind
  32893. * - BABYLON.VertexBuffer.UV4Kind
  32894. * - BABYLON.VertexBuffer.UV5Kind
  32895. * - BABYLON.VertexBuffer.UV6Kind
  32896. * - BABYLON.VertexBuffer.ColorKind
  32897. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32898. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32899. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32900. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32901. * @returns an array of strings
  32902. */
  32903. Mesh.prototype.getVerticesDataKinds = function () {
  32904. if (!this._geometry) {
  32905. var result = new Array();
  32906. if (this._delayInfo) {
  32907. this._delayInfo.forEach(function (kind, index, array) {
  32908. result.push(kind);
  32909. });
  32910. }
  32911. return result;
  32912. }
  32913. return this._geometry.getVerticesDataKinds();
  32914. };
  32915. /**
  32916. * Returns a positive integer : the total number of indices in this mesh geometry.
  32917. * @returns the numner of indices or zero if the mesh has no geometry.
  32918. */
  32919. Mesh.prototype.getTotalIndices = function () {
  32920. if (!this._geometry) {
  32921. return 0;
  32922. }
  32923. return this._geometry.getTotalIndices();
  32924. };
  32925. /**
  32926. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32927. * @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.
  32928. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32929. * @returns the indices array or an empty array if the mesh has no geometry
  32930. */
  32931. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32932. if (!this._geometry) {
  32933. return [];
  32934. }
  32935. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32936. };
  32937. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32938. get: function () {
  32939. return this._masterMesh !== null && this._masterMesh !== undefined;
  32940. },
  32941. enumerable: true,
  32942. configurable: true
  32943. });
  32944. /**
  32945. * Determine if the current mesh is ready to be rendered
  32946. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32947. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32948. * @returns true if all associated assets are ready (material, textures, shaders)
  32949. */
  32950. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32951. if (completeCheck === void 0) { completeCheck = false; }
  32952. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32953. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32954. return false;
  32955. }
  32956. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32957. return false;
  32958. }
  32959. if (!this.subMeshes || this.subMeshes.length === 0) {
  32960. return true;
  32961. }
  32962. if (!completeCheck) {
  32963. return true;
  32964. }
  32965. var engine = this.getEngine();
  32966. var scene = this.getScene();
  32967. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32968. this.computeWorldMatrix();
  32969. var mat = this.material || scene.defaultMaterial;
  32970. if (mat) {
  32971. if (mat._storeEffectOnSubMeshes) {
  32972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32973. var subMesh = _a[_i];
  32974. var effectiveMaterial = subMesh.getMaterial();
  32975. if (effectiveMaterial) {
  32976. if (effectiveMaterial._storeEffectOnSubMeshes) {
  32977. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32978. return false;
  32979. }
  32980. }
  32981. else {
  32982. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32983. return false;
  32984. }
  32985. }
  32986. }
  32987. }
  32988. }
  32989. else {
  32990. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32991. return false;
  32992. }
  32993. }
  32994. }
  32995. // Shadows
  32996. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32997. var light = _c[_b];
  32998. var generator = light.getShadowGenerator();
  32999. if (generator) {
  33000. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  33001. var subMesh = _e[_d];
  33002. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  33003. return false;
  33004. }
  33005. }
  33006. }
  33007. }
  33008. // LOD
  33009. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  33010. var lod = _g[_f];
  33011. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  33012. return false;
  33013. }
  33014. }
  33015. return true;
  33016. };
  33017. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  33018. /**
  33019. * 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.
  33020. */
  33021. get: function () {
  33022. return this._areNormalsFrozen;
  33023. },
  33024. enumerable: true,
  33025. configurable: true
  33026. });
  33027. /**
  33028. * 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.
  33029. * @returns the current mesh
  33030. */
  33031. Mesh.prototype.freezeNormals = function () {
  33032. this._areNormalsFrozen = true;
  33033. return this;
  33034. };
  33035. /**
  33036. * 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
  33037. * @returns the current mesh
  33038. */
  33039. Mesh.prototype.unfreezeNormals = function () {
  33040. this._areNormalsFrozen = false;
  33041. return this;
  33042. };
  33043. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33044. /**
  33045. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33046. */
  33047. set: function (count) {
  33048. this._instanceDataStorage.overridenInstanceCount = count;
  33049. },
  33050. enumerable: true,
  33051. configurable: true
  33052. });
  33053. // Methods
  33054. /** @hidden */
  33055. Mesh.prototype._preActivate = function () {
  33056. var sceneRenderId = this.getScene().getRenderId();
  33057. if (this._preActivateId === sceneRenderId) {
  33058. return this;
  33059. }
  33060. this._preActivateId = sceneRenderId;
  33061. this._instanceDataStorage.visibleInstances = null;
  33062. return this;
  33063. };
  33064. /** @hidden */
  33065. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33066. if (this._instanceDataStorage.visibleInstances) {
  33067. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33068. }
  33069. return this;
  33070. };
  33071. /** @hidden */
  33072. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33073. if (!this._instanceDataStorage.visibleInstances) {
  33074. this._instanceDataStorage.visibleInstances = {};
  33075. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  33076. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  33077. }
  33078. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33079. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33080. }
  33081. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33082. return this;
  33083. };
  33084. /**
  33085. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33086. * This means the mesh underlying bounding box and sphere are recomputed.
  33087. * @returns the current mesh
  33088. */
  33089. Mesh.prototype.refreshBoundingInfo = function () {
  33090. return this._refreshBoundingInfo(false);
  33091. };
  33092. /** @hidden */
  33093. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  33094. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33095. return this;
  33096. }
  33097. var data = this._getPositionData(applySkeleton);
  33098. if (data) {
  33099. var bias = this.geometry ? this.geometry.boundingBias : null;
  33100. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  33101. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33102. }
  33103. if (this.subMeshes) {
  33104. for (var index = 0; index < this.subMeshes.length; index++) {
  33105. this.subMeshes[index].refreshBoundingInfo();
  33106. }
  33107. }
  33108. this._updateBoundingInfo();
  33109. return this;
  33110. };
  33111. Mesh.prototype._getPositionData = function (applySkeleton) {
  33112. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33113. if (data && applySkeleton && this.skeleton) {
  33114. data = BABYLON.Tools.Slice(data);
  33115. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33116. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33117. if (matricesWeightsData && matricesIndicesData) {
  33118. var needExtras = this.numBoneInfluencers > 4;
  33119. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33120. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33121. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  33122. var tempVector = BABYLON.Tmp.Vector3[0];
  33123. var finalMatrix = BABYLON.Tmp.Matrix[0];
  33124. var tempMatrix = BABYLON.Tmp.Matrix[1];
  33125. var matWeightIdx = 0;
  33126. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  33127. finalMatrix.reset();
  33128. var inf;
  33129. var weight;
  33130. for (inf = 0; inf < 4; inf++) {
  33131. weight = matricesWeightsData[matWeightIdx + inf];
  33132. if (weight > 0) {
  33133. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33134. finalMatrix.addToSelf(tempMatrix);
  33135. }
  33136. }
  33137. if (needExtras) {
  33138. for (inf = 0; inf < 4; inf++) {
  33139. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33140. if (weight > 0) {
  33141. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33142. finalMatrix.addToSelf(tempMatrix);
  33143. }
  33144. }
  33145. }
  33146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  33147. tempVector.toArray(data, index);
  33148. }
  33149. }
  33150. }
  33151. return data;
  33152. };
  33153. /** @hidden */
  33154. Mesh.prototype._createGlobalSubMesh = function (force) {
  33155. var totalVertices = this.getTotalVertices();
  33156. if (!totalVertices || !this.getIndices()) {
  33157. return null;
  33158. }
  33159. // Check if we need to recreate the submeshes
  33160. if (this.subMeshes && this.subMeshes.length > 0) {
  33161. var ib = this.getIndices();
  33162. if (!ib) {
  33163. return null;
  33164. }
  33165. var totalIndices = ib.length;
  33166. var needToRecreate = false;
  33167. if (force) {
  33168. needToRecreate = true;
  33169. }
  33170. else {
  33171. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33172. var submesh = _a[_i];
  33173. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33174. needToRecreate = true;
  33175. break;
  33176. }
  33177. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33178. needToRecreate = true;
  33179. break;
  33180. }
  33181. }
  33182. }
  33183. if (!needToRecreate) {
  33184. return this.subMeshes[0];
  33185. }
  33186. }
  33187. this.releaseSubMeshes();
  33188. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33189. };
  33190. /**
  33191. * This function will subdivide the mesh into multiple submeshes
  33192. * @param count defines the expected number of submeshes
  33193. */
  33194. Mesh.prototype.subdivide = function (count) {
  33195. if (count < 1) {
  33196. return;
  33197. }
  33198. var totalIndices = this.getTotalIndices();
  33199. var subdivisionSize = (totalIndices / count) | 0;
  33200. var offset = 0;
  33201. // Ensure that subdivisionSize is a multiple of 3
  33202. while (subdivisionSize % 3 !== 0) {
  33203. subdivisionSize++;
  33204. }
  33205. this.releaseSubMeshes();
  33206. for (var index = 0; index < count; index++) {
  33207. if (offset >= totalIndices) {
  33208. break;
  33209. }
  33210. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33211. offset += subdivisionSize;
  33212. }
  33213. this.synchronizeInstances();
  33214. };
  33215. /**
  33216. * Copy a FloatArray into a specific associated vertex buffer
  33217. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33218. * - BABYLON.VertexBuffer.PositionKind
  33219. * - BABYLON.VertexBuffer.UVKind
  33220. * - BABYLON.VertexBuffer.UV2Kind
  33221. * - BABYLON.VertexBuffer.UV3Kind
  33222. * - BABYLON.VertexBuffer.UV4Kind
  33223. * - BABYLON.VertexBuffer.UV5Kind
  33224. * - BABYLON.VertexBuffer.UV6Kind
  33225. * - BABYLON.VertexBuffer.ColorKind
  33226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33230. * @param data defines the data source
  33231. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33232. * @param stride defines the data stride size (can be null)
  33233. * @returns the current mesh
  33234. */
  33235. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33236. if (updatable === void 0) { updatable = false; }
  33237. if (!this._geometry) {
  33238. var vertexData = new BABYLON.VertexData();
  33239. vertexData.set(data, kind);
  33240. var scene = this.getScene();
  33241. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33242. }
  33243. else {
  33244. this._geometry.setVerticesData(kind, data, updatable, stride);
  33245. }
  33246. return this;
  33247. };
  33248. /**
  33249. * Flags an associated vertex buffer as updatable
  33250. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33251. * - BABYLON.VertexBuffer.PositionKind
  33252. * - BABYLON.VertexBuffer.UVKind
  33253. * - BABYLON.VertexBuffer.UV2Kind
  33254. * - BABYLON.VertexBuffer.UV3Kind
  33255. * - BABYLON.VertexBuffer.UV4Kind
  33256. * - BABYLON.VertexBuffer.UV5Kind
  33257. * - BABYLON.VertexBuffer.UV6Kind
  33258. * - BABYLON.VertexBuffer.ColorKind
  33259. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33260. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33261. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33262. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33263. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33264. */
  33265. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33266. if (updatable === void 0) { updatable = true; }
  33267. var vb = this.getVertexBuffer(kind);
  33268. if (!vb || vb.isUpdatable() === updatable) {
  33269. return;
  33270. }
  33271. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33272. };
  33273. /**
  33274. * Sets the mesh global Vertex Buffer
  33275. * @param buffer defines the buffer to use
  33276. * @returns the current mesh
  33277. */
  33278. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33279. if (!this._geometry) {
  33280. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33281. }
  33282. this._geometry.setVerticesBuffer(buffer);
  33283. return this;
  33284. };
  33285. /**
  33286. * Update a specific associated vertex buffer
  33287. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33288. * - BABYLON.VertexBuffer.PositionKind
  33289. * - BABYLON.VertexBuffer.UVKind
  33290. * - BABYLON.VertexBuffer.UV2Kind
  33291. * - BABYLON.VertexBuffer.UV3Kind
  33292. * - BABYLON.VertexBuffer.UV4Kind
  33293. * - BABYLON.VertexBuffer.UV5Kind
  33294. * - BABYLON.VertexBuffer.UV6Kind
  33295. * - BABYLON.VertexBuffer.ColorKind
  33296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33300. * @param data defines the data source
  33301. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33302. * @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)
  33303. * @returns the current mesh
  33304. */
  33305. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33306. if (!this._geometry) {
  33307. return this;
  33308. }
  33309. if (!makeItUnique) {
  33310. this._geometry.updateVerticesData(kind, data, updateExtends);
  33311. }
  33312. else {
  33313. this.makeGeometryUnique();
  33314. this.updateVerticesData(kind, data, updateExtends, false);
  33315. }
  33316. return this;
  33317. };
  33318. /**
  33319. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33320. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33321. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33322. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33323. * @returns the current mesh
  33324. */
  33325. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33326. if (computeNormals === void 0) { computeNormals = true; }
  33327. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33328. if (!positions) {
  33329. return this;
  33330. }
  33331. positionFunction(positions);
  33332. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33333. if (computeNormals) {
  33334. var indices = this.getIndices();
  33335. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33336. if (!normals) {
  33337. return this;
  33338. }
  33339. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33340. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33341. }
  33342. return this;
  33343. };
  33344. /**
  33345. * Creates a un-shared specific occurence of the geometry for the mesh.
  33346. * @returns the current mesh
  33347. */
  33348. Mesh.prototype.makeGeometryUnique = function () {
  33349. if (!this._geometry) {
  33350. return this;
  33351. }
  33352. var oldGeometry = this._geometry;
  33353. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33354. oldGeometry.releaseForMesh(this, true);
  33355. geometry.applyToMesh(this);
  33356. return this;
  33357. };
  33358. /**
  33359. * Set the index buffer of this mesh
  33360. * @param indices defines the source data
  33361. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33362. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33363. * @returns the current mesh
  33364. */
  33365. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33366. if (totalVertices === void 0) { totalVertices = null; }
  33367. if (updatable === void 0) { updatable = false; }
  33368. if (!this._geometry) {
  33369. var vertexData = new BABYLON.VertexData();
  33370. vertexData.indices = indices;
  33371. var scene = this.getScene();
  33372. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33373. }
  33374. else {
  33375. this._geometry.setIndices(indices, totalVertices, updatable);
  33376. }
  33377. return this;
  33378. };
  33379. /**
  33380. * Update the current index buffer
  33381. * @param indices defines the source data
  33382. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33383. * @returns the current mesh
  33384. */
  33385. Mesh.prototype.updateIndices = function (indices, offset) {
  33386. if (!this._geometry) {
  33387. return this;
  33388. }
  33389. this._geometry.updateIndices(indices, offset);
  33390. return this;
  33391. };
  33392. /**
  33393. * Invert the geometry to move from a right handed system to a left handed one.
  33394. * @returns the current mesh
  33395. */
  33396. Mesh.prototype.toLeftHanded = function () {
  33397. if (!this._geometry) {
  33398. return this;
  33399. }
  33400. this._geometry.toLeftHanded();
  33401. return this;
  33402. };
  33403. /** @hidden */
  33404. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33405. if (!this._geometry) {
  33406. return this;
  33407. }
  33408. var engine = this.getScene().getEngine();
  33409. // Wireframe
  33410. var indexToBind;
  33411. if (this._unIndexed) {
  33412. indexToBind = null;
  33413. }
  33414. else {
  33415. switch (fillMode) {
  33416. case BABYLON.Material.PointFillMode:
  33417. indexToBind = null;
  33418. break;
  33419. case BABYLON.Material.WireFrameFillMode:
  33420. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33421. break;
  33422. default:
  33423. case BABYLON.Material.TriangleFillMode:
  33424. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33425. break;
  33426. }
  33427. }
  33428. // VBOs
  33429. this._geometry._bind(effect, indexToBind);
  33430. return this;
  33431. };
  33432. /** @hidden */
  33433. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33434. if (alternate === void 0) { alternate = false; }
  33435. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33436. return this;
  33437. }
  33438. if (this._onBeforeDrawObservable) {
  33439. this._onBeforeDrawObservable.notifyObservers(this);
  33440. }
  33441. var scene = this.getScene();
  33442. var engine = scene.getEngine();
  33443. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33444. // or triangles as points
  33445. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33446. }
  33447. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33448. // Triangles as wireframe
  33449. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33450. }
  33451. else {
  33452. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33453. }
  33454. if (scene._isAlternateRenderingEnabled && !alternate) {
  33455. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33456. if (!effect || !scene.activeCamera) {
  33457. return this;
  33458. }
  33459. scene._switchToAlternateCameraConfiguration(true);
  33460. this._effectiveMaterial.bindView(effect);
  33461. this._effectiveMaterial.bindViewProjection(effect);
  33462. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33463. this._draw(subMesh, fillMode, instancesCount, true);
  33464. engine.setViewport(scene.activeCamera.viewport);
  33465. scene._switchToAlternateCameraConfiguration(false);
  33466. this._effectiveMaterial.bindView(effect);
  33467. this._effectiveMaterial.bindViewProjection(effect);
  33468. }
  33469. return this;
  33470. };
  33471. /**
  33472. * Registers for this mesh a javascript function called just before the rendering process
  33473. * @param func defines the function to call before rendering this mesh
  33474. * @returns the current mesh
  33475. */
  33476. Mesh.prototype.registerBeforeRender = function (func) {
  33477. this.onBeforeRenderObservable.add(func);
  33478. return this;
  33479. };
  33480. /**
  33481. * Disposes a previously registered javascript function called before the rendering
  33482. * @param func defines the function to remove
  33483. * @returns the current mesh
  33484. */
  33485. Mesh.prototype.unregisterBeforeRender = function (func) {
  33486. this.onBeforeRenderObservable.removeCallback(func);
  33487. return this;
  33488. };
  33489. /**
  33490. * Registers for this mesh a javascript function called just after the rendering is complete
  33491. * @param func defines the function to call after rendering this mesh
  33492. * @returns the current mesh
  33493. */
  33494. Mesh.prototype.registerAfterRender = function (func) {
  33495. this.onAfterRenderObservable.add(func);
  33496. return this;
  33497. };
  33498. /**
  33499. * Disposes a previously registered javascript function called after the rendering.
  33500. * @param func defines the function to remove
  33501. * @returns the current mesh
  33502. */
  33503. Mesh.prototype.unregisterAfterRender = function (func) {
  33504. this.onAfterRenderObservable.removeCallback(func);
  33505. return this;
  33506. };
  33507. /** @hidden */
  33508. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33509. var scene = this.getScene();
  33510. var batchCache = this._instanceDataStorage.batchCache;
  33511. batchCache.mustReturn = false;
  33512. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33513. batchCache.visibleInstances[subMeshId] = null;
  33514. if (this._instanceDataStorage.visibleInstances) {
  33515. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33516. var currentRenderId = scene.getRenderId();
  33517. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33518. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33519. var selfRenderId = this._renderId;
  33520. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33521. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33522. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33523. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33524. }
  33525. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33526. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33527. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33528. batchCache.mustReturn = true;
  33529. return batchCache;
  33530. }
  33531. if (currentRenderId !== selfRenderId) {
  33532. batchCache.renderSelf[subMeshId] = false;
  33533. }
  33534. }
  33535. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33536. }
  33537. return batchCache;
  33538. };
  33539. /** @hidden */
  33540. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33541. var visibleInstances = batch.visibleInstances[subMesh._id];
  33542. if (!visibleInstances) {
  33543. return this;
  33544. }
  33545. var matricesCount = visibleInstances.length + 1;
  33546. var bufferSize = matricesCount * 16 * 4;
  33547. var instanceStorage = this._instanceDataStorage;
  33548. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33549. var instancesBuffer = instanceStorage.instancesBuffer;
  33550. while (instanceStorage.instancesBufferSize < bufferSize) {
  33551. instanceStorage.instancesBufferSize *= 2;
  33552. }
  33553. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33554. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33555. }
  33556. var offset = 0;
  33557. var instancesCount = 0;
  33558. var world = this.getWorldMatrix();
  33559. if (batch.renderSelf[subMesh._id]) {
  33560. world.copyToArray(instanceStorage.instancesData, offset);
  33561. offset += 16;
  33562. instancesCount++;
  33563. }
  33564. if (visibleInstances) {
  33565. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33566. var instance = visibleInstances[instanceIndex];
  33567. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33568. offset += 16;
  33569. instancesCount++;
  33570. }
  33571. }
  33572. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33573. if (instancesBuffer) {
  33574. instancesBuffer.dispose();
  33575. }
  33576. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33577. instanceStorage.instancesBuffer = instancesBuffer;
  33578. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33579. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33580. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33581. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33582. }
  33583. else {
  33584. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33585. }
  33586. this._bind(subMesh, effect, fillMode);
  33587. this._draw(subMesh, fillMode, instancesCount);
  33588. engine.unbindInstanceAttributes();
  33589. return this;
  33590. };
  33591. /** @hidden */
  33592. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33593. var scene = this.getScene();
  33594. var engine = scene.getEngine();
  33595. if (hardwareInstancedRendering) {
  33596. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33597. }
  33598. else {
  33599. if (batch.renderSelf[subMesh._id]) {
  33600. // Draw
  33601. if (onBeforeDraw) {
  33602. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33603. }
  33604. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33605. }
  33606. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33607. if (visibleInstancesForSubMesh) {
  33608. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33609. var instance = visibleInstancesForSubMesh[instanceIndex];
  33610. // World
  33611. var world = instance.getWorldMatrix();
  33612. if (onBeforeDraw) {
  33613. onBeforeDraw(true, world, effectiveMaterial);
  33614. }
  33615. // Draw
  33616. this._draw(subMesh, fillMode);
  33617. }
  33618. }
  33619. }
  33620. return this;
  33621. };
  33622. /**
  33623. * 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
  33624. * @param subMesh defines the subMesh to render
  33625. * @param enableAlphaMode defines if alpha mode can be changed
  33626. * @returns the current mesh
  33627. */
  33628. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33629. if (this._checkOcclusionQuery()) {
  33630. return this;
  33631. }
  33632. var scene = this.getScene();
  33633. // Managing instances
  33634. var batch = this._getInstancesRenderList(subMesh._id);
  33635. if (batch.mustReturn) {
  33636. return this;
  33637. }
  33638. // Checking geometry state
  33639. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33640. return this;
  33641. }
  33642. if (this._onBeforeRenderObservable) {
  33643. this._onBeforeRenderObservable.notifyObservers(this);
  33644. }
  33645. var engine = scene.getEngine();
  33646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33647. // Material
  33648. var material = subMesh.getMaterial();
  33649. if (!material) {
  33650. return this;
  33651. }
  33652. this._effectiveMaterial = material;
  33653. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33654. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33655. return this;
  33656. }
  33657. }
  33658. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33659. return this;
  33660. }
  33661. // Alpha mode
  33662. if (enableAlphaMode) {
  33663. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33664. }
  33665. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33666. var step = _a[_i];
  33667. step.action(this, subMesh, batch);
  33668. }
  33669. var effect;
  33670. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33671. effect = subMesh.effect;
  33672. }
  33673. else {
  33674. effect = this._effectiveMaterial.getEffect();
  33675. }
  33676. if (!effect) {
  33677. return this;
  33678. }
  33679. var sideOrientation = this.overrideMaterialSideOrientation;
  33680. if (sideOrientation == null) {
  33681. sideOrientation = this._effectiveMaterial.sideOrientation;
  33682. if (this._getWorldMatrixDeterminant() < 0) {
  33683. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33684. }
  33685. }
  33686. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33687. if (this._effectiveMaterial.forceDepthWrite) {
  33688. engine.setDepthWrite(true);
  33689. }
  33690. // Bind
  33691. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33692. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33693. this._bind(subMesh, effect, fillMode);
  33694. }
  33695. var world = this.getWorldMatrix();
  33696. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33697. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33698. }
  33699. else {
  33700. this._effectiveMaterial.bind(world, this);
  33701. }
  33702. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33703. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33704. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33705. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33706. }
  33707. // Draw
  33708. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33709. // Unbind
  33710. this._effectiveMaterial.unbind();
  33711. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33712. var step = _c[_b];
  33713. step.action(this, subMesh, batch);
  33714. }
  33715. if (this._onAfterRenderObservable) {
  33716. this._onAfterRenderObservable.notifyObservers(this);
  33717. }
  33718. return this;
  33719. };
  33720. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33721. if (isInstance && effectiveMaterial) {
  33722. effectiveMaterial.bindOnlyWorldMatrix(world);
  33723. }
  33724. };
  33725. /**
  33726. * Renormalize the mesh and patch it up if there are no weights
  33727. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33728. * However in the case of zero weights then we set just a single influence to 1.
  33729. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33730. */
  33731. Mesh.prototype.cleanMatrixWeights = function () {
  33732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33733. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33734. this.normalizeSkinWeightsAndExtra();
  33735. }
  33736. else {
  33737. this.normalizeSkinFourWeights();
  33738. }
  33739. }
  33740. };
  33741. // faster 4 weight version.
  33742. Mesh.prototype.normalizeSkinFourWeights = function () {
  33743. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33744. var numWeights = matricesWeights.length;
  33745. for (var a = 0; a < numWeights; a += 4) {
  33746. // accumulate weights
  33747. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33748. // check for invalid weight and just set it to 1.
  33749. if (t === 0) {
  33750. matricesWeights[a] = 1;
  33751. }
  33752. else {
  33753. // renormalize so everything adds to 1 use reciprical
  33754. var recip = 1 / t;
  33755. matricesWeights[a] *= recip;
  33756. matricesWeights[a + 1] *= recip;
  33757. matricesWeights[a + 2] *= recip;
  33758. matricesWeights[a + 3] *= recip;
  33759. }
  33760. }
  33761. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33762. };
  33763. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33764. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33765. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33766. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33767. var numWeights = matricesWeights.length;
  33768. for (var a = 0; a < numWeights; a += 4) {
  33769. // accumulate weights
  33770. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33771. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33772. // check for invalid weight and just set it to 1.
  33773. if (t === 0) {
  33774. matricesWeights[a] = 1;
  33775. }
  33776. else {
  33777. // renormalize so everything adds to 1 use reciprical
  33778. var recip = 1 / t;
  33779. matricesWeights[a] *= recip;
  33780. matricesWeights[a + 1] *= recip;
  33781. matricesWeights[a + 2] *= recip;
  33782. matricesWeights[a + 3] *= recip;
  33783. // same goes for extras
  33784. matricesWeightsExtra[a] *= recip;
  33785. matricesWeightsExtra[a + 1] *= recip;
  33786. matricesWeightsExtra[a + 2] *= recip;
  33787. matricesWeightsExtra[a + 3] *= recip;
  33788. }
  33789. }
  33790. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33791. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33792. };
  33793. /**
  33794. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33795. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33796. * the user know there was an issue with importing the mesh
  33797. * @returns a validation object with skinned, valid and report string
  33798. */
  33799. Mesh.prototype.validateSkinning = function () {
  33800. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33801. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33802. if (matricesWeights === null || this.skeleton == null) {
  33803. return { skinned: false, valid: true, report: "not skinned" };
  33804. }
  33805. var numWeights = matricesWeights.length;
  33806. var numberNotSorted = 0;
  33807. var missingWeights = 0;
  33808. var maxUsedWeights = 0;
  33809. var numberNotNormalized = 0;
  33810. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33811. var usedWeightCounts = new Array();
  33812. for (var a = 0; a <= numInfluences; a++) {
  33813. usedWeightCounts[a] = 0;
  33814. }
  33815. var toleranceEpsilon = 0.001;
  33816. for (var a = 0; a < numWeights; a += 4) {
  33817. var lastWeight = matricesWeights[a];
  33818. var t = lastWeight;
  33819. var usedWeights = t === 0 ? 0 : 1;
  33820. for (var b = 1; b < numInfluences; b++) {
  33821. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33822. if (d > lastWeight) {
  33823. numberNotSorted++;
  33824. }
  33825. if (d !== 0) {
  33826. usedWeights++;
  33827. }
  33828. t += d;
  33829. lastWeight = d;
  33830. }
  33831. // count the buffer weights usage
  33832. usedWeightCounts[usedWeights]++;
  33833. // max influences
  33834. if (usedWeights > maxUsedWeights) {
  33835. maxUsedWeights = usedWeights;
  33836. }
  33837. // check for invalid weight and just set it to 1.
  33838. if (t === 0) {
  33839. missingWeights++;
  33840. }
  33841. else {
  33842. // renormalize so everything adds to 1 use reciprical
  33843. var recip = 1 / t;
  33844. var tolerance = 0;
  33845. for (b = 0; b < numInfluences; b++) {
  33846. if (b < 4) {
  33847. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33848. }
  33849. else {
  33850. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33851. }
  33852. }
  33853. // arbitary epsilon value for dicdating not normalized
  33854. if (tolerance > toleranceEpsilon) {
  33855. numberNotNormalized++;
  33856. }
  33857. }
  33858. }
  33859. // validate bone indices are in range of the skeleton
  33860. var numBones = this.skeleton.bones.length;
  33861. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33862. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33863. var numBadBoneIndices = 0;
  33864. for (var a = 0; a < numWeights; a++) {
  33865. for (var b = 0; b < numInfluences; b++) {
  33866. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33867. if (index >= numBones || index < 0) {
  33868. numBadBoneIndices++;
  33869. }
  33870. }
  33871. }
  33872. // log mesh stats
  33873. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33874. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33875. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33876. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33877. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33878. };
  33879. /** @hidden */
  33880. Mesh.prototype._checkDelayState = function () {
  33881. var scene = this.getScene();
  33882. if (this._geometry) {
  33883. this._geometry.load(scene);
  33884. }
  33885. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33886. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33887. this._queueLoad(scene);
  33888. }
  33889. return this;
  33890. };
  33891. Mesh.prototype._queueLoad = function (scene) {
  33892. var _this = this;
  33893. scene._addPendingData(this);
  33894. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33895. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33896. if (data instanceof ArrayBuffer) {
  33897. _this._delayLoadingFunction(data, _this);
  33898. }
  33899. else {
  33900. _this._delayLoadingFunction(JSON.parse(data), _this);
  33901. }
  33902. _this.instances.forEach(function (instance) {
  33903. instance._syncSubMeshes();
  33904. });
  33905. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33906. scene._removePendingData(_this);
  33907. }, function () { }, scene.offlineProvider, getBinaryData);
  33908. return this;
  33909. };
  33910. /**
  33911. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33912. * A mesh is in the frustum if its bounding box intersects the frustum
  33913. * @param frustumPlanes defines the frustum to test
  33914. * @returns true if the mesh is in the frustum planes
  33915. */
  33916. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33917. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33918. return false;
  33919. }
  33920. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33921. return false;
  33922. }
  33923. this._checkDelayState();
  33924. return true;
  33925. };
  33926. /**
  33927. * Sets the mesh material by the material or multiMaterial `id` property
  33928. * @param id is a string identifying the material or the multiMaterial
  33929. * @returns the current mesh
  33930. */
  33931. Mesh.prototype.setMaterialByID = function (id) {
  33932. var materials = this.getScene().materials;
  33933. var index;
  33934. for (index = materials.length - 1; index > -1; index--) {
  33935. if (materials[index].id === id) {
  33936. this.material = materials[index];
  33937. return this;
  33938. }
  33939. }
  33940. // Multi
  33941. var multiMaterials = this.getScene().multiMaterials;
  33942. for (index = multiMaterials.length - 1; index > -1; index--) {
  33943. if (multiMaterials[index].id === id) {
  33944. this.material = multiMaterials[index];
  33945. return this;
  33946. }
  33947. }
  33948. return this;
  33949. };
  33950. /**
  33951. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33952. * @returns an array of IAnimatable
  33953. */
  33954. Mesh.prototype.getAnimatables = function () {
  33955. var results = new Array();
  33956. if (this.material) {
  33957. results.push(this.material);
  33958. }
  33959. if (this.skeleton) {
  33960. results.push(this.skeleton);
  33961. }
  33962. return results;
  33963. };
  33964. /**
  33965. * Modifies the mesh geometry according to the passed transformation matrix.
  33966. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33967. * The mesh normals are modified using the same transformation.
  33968. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33969. * @param transform defines the transform matrix to use
  33970. * @see http://doc.babylonjs.com/resources/baking_transformations
  33971. * @returns the current mesh
  33972. */
  33973. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33974. // Position
  33975. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33976. return this;
  33977. }
  33978. var submeshes = this.subMeshes.splice(0);
  33979. this._resetPointsArrayCache();
  33980. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33981. var temp = new Array();
  33982. var index;
  33983. for (index = 0; index < data.length; index += 3) {
  33984. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33985. }
  33986. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33987. // Normals
  33988. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33989. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33990. temp = [];
  33991. for (index = 0; index < data.length; index += 3) {
  33992. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33993. }
  33994. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33995. }
  33996. // flip faces?
  33997. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33998. this.flipFaces();
  33999. }
  34000. // Restore submeshes
  34001. this.releaseSubMeshes();
  34002. this.subMeshes = submeshes;
  34003. return this;
  34004. };
  34005. /**
  34006. * Modifies the mesh geometry according to its own current World Matrix.
  34007. * The mesh World Matrix is then reset.
  34008. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  34009. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34010. * @see http://doc.babylonjs.com/resources/baking_transformations
  34011. * @returns the current mesh
  34012. */
  34013. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  34014. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  34015. this.scaling.copyFromFloats(1, 1, 1);
  34016. this.position.copyFromFloats(0, 0, 0);
  34017. this.rotation.copyFromFloats(0, 0, 0);
  34018. //only if quaternion is already set
  34019. if (this.rotationQuaternion) {
  34020. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  34021. }
  34022. this._worldMatrix = BABYLON.Matrix.Identity();
  34023. return this;
  34024. };
  34025. Object.defineProperty(Mesh.prototype, "_positions", {
  34026. // Cache
  34027. /** @hidden */
  34028. get: function () {
  34029. if (this._geometry) {
  34030. return this._geometry._positions;
  34031. }
  34032. return null;
  34033. },
  34034. enumerable: true,
  34035. configurable: true
  34036. });
  34037. /** @hidden */
  34038. Mesh.prototype._resetPointsArrayCache = function () {
  34039. if (this._geometry) {
  34040. this._geometry._resetPointsArrayCache();
  34041. }
  34042. return this;
  34043. };
  34044. /** @hidden */
  34045. Mesh.prototype._generatePointsArray = function () {
  34046. if (this._geometry) {
  34047. return this._geometry._generatePointsArray();
  34048. }
  34049. return false;
  34050. };
  34051. /**
  34052. * Returns a new Mesh object generated from the current mesh properties.
  34053. * This method must not get confused with createInstance()
  34054. * @param name is a string, the name given to the new mesh
  34055. * @param newParent can be any Node object (default `null`)
  34056. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34057. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34058. * @returns a new mesh
  34059. */
  34060. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34061. if (name === void 0) { name = ""; }
  34062. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34063. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34064. };
  34065. /**
  34066. * Releases resources associated with this mesh.
  34067. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34068. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34069. */
  34070. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34071. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34072. this.morphTargetManager = null;
  34073. if (this._geometry) {
  34074. this._geometry.releaseForMesh(this, true);
  34075. }
  34076. if (this._onBeforeDrawObservable) {
  34077. this._onBeforeDrawObservable.clear();
  34078. }
  34079. if (this._onBeforeRenderObservable) {
  34080. this._onBeforeRenderObservable.clear();
  34081. }
  34082. if (this._onAfterRenderObservable) {
  34083. this._onAfterRenderObservable.clear();
  34084. }
  34085. // Sources
  34086. if (this._scene.useClonedMeshhMap) {
  34087. if (this.meshMap) {
  34088. for (var uniqueId in this.meshMap) {
  34089. var mesh = this.meshMap[uniqueId];
  34090. if (mesh) {
  34091. mesh._source = null;
  34092. this.meshMap[uniqueId] = undefined;
  34093. }
  34094. }
  34095. }
  34096. if (this._source && this._source.meshMap) {
  34097. this._source.meshMap[this.uniqueId] = undefined;
  34098. }
  34099. }
  34100. else {
  34101. var meshes = this.getScene().meshes;
  34102. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34103. var abstractMesh = meshes_1[_i];
  34104. var mesh = abstractMesh;
  34105. if (mesh._source && mesh._source === this) {
  34106. mesh._source = null;
  34107. }
  34108. }
  34109. }
  34110. this._source = null;
  34111. // Instances
  34112. if (this._instanceDataStorage.instancesBuffer) {
  34113. this._instanceDataStorage.instancesBuffer.dispose();
  34114. this._instanceDataStorage.instancesBuffer = null;
  34115. }
  34116. while (this.instances.length) {
  34117. this.instances[0].dispose();
  34118. }
  34119. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34120. };
  34121. /**
  34122. * Modifies the mesh geometry according to a displacement map.
  34123. * 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.
  34124. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34125. * @param url is a string, the URL from the image file is to be downloaded.
  34126. * @param minHeight is the lower limit of the displacement.
  34127. * @param maxHeight is the upper limit of the displacement.
  34128. * @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.
  34129. * @param uvOffset is an optional vector2 used to offset UV.
  34130. * @param uvScale is an optional vector2 used to scale UV.
  34131. * @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.
  34132. * @returns the Mesh.
  34133. */
  34134. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34135. var _this = this;
  34136. if (forceUpdate === void 0) { forceUpdate = false; }
  34137. var scene = this.getScene();
  34138. var onload = function (img) {
  34139. // Getting height map data
  34140. var canvas = document.createElement("canvas");
  34141. var context = canvas.getContext("2d");
  34142. var heightMapWidth = img.width;
  34143. var heightMapHeight = img.height;
  34144. canvas.width = heightMapWidth;
  34145. canvas.height = heightMapHeight;
  34146. context.drawImage(img, 0, 0);
  34147. // Create VertexData from map data
  34148. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34149. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34150. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34151. //execute success callback, if set
  34152. if (onSuccess) {
  34153. onSuccess(_this);
  34154. }
  34155. };
  34156. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34157. return this;
  34158. };
  34159. /**
  34160. * Modifies the mesh geometry according to a displacementMap buffer.
  34161. * 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.
  34162. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34163. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34164. * @param heightMapWidth is the width of the buffer image.
  34165. * @param heightMapHeight is the height of the buffer image.
  34166. * @param minHeight is the lower limit of the displacement.
  34167. * @param maxHeight is the upper limit of the displacement.
  34168. * @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.
  34169. * @param uvOffset is an optional vector2 used to offset UV.
  34170. * @param uvScale is an optional vector2 used to scale UV.
  34171. * @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.
  34172. * @returns the Mesh.
  34173. */
  34174. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34175. if (forceUpdate === void 0) { forceUpdate = false; }
  34176. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34177. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34178. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34179. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34180. return this;
  34181. }
  34182. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34183. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34184. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34185. var position = BABYLON.Vector3.Zero();
  34186. var normal = BABYLON.Vector3.Zero();
  34187. var uv = BABYLON.Vector2.Zero();
  34188. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34189. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34190. for (var index = 0; index < positions.length; index += 3) {
  34191. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34192. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34193. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34194. // Compute height
  34195. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34196. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34197. var pos = (u + v * heightMapWidth) * 4;
  34198. var r = buffer[pos] / 255.0;
  34199. var g = buffer[pos + 1] / 255.0;
  34200. var b = buffer[pos + 2] / 255.0;
  34201. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34202. normal.normalize();
  34203. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34204. position = position.add(normal);
  34205. position.toArray(positions, index);
  34206. }
  34207. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34208. if (forceUpdate) {
  34209. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34210. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34211. }
  34212. else {
  34213. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34214. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34215. }
  34216. return this;
  34217. };
  34218. /**
  34219. * Modify the mesh to get a flat shading rendering.
  34220. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34221. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34222. * @returns current mesh
  34223. */
  34224. Mesh.prototype.convertToFlatShadedMesh = function () {
  34225. var kinds = this.getVerticesDataKinds();
  34226. var vbs = {};
  34227. var data = {};
  34228. var newdata = {};
  34229. var updatableNormals = false;
  34230. var kindIndex;
  34231. var kind;
  34232. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34233. kind = kinds[kindIndex];
  34234. var vertexBuffer = this.getVertexBuffer(kind);
  34235. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34236. updatableNormals = vertexBuffer.isUpdatable();
  34237. kinds.splice(kindIndex, 1);
  34238. kindIndex--;
  34239. continue;
  34240. }
  34241. vbs[kind] = vertexBuffer;
  34242. data[kind] = vbs[kind].getData();
  34243. newdata[kind] = [];
  34244. }
  34245. // Save previous submeshes
  34246. var previousSubmeshes = this.subMeshes.slice(0);
  34247. var indices = this.getIndices();
  34248. var totalIndices = this.getTotalIndices();
  34249. // Generating unique vertices per face
  34250. var index;
  34251. for (index = 0; index < totalIndices; index++) {
  34252. var vertexIndex = indices[index];
  34253. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34254. kind = kinds[kindIndex];
  34255. var stride = vbs[kind].getStrideSize();
  34256. for (var offset = 0; offset < stride; offset++) {
  34257. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34258. }
  34259. }
  34260. }
  34261. // Updating faces & normal
  34262. var normals = [];
  34263. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34264. for (index = 0; index < totalIndices; index += 3) {
  34265. indices[index] = index;
  34266. indices[index + 1] = index + 1;
  34267. indices[index + 2] = index + 2;
  34268. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34269. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34270. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34271. var p1p2 = p1.subtract(p2);
  34272. var p3p2 = p3.subtract(p2);
  34273. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34274. // Store same normals for every vertex
  34275. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34276. normals.push(normal.x);
  34277. normals.push(normal.y);
  34278. normals.push(normal.z);
  34279. }
  34280. }
  34281. this.setIndices(indices);
  34282. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34283. // Updating vertex buffers
  34284. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34285. kind = kinds[kindIndex];
  34286. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34287. }
  34288. // Updating submeshes
  34289. this.releaseSubMeshes();
  34290. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34291. var previousOne = previousSubmeshes[submeshIndex];
  34292. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34293. }
  34294. this.synchronizeInstances();
  34295. return this;
  34296. };
  34297. /**
  34298. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34299. * In other words, more vertices, no more indices and a single bigger VBO.
  34300. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34301. * @returns current mesh
  34302. */
  34303. Mesh.prototype.convertToUnIndexedMesh = function () {
  34304. var kinds = this.getVerticesDataKinds();
  34305. var vbs = {};
  34306. var data = {};
  34307. var newdata = {};
  34308. var kindIndex;
  34309. var kind;
  34310. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34311. kind = kinds[kindIndex];
  34312. var vertexBuffer = this.getVertexBuffer(kind);
  34313. vbs[kind] = vertexBuffer;
  34314. data[kind] = vbs[kind].getData();
  34315. newdata[kind] = [];
  34316. }
  34317. // Save previous submeshes
  34318. var previousSubmeshes = this.subMeshes.slice(0);
  34319. var indices = this.getIndices();
  34320. var totalIndices = this.getTotalIndices();
  34321. // Generating unique vertices per face
  34322. var index;
  34323. for (index = 0; index < totalIndices; index++) {
  34324. var vertexIndex = indices[index];
  34325. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34326. kind = kinds[kindIndex];
  34327. var stride = vbs[kind].getStrideSize();
  34328. for (var offset = 0; offset < stride; offset++) {
  34329. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34330. }
  34331. }
  34332. }
  34333. // Updating indices
  34334. for (index = 0; index < totalIndices; index += 3) {
  34335. indices[index] = index;
  34336. indices[index + 1] = index + 1;
  34337. indices[index + 2] = index + 2;
  34338. }
  34339. this.setIndices(indices);
  34340. // Updating vertex buffers
  34341. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34342. kind = kinds[kindIndex];
  34343. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34344. }
  34345. // Updating submeshes
  34346. this.releaseSubMeshes();
  34347. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34348. var previousOne = previousSubmeshes[submeshIndex];
  34349. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34350. }
  34351. this._unIndexed = true;
  34352. this.synchronizeInstances();
  34353. return this;
  34354. };
  34355. /**
  34356. * Inverses facet orientations.
  34357. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34358. * @param flipNormals will also inverts the normals
  34359. * @returns current mesh
  34360. */
  34361. Mesh.prototype.flipFaces = function (flipNormals) {
  34362. if (flipNormals === void 0) { flipNormals = false; }
  34363. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34364. var i;
  34365. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34366. for (i = 0; i < vertex_data.normals.length; i++) {
  34367. vertex_data.normals[i] *= -1;
  34368. }
  34369. }
  34370. if (vertex_data.indices) {
  34371. var temp;
  34372. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34373. // reassign indices
  34374. temp = vertex_data.indices[i + 1];
  34375. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34376. vertex_data.indices[i + 2] = temp;
  34377. }
  34378. }
  34379. vertex_data.applyToMesh(this);
  34380. return this;
  34381. };
  34382. // Instances
  34383. /**
  34384. * Creates a new InstancedMesh object from the mesh model.
  34385. * Warning : this method is not supported for Line mesh and LineSystem
  34386. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34387. * @param name defines the name of the new instance
  34388. * @returns a new InstancedMesh
  34389. */
  34390. Mesh.prototype.createInstance = function (name) {
  34391. return new BABYLON.InstancedMesh(name, this);
  34392. };
  34393. /**
  34394. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34395. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34396. * @returns the current mesh
  34397. */
  34398. Mesh.prototype.synchronizeInstances = function () {
  34399. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34400. var instance = this.instances[instanceIndex];
  34401. instance._syncSubMeshes();
  34402. }
  34403. return this;
  34404. };
  34405. /**
  34406. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34407. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34408. * This should be used together with the simplification to avoid disappearing triangles.
  34409. * @param successCallback an optional success callback to be called after the optimization finished.
  34410. * @returns the current mesh
  34411. */
  34412. Mesh.prototype.optimizeIndices = function (successCallback) {
  34413. var _this = this;
  34414. var indices = this.getIndices();
  34415. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34416. if (!positions || !indices) {
  34417. return this;
  34418. }
  34419. var vectorPositions = new Array();
  34420. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34421. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34422. }
  34423. var dupes = new Array();
  34424. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34425. var realPos = vectorPositions.length - 1 - iteration;
  34426. var testedPosition = vectorPositions[realPos];
  34427. for (var j = 0; j < realPos; ++j) {
  34428. var againstPosition = vectorPositions[j];
  34429. if (testedPosition.equals(againstPosition)) {
  34430. dupes[realPos] = j;
  34431. break;
  34432. }
  34433. }
  34434. }, function () {
  34435. for (var i = 0; i < indices.length; ++i) {
  34436. indices[i] = dupes[indices[i]] || indices[i];
  34437. }
  34438. //indices are now reordered
  34439. var originalSubMeshes = _this.subMeshes.slice(0);
  34440. _this.setIndices(indices);
  34441. _this.subMeshes = originalSubMeshes;
  34442. if (successCallback) {
  34443. successCallback(_this);
  34444. }
  34445. });
  34446. return this;
  34447. };
  34448. /**
  34449. * Serialize current mesh
  34450. * @param serializationObject defines the object which will receive the serialization data
  34451. */
  34452. Mesh.prototype.serialize = function (serializationObject) {
  34453. serializationObject.name = this.name;
  34454. serializationObject.id = this.id;
  34455. serializationObject.type = this.getClassName();
  34456. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34457. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34458. }
  34459. serializationObject.position = this.position.asArray();
  34460. if (this.rotationQuaternion) {
  34461. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34462. }
  34463. else if (this.rotation) {
  34464. serializationObject.rotation = this.rotation.asArray();
  34465. }
  34466. serializationObject.scaling = this.scaling.asArray();
  34467. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34468. serializationObject.isEnabled = this.isEnabled(false);
  34469. serializationObject.isVisible = this.isVisible;
  34470. serializationObject.infiniteDistance = this.infiniteDistance;
  34471. serializationObject.pickable = this.isPickable;
  34472. serializationObject.receiveShadows = this.receiveShadows;
  34473. serializationObject.billboardMode = this.billboardMode;
  34474. serializationObject.visibility = this.visibility;
  34475. serializationObject.checkCollisions = this.checkCollisions;
  34476. serializationObject.isBlocker = this.isBlocker;
  34477. // Parent
  34478. if (this.parent) {
  34479. serializationObject.parentId = this.parent.id;
  34480. }
  34481. // Geometry
  34482. serializationObject.isUnIndexed = this.isUnIndexed;
  34483. var geometry = this._geometry;
  34484. if (geometry) {
  34485. var geometryId = geometry.id;
  34486. serializationObject.geometryId = geometryId;
  34487. // SubMeshes
  34488. serializationObject.subMeshes = [];
  34489. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34490. var subMesh = this.subMeshes[subIndex];
  34491. serializationObject.subMeshes.push({
  34492. materialIndex: subMesh.materialIndex,
  34493. verticesStart: subMesh.verticesStart,
  34494. verticesCount: subMesh.verticesCount,
  34495. indexStart: subMesh.indexStart,
  34496. indexCount: subMesh.indexCount
  34497. });
  34498. }
  34499. }
  34500. // Material
  34501. if (this.material) {
  34502. serializationObject.materialId = this.material.id;
  34503. }
  34504. else {
  34505. this.material = null;
  34506. }
  34507. // Morph targets
  34508. if (this.morphTargetManager) {
  34509. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34510. }
  34511. // Skeleton
  34512. if (this.skeleton) {
  34513. serializationObject.skeletonId = this.skeleton.id;
  34514. }
  34515. // Physics
  34516. //TODO implement correct serialization for physics impostors.
  34517. var impostor = this.getPhysicsImpostor();
  34518. if (impostor) {
  34519. serializationObject.physicsMass = impostor.getParam("mass");
  34520. serializationObject.physicsFriction = impostor.getParam("friction");
  34521. serializationObject.physicsRestitution = impostor.getParam("mass");
  34522. serializationObject.physicsImpostor = impostor.type;
  34523. }
  34524. // Metadata
  34525. if (this.metadata) {
  34526. serializationObject.metadata = this.metadata;
  34527. }
  34528. // Instances
  34529. serializationObject.instances = [];
  34530. for (var index = 0; index < this.instances.length; index++) {
  34531. var instance = this.instances[index];
  34532. if (instance.doNotSerialize) {
  34533. continue;
  34534. }
  34535. var serializationInstance = {
  34536. name: instance.name,
  34537. id: instance.id,
  34538. position: instance.position.asArray(),
  34539. scaling: instance.scaling.asArray()
  34540. };
  34541. if (instance.parent) {
  34542. serializationInstance.parentId = instance.parent.id;
  34543. }
  34544. if (instance.rotationQuaternion) {
  34545. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34546. }
  34547. else if (instance.rotation) {
  34548. serializationInstance.rotation = instance.rotation.asArray();
  34549. }
  34550. serializationObject.instances.push(serializationInstance);
  34551. // Animations
  34552. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34553. serializationInstance.ranges = instance.serializeAnimationRanges();
  34554. }
  34555. //
  34556. // Animations
  34557. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34558. serializationObject.ranges = this.serializeAnimationRanges();
  34559. // Layer mask
  34560. serializationObject.layerMask = this.layerMask;
  34561. // Alpha
  34562. serializationObject.alphaIndex = this.alphaIndex;
  34563. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34564. // Overlay
  34565. serializationObject.overlayAlpha = this.overlayAlpha;
  34566. serializationObject.overlayColor = this.overlayColor.asArray();
  34567. serializationObject.renderOverlay = this.renderOverlay;
  34568. // Fog
  34569. serializationObject.applyFog = this.applyFog;
  34570. // Action Manager
  34571. if (this.actionManager) {
  34572. serializationObject.actions = this.actionManager.serialize(this.name);
  34573. }
  34574. };
  34575. /** @hidden */
  34576. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34577. if (!this.geometry) {
  34578. return;
  34579. }
  34580. this._markSubMeshesAsAttributesDirty();
  34581. var morphTargetManager = this._morphTargetManager;
  34582. if (morphTargetManager && morphTargetManager.vertexCount) {
  34583. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34584. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34585. this.morphTargetManager = null;
  34586. return;
  34587. }
  34588. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34589. var morphTarget = morphTargetManager.getActiveTarget(index);
  34590. var positions = morphTarget.getPositions();
  34591. if (!positions) {
  34592. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34593. return;
  34594. }
  34595. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34596. var normals = morphTarget.getNormals();
  34597. if (normals) {
  34598. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34599. }
  34600. var tangents = morphTarget.getTangents();
  34601. if (tangents) {
  34602. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34603. }
  34604. }
  34605. }
  34606. else {
  34607. var index = 0;
  34608. // Positions
  34609. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34610. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34611. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34612. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34613. }
  34614. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34615. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34616. }
  34617. index++;
  34618. }
  34619. }
  34620. };
  34621. // Statics
  34622. /**
  34623. * Returns a new Mesh object parsed from the source provided.
  34624. * @param parsedMesh is the source
  34625. * @param scene defines the hosting scene
  34626. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34627. * @returns a new Mesh
  34628. */
  34629. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34630. var mesh;
  34631. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34632. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34633. }
  34634. else {
  34635. mesh = new Mesh(parsedMesh.name, scene);
  34636. }
  34637. mesh.id = parsedMesh.id;
  34638. if (BABYLON.Tags) {
  34639. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34640. }
  34641. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34642. if (parsedMesh.metadata !== undefined) {
  34643. mesh.metadata = parsedMesh.metadata;
  34644. }
  34645. if (parsedMesh.rotationQuaternion) {
  34646. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34647. }
  34648. else if (parsedMesh.rotation) {
  34649. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34650. }
  34651. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34652. if (parsedMesh.localMatrix) {
  34653. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34654. }
  34655. else if (parsedMesh.pivotMatrix) {
  34656. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34657. }
  34658. mesh.setEnabled(parsedMesh.isEnabled);
  34659. mesh.isVisible = parsedMesh.isVisible;
  34660. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34661. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34662. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34663. if (parsedMesh.applyFog !== undefined) {
  34664. mesh.applyFog = parsedMesh.applyFog;
  34665. }
  34666. if (parsedMesh.pickable !== undefined) {
  34667. mesh.isPickable = parsedMesh.pickable;
  34668. }
  34669. if (parsedMesh.alphaIndex !== undefined) {
  34670. mesh.alphaIndex = parsedMesh.alphaIndex;
  34671. }
  34672. mesh.receiveShadows = parsedMesh.receiveShadows;
  34673. mesh.billboardMode = parsedMesh.billboardMode;
  34674. if (parsedMesh.visibility !== undefined) {
  34675. mesh.visibility = parsedMesh.visibility;
  34676. }
  34677. mesh.checkCollisions = parsedMesh.checkCollisions;
  34678. if (parsedMesh.isBlocker !== undefined) {
  34679. mesh.isBlocker = parsedMesh.isBlocker;
  34680. }
  34681. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34682. // freezeWorldMatrix
  34683. if (parsedMesh.freezeWorldMatrix) {
  34684. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34685. }
  34686. // Parent
  34687. if (parsedMesh.parentId) {
  34688. mesh._waitingParentId = parsedMesh.parentId;
  34689. }
  34690. // Actions
  34691. if (parsedMesh.actions !== undefined) {
  34692. mesh._waitingActions = parsedMesh.actions;
  34693. }
  34694. // Overlay
  34695. if (parsedMesh.overlayAlpha !== undefined) {
  34696. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34697. }
  34698. if (parsedMesh.overlayColor !== undefined) {
  34699. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34700. }
  34701. if (parsedMesh.renderOverlay !== undefined) {
  34702. mesh.renderOverlay = parsedMesh.renderOverlay;
  34703. }
  34704. // Geometry
  34705. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34706. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34707. if (parsedMesh.delayLoadingFile) {
  34708. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34709. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34710. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34711. if (parsedMesh._binaryInfo) {
  34712. mesh._binaryInfo = parsedMesh._binaryInfo;
  34713. }
  34714. mesh._delayInfo = [];
  34715. if (parsedMesh.hasUVs) {
  34716. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34717. }
  34718. if (parsedMesh.hasUVs2) {
  34719. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34720. }
  34721. if (parsedMesh.hasUVs3) {
  34722. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34723. }
  34724. if (parsedMesh.hasUVs4) {
  34725. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34726. }
  34727. if (parsedMesh.hasUVs5) {
  34728. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34729. }
  34730. if (parsedMesh.hasUVs6) {
  34731. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34732. }
  34733. if (parsedMesh.hasColors) {
  34734. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34735. }
  34736. if (parsedMesh.hasMatricesIndices) {
  34737. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34738. }
  34739. if (parsedMesh.hasMatricesWeights) {
  34740. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34741. }
  34742. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34743. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34744. mesh._checkDelayState();
  34745. }
  34746. }
  34747. else {
  34748. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34749. }
  34750. // Material
  34751. if (parsedMesh.materialId) {
  34752. mesh.setMaterialByID(parsedMesh.materialId);
  34753. }
  34754. else {
  34755. mesh.material = null;
  34756. }
  34757. // Morph targets
  34758. if (parsedMesh.morphTargetManagerId > -1) {
  34759. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34760. }
  34761. // Skeleton
  34762. if (parsedMesh.skeletonId > -1) {
  34763. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34764. if (parsedMesh.numBoneInfluencers) {
  34765. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34766. }
  34767. }
  34768. // Animations
  34769. if (parsedMesh.animations) {
  34770. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34771. var parsedAnimation = parsedMesh.animations[animationIndex];
  34772. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34773. }
  34774. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34775. }
  34776. if (parsedMesh.autoAnimate) {
  34777. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34778. }
  34779. // Layer Mask
  34780. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34781. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34782. }
  34783. else {
  34784. mesh.layerMask = 0x0FFFFFFF;
  34785. }
  34786. // Physics
  34787. if (parsedMesh.physicsImpostor) {
  34788. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34789. mass: parsedMesh.physicsMass,
  34790. friction: parsedMesh.physicsFriction,
  34791. restitution: parsedMesh.physicsRestitution
  34792. }, scene);
  34793. }
  34794. // Instances
  34795. if (parsedMesh.instances) {
  34796. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34797. var parsedInstance = parsedMesh.instances[index];
  34798. var instance = mesh.createInstance(parsedInstance.name);
  34799. if (parsedInstance.id) {
  34800. instance.id = parsedInstance.id;
  34801. }
  34802. if (BABYLON.Tags) {
  34803. if (parsedInstance.tags) {
  34804. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34805. }
  34806. else {
  34807. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34808. }
  34809. }
  34810. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34811. if (parsedInstance.parentId) {
  34812. instance._waitingParentId = parsedInstance.parentId;
  34813. }
  34814. if (parsedInstance.rotationQuaternion) {
  34815. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34816. }
  34817. else if (parsedInstance.rotation) {
  34818. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34819. }
  34820. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34821. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34822. instance.checkCollisions = parsedInstance.checkCollisions;
  34823. }
  34824. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34825. instance.isPickable = parsedInstance.pickable;
  34826. }
  34827. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34828. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34829. }
  34830. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34831. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34832. }
  34833. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34834. instance.alphaIndex = parsedInstance.alphaIndex;
  34835. }
  34836. // Physics
  34837. if (parsedInstance.physicsImpostor) {
  34838. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34839. mass: parsedInstance.physicsMass,
  34840. friction: parsedInstance.physicsFriction,
  34841. restitution: parsedInstance.physicsRestitution
  34842. }, scene);
  34843. }
  34844. // Animation
  34845. if (parsedInstance.animations) {
  34846. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34847. parsedAnimation = parsedInstance.animations[animationIndex];
  34848. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34849. }
  34850. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34851. if (parsedInstance.autoAnimate) {
  34852. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34853. }
  34854. }
  34855. }
  34856. }
  34857. return mesh;
  34858. };
  34859. /**
  34860. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34861. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34862. * @param name defines the name of the mesh to create
  34863. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34864. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34865. * @param closePath creates a seam between the first and the last points of each path of the path array
  34866. * @param offset is taken in account only if the `pathArray` is containing a single path
  34867. * @param scene defines the hosting scene
  34868. * @param updatable defines if the mesh must be flagged as updatable
  34869. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34870. * @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)
  34871. * @returns a new Mesh
  34872. */
  34873. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34874. if (closeArray === void 0) { closeArray = false; }
  34875. if (updatable === void 0) { updatable = false; }
  34876. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34877. pathArray: pathArray,
  34878. closeArray: closeArray,
  34879. closePath: closePath,
  34880. offset: offset,
  34881. updatable: updatable,
  34882. sideOrientation: sideOrientation,
  34883. instance: instance
  34884. }, scene);
  34885. };
  34886. /**
  34887. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34888. * @param name defines the name of the mesh to create
  34889. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34890. * @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
  34891. * @param scene defines the hosting scene
  34892. * @param updatable defines if the mesh must be flagged as updatable
  34893. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34894. * @returns a new Mesh
  34895. */
  34896. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34897. if (scene === void 0) { scene = null; }
  34898. var options = {
  34899. radius: radius,
  34900. tessellation: tessellation,
  34901. sideOrientation: sideOrientation,
  34902. updatable: updatable
  34903. };
  34904. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34905. };
  34906. /**
  34907. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34908. * @param name defines the name of the mesh to create
  34909. * @param size sets the size (float) of each box side (default 1)
  34910. * @param scene defines the hosting scene
  34911. * @param updatable defines if the mesh must be flagged as updatable
  34912. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34913. * @returns a new Mesh
  34914. */
  34915. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34916. if (scene === void 0) { scene = null; }
  34917. var options = {
  34918. size: size,
  34919. sideOrientation: sideOrientation,
  34920. updatable: updatable
  34921. };
  34922. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34923. };
  34924. /**
  34925. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34926. * @param name defines the name of the mesh to create
  34927. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34928. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34929. * @param scene defines the hosting scene
  34930. * @param updatable defines if the mesh must be flagged as updatable
  34931. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34932. * @returns a new Mesh
  34933. */
  34934. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34935. var options = {
  34936. segments: segments,
  34937. diameterX: diameter,
  34938. diameterY: diameter,
  34939. diameterZ: diameter,
  34940. sideOrientation: sideOrientation,
  34941. updatable: updatable
  34942. };
  34943. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34944. };
  34945. /**
  34946. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34947. * @param name defines the name of the mesh to create
  34948. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34949. * @param diameterTop set the top cap diameter (floats, default 1)
  34950. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34951. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34952. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34953. * @param scene defines the hosting scene
  34954. * @param updatable defines if the mesh must be flagged as updatable
  34955. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34956. * @returns a new Mesh
  34957. */
  34958. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34959. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34960. if (scene !== undefined) {
  34961. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34962. updatable = scene;
  34963. }
  34964. scene = subdivisions;
  34965. subdivisions = 1;
  34966. }
  34967. var options = {
  34968. height: height,
  34969. diameterTop: diameterTop,
  34970. diameterBottom: diameterBottom,
  34971. tessellation: tessellation,
  34972. subdivisions: subdivisions,
  34973. sideOrientation: sideOrientation,
  34974. updatable: updatable
  34975. };
  34976. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34977. };
  34978. // Torus (Code from SharpDX.org)
  34979. /**
  34980. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34981. * @param name defines the name of the mesh to create
  34982. * @param diameter sets the diameter size (float) of the torus (default 1)
  34983. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34984. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34985. * @param scene defines the hosting scene
  34986. * @param updatable defines if the mesh must be flagged as updatable
  34987. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34988. * @returns a new Mesh
  34989. */
  34990. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34991. var options = {
  34992. diameter: diameter,
  34993. thickness: thickness,
  34994. tessellation: tessellation,
  34995. sideOrientation: sideOrientation,
  34996. updatable: updatable
  34997. };
  34998. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34999. };
  35000. /**
  35001. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  35002. * @param name defines the name of the mesh to create
  35003. * @param radius sets the global radius size (float) of the torus knot (default 2)
  35004. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  35005. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  35006. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  35007. * @param p the number of windings on X axis (positive integers, default 2)
  35008. * @param q the number of windings on Y axis (positive integers, default 3)
  35009. * @param scene defines the hosting scene
  35010. * @param updatable defines if the mesh must be flagged as updatable
  35011. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35012. * @returns a new Mesh
  35013. */
  35014. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  35015. var options = {
  35016. radius: radius,
  35017. tube: tube,
  35018. radialSegments: radialSegments,
  35019. tubularSegments: tubularSegments,
  35020. p: p,
  35021. q: q,
  35022. sideOrientation: sideOrientation,
  35023. updatable: updatable
  35024. };
  35025. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  35026. };
  35027. /**
  35028. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35029. * @param name defines the name of the mesh to create
  35030. * @param points is an array successive Vector3
  35031. * @param scene defines the hosting scene
  35032. * @param updatable defines if the mesh must be flagged as updatable
  35033. * @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).
  35034. * @returns a new Mesh
  35035. */
  35036. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35037. if (scene === void 0) { scene = null; }
  35038. if (updatable === void 0) { updatable = false; }
  35039. if (instance === void 0) { instance = null; }
  35040. var options = {
  35041. points: points,
  35042. updatable: updatable,
  35043. instance: instance
  35044. };
  35045. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35046. };
  35047. /**
  35048. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35049. * @param name defines the name of the mesh to create
  35050. * @param points is an array successive Vector3
  35051. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35052. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35053. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35054. * @param scene defines the hosting scene
  35055. * @param updatable defines if the mesh must be flagged as updatable
  35056. * @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)
  35057. * @returns a new Mesh
  35058. */
  35059. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35060. if (scene === void 0) { scene = null; }
  35061. var options = {
  35062. points: points,
  35063. dashSize: dashSize,
  35064. gapSize: gapSize,
  35065. dashNb: dashNb,
  35066. updatable: updatable,
  35067. instance: instance
  35068. };
  35069. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35070. };
  35071. /**
  35072. * Creates a polygon mesh.
  35073. * Please consider using the same method from the MeshBuilder class instead.
  35074. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35075. * 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.
  35076. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35078. * Remember you can only change the shape positions, not their number when updating a polygon.
  35079. */
  35080. /**
  35081. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35082. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35083. * @param name defines the name of the mesh to create
  35084. * @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
  35085. * @param scene defines the hosting scene
  35086. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35087. * @param updatable defines if the mesh must be flagged as updatable
  35088. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35089. * @returns a new Mesh
  35090. */
  35091. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35092. var options = {
  35093. shape: shape,
  35094. holes: holes,
  35095. updatable: updatable,
  35096. sideOrientation: sideOrientation
  35097. };
  35098. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35099. };
  35100. /**
  35101. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35102. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35103. * @param name defines the name of the mesh to create
  35104. * @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
  35105. * @param depth defines the height of extrusion
  35106. * @param scene defines the hosting scene
  35107. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35108. * @param updatable defines if the mesh must be flagged as updatable
  35109. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35110. * @returns a new Mesh
  35111. */
  35112. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35113. var options = {
  35114. shape: shape,
  35115. holes: holes,
  35116. depth: depth,
  35117. updatable: updatable,
  35118. sideOrientation: sideOrientation
  35119. };
  35120. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35121. };
  35122. /**
  35123. * Creates an extruded shape mesh.
  35124. * 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
  35125. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35126. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35127. * @param name defines the name of the mesh to create
  35128. * @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
  35129. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35130. * @param scale is the value to scale the shape
  35131. * @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
  35132. * @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
  35133. * @param scene defines the hosting scene
  35134. * @param updatable defines if the mesh must be flagged as updatable
  35135. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35136. * @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)
  35137. * @returns a new Mesh
  35138. */
  35139. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35140. if (scene === void 0) { scene = null; }
  35141. var options = {
  35142. shape: shape,
  35143. path: path,
  35144. scale: scale,
  35145. rotation: rotation,
  35146. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35147. sideOrientation: sideOrientation,
  35148. instance: instance,
  35149. updatable: updatable
  35150. };
  35151. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35152. };
  35153. /**
  35154. * Creates an custom extruded shape mesh.
  35155. * The custom extrusion is a parametric shape.
  35156. * It has no predefined shape. Its final shape will depend on the input parameters.
  35157. * Please consider using the same method from the MeshBuilder class instead
  35158. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35159. * @param name defines the name of the mesh to create
  35160. * @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
  35161. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35162. * @param scaleFunction is a custom Javascript function called on each path point
  35163. * @param rotationFunction is a custom Javascript function called on each path point
  35164. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35165. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35166. * @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
  35167. * @param scene defines the hosting scene
  35168. * @param updatable defines if the mesh must be flagged as updatable
  35169. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35170. * @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)
  35171. * @returns a new Mesh
  35172. */
  35173. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35174. var options = {
  35175. shape: shape,
  35176. path: path,
  35177. scaleFunction: scaleFunction,
  35178. rotationFunction: rotationFunction,
  35179. ribbonCloseArray: ribbonCloseArray,
  35180. ribbonClosePath: ribbonClosePath,
  35181. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35182. sideOrientation: sideOrientation,
  35183. instance: instance,
  35184. updatable: updatable
  35185. };
  35186. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35187. };
  35188. /**
  35189. * Creates lathe mesh.
  35190. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35191. * Please consider using the same method from the MeshBuilder class instead
  35192. * @param name defines the name of the mesh to create
  35193. * @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
  35194. * @param radius is the radius value of the lathe
  35195. * @param tessellation is the side number of the lathe.
  35196. * @param scene defines the hosting scene
  35197. * @param updatable defines if the mesh must be flagged as updatable
  35198. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35199. * @returns a new Mesh
  35200. */
  35201. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35202. var options = {
  35203. shape: shape,
  35204. radius: radius,
  35205. tessellation: tessellation,
  35206. sideOrientation: sideOrientation,
  35207. updatable: updatable
  35208. };
  35209. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35210. };
  35211. /**
  35212. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35213. * @param name defines the name of the mesh to create
  35214. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35215. * @param scene defines the hosting scene
  35216. * @param updatable defines if the mesh must be flagged as updatable
  35217. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35218. * @returns a new Mesh
  35219. */
  35220. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35221. var options = {
  35222. size: size,
  35223. width: size,
  35224. height: size,
  35225. sideOrientation: sideOrientation,
  35226. updatable: updatable
  35227. };
  35228. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35229. };
  35230. /**
  35231. * Creates a ground mesh.
  35232. * Please consider using the same method from the MeshBuilder class instead
  35233. * @param name defines the name of the mesh to create
  35234. * @param width set the width of the ground
  35235. * @param height set the height of the ground
  35236. * @param subdivisions sets the number of subdivisions per side
  35237. * @param scene defines the hosting scene
  35238. * @param updatable defines if the mesh must be flagged as updatable
  35239. * @returns a new Mesh
  35240. */
  35241. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35242. var options = {
  35243. width: width,
  35244. height: height,
  35245. subdivisions: subdivisions,
  35246. updatable: updatable
  35247. };
  35248. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35249. };
  35250. /**
  35251. * Creates a tiled ground mesh.
  35252. * Please consider using the same method from the MeshBuilder class instead
  35253. * @param name defines the name of the mesh to create
  35254. * @param xmin set the ground minimum X coordinate
  35255. * @param zmin set the ground minimum Y coordinate
  35256. * @param xmax set the ground maximum X coordinate
  35257. * @param zmax set the ground maximum Z coordinate
  35258. * @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
  35259. * @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
  35260. * @param scene defines the hosting scene
  35261. * @param updatable defines if the mesh must be flagged as updatable
  35262. * @returns a new Mesh
  35263. */
  35264. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35265. var options = {
  35266. xmin: xmin,
  35267. zmin: zmin,
  35268. xmax: xmax,
  35269. zmax: zmax,
  35270. subdivisions: subdivisions,
  35271. precision: precision,
  35272. updatable: updatable
  35273. };
  35274. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35275. };
  35276. /**
  35277. * Creates a ground mesh from a height map.
  35278. * Please consider using the same method from the MeshBuilder class instead
  35279. * @see http://doc.babylonjs.com/babylon101/height_map
  35280. * @param name defines the name of the mesh to create
  35281. * @param url sets the URL of the height map image resource
  35282. * @param width set the ground width size
  35283. * @param height set the ground height size
  35284. * @param subdivisions sets the number of subdivision per side
  35285. * @param minHeight is the minimum altitude on the ground
  35286. * @param maxHeight is the maximum altitude on the ground
  35287. * @param scene defines the hosting scene
  35288. * @param updatable defines if the mesh must be flagged as updatable
  35289. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35290. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35291. * @returns a new Mesh
  35292. */
  35293. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35294. var options = {
  35295. width: width,
  35296. height: height,
  35297. subdivisions: subdivisions,
  35298. minHeight: minHeight,
  35299. maxHeight: maxHeight,
  35300. updatable: updatable,
  35301. onReady: onReady,
  35302. alphaFilter: alphaFilter
  35303. };
  35304. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35305. };
  35306. /**
  35307. * Creates a tube mesh.
  35308. * The tube is a parametric shape.
  35309. * It has no predefined shape. Its final shape will depend on the input parameters.
  35310. * Please consider using the same method from the MeshBuilder class instead
  35311. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35312. * @param name defines the name of the mesh to create
  35313. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35314. * @param radius sets the tube radius size
  35315. * @param tessellation is the number of sides on the tubular surface
  35316. * @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
  35317. * @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
  35318. * @param scene defines the hosting scene
  35319. * @param updatable defines if the mesh must be flagged as updatable
  35320. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35321. * @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)
  35322. * @returns a new Mesh
  35323. */
  35324. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35325. var options = {
  35326. path: path,
  35327. radius: radius,
  35328. tessellation: tessellation,
  35329. radiusFunction: radiusFunction,
  35330. arc: 1,
  35331. cap: cap,
  35332. updatable: updatable,
  35333. sideOrientation: sideOrientation,
  35334. instance: instance
  35335. };
  35336. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35337. };
  35338. /**
  35339. * Creates a polyhedron mesh.
  35340. * Please consider using the same method from the MeshBuilder class instead.
  35341. * * 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
  35342. * * The parameter `size` (positive float, default 1) sets the polygon size
  35343. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35344. * * 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`
  35345. * * 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
  35346. * * 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)`)
  35347. * * 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
  35348. * * 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
  35349. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35350. * * 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
  35351. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35352. * @param name defines the name of the mesh to create
  35353. * @param options defines the options used to create the mesh
  35354. * @param scene defines the hosting scene
  35355. * @returns a new Mesh
  35356. */
  35357. Mesh.CreatePolyhedron = function (name, options, scene) {
  35358. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35359. };
  35360. /**
  35361. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35362. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35363. * * 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`)
  35364. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35365. * * 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
  35366. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35367. * * 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
  35368. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35369. * @param name defines the name of the mesh
  35370. * @param options defines the options used to create the mesh
  35371. * @param scene defines the hosting scene
  35372. * @returns a new Mesh
  35373. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35374. */
  35375. Mesh.CreateIcoSphere = function (name, options, scene) {
  35376. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35377. };
  35378. /**
  35379. * Creates a decal mesh.
  35380. * Please consider using the same method from the MeshBuilder class instead.
  35381. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35382. * @param name defines the name of the mesh
  35383. * @param sourceMesh defines the mesh receiving the decal
  35384. * @param position sets the position of the decal in world coordinates
  35385. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35386. * @param size sets the decal scaling
  35387. * @param angle sets the angle to rotate the decal
  35388. * @returns a new Mesh
  35389. */
  35390. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35391. var options = {
  35392. position: position,
  35393. normal: normal,
  35394. size: size,
  35395. angle: angle
  35396. };
  35397. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35398. };
  35399. // Skeletons
  35400. /**
  35401. * Prepare internal position array for software CPU skinning
  35402. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35403. */
  35404. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35405. if (!this._sourcePositions) {
  35406. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35407. if (!source) {
  35408. return this._sourcePositions;
  35409. }
  35410. this._sourcePositions = new Float32Array(source);
  35411. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35412. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35413. }
  35414. }
  35415. return this._sourcePositions;
  35416. };
  35417. /**
  35418. * Prepare internal normal array for software CPU skinning
  35419. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35420. */
  35421. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35422. if (!this._sourceNormals) {
  35423. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35424. if (!source) {
  35425. return this._sourceNormals;
  35426. }
  35427. this._sourceNormals = new Float32Array(source);
  35428. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35429. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35430. }
  35431. }
  35432. return this._sourceNormals;
  35433. };
  35434. /**
  35435. * Updates the vertex buffer by applying transformation from the bones
  35436. * @param skeleton defines the skeleton to apply to current mesh
  35437. * @returns the current mesh
  35438. */
  35439. Mesh.prototype.applySkeleton = function (skeleton) {
  35440. if (!this.geometry) {
  35441. return this;
  35442. }
  35443. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35444. return this;
  35445. }
  35446. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35447. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35448. return this;
  35449. }
  35450. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35451. return this;
  35452. }
  35453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35454. return this;
  35455. }
  35456. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35457. return this;
  35458. }
  35459. if (!this._sourcePositions) {
  35460. var submeshes = this.subMeshes.slice();
  35461. this.setPositionsForCPUSkinning();
  35462. this.subMeshes = submeshes;
  35463. }
  35464. if (!this._sourceNormals) {
  35465. this.setNormalsForCPUSkinning();
  35466. }
  35467. // positionsData checks for not being Float32Array will only pass at most once
  35468. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35469. if (!positionsData) {
  35470. return this;
  35471. }
  35472. if (!(positionsData instanceof Float32Array)) {
  35473. positionsData = new Float32Array(positionsData);
  35474. }
  35475. // normalsData checks for not being Float32Array will only pass at most once
  35476. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35477. if (!normalsData) {
  35478. return this;
  35479. }
  35480. if (!(normalsData instanceof Float32Array)) {
  35481. normalsData = new Float32Array(normalsData);
  35482. }
  35483. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35484. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35485. if (!matricesWeightsData || !matricesIndicesData) {
  35486. return this;
  35487. }
  35488. var needExtras = this.numBoneInfluencers > 4;
  35489. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35490. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35491. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35492. var tempVector3 = BABYLON.Vector3.Zero();
  35493. var finalMatrix = new BABYLON.Matrix();
  35494. var tempMatrix = new BABYLON.Matrix();
  35495. var matWeightIdx = 0;
  35496. var inf;
  35497. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35498. var weight;
  35499. for (inf = 0; inf < 4; inf++) {
  35500. weight = matricesWeightsData[matWeightIdx + inf];
  35501. if (weight > 0) {
  35502. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35503. finalMatrix.addToSelf(tempMatrix);
  35504. }
  35505. }
  35506. if (needExtras) {
  35507. for (inf = 0; inf < 4; inf++) {
  35508. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35509. if (weight > 0) {
  35510. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35511. finalMatrix.addToSelf(tempMatrix);
  35512. }
  35513. }
  35514. }
  35515. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35516. tempVector3.toArray(positionsData, index);
  35517. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35518. tempVector3.toArray(normalsData, index);
  35519. finalMatrix.reset();
  35520. }
  35521. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35522. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35523. return this;
  35524. };
  35525. // Tools
  35526. /**
  35527. * 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
  35528. * @param meshes defines the list of meshes to scan
  35529. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35530. */
  35531. Mesh.MinMax = function (meshes) {
  35532. var minVector = null;
  35533. var maxVector = null;
  35534. meshes.forEach(function (mesh, index, array) {
  35535. var boundingInfo = mesh.getBoundingInfo();
  35536. var boundingBox = boundingInfo.boundingBox;
  35537. if (!minVector || !maxVector) {
  35538. minVector = boundingBox.minimumWorld;
  35539. maxVector = boundingBox.maximumWorld;
  35540. }
  35541. else {
  35542. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35543. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35544. }
  35545. });
  35546. if (!minVector || !maxVector) {
  35547. return {
  35548. min: BABYLON.Vector3.Zero(),
  35549. max: BABYLON.Vector3.Zero()
  35550. };
  35551. }
  35552. return {
  35553. min: minVector,
  35554. max: maxVector
  35555. };
  35556. };
  35557. /**
  35558. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35559. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35560. * @returns a vector3
  35561. */
  35562. Mesh.Center = function (meshesOrMinMaxVector) {
  35563. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35564. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35565. };
  35566. /**
  35567. * Merge the array of meshes into a single mesh for performance reasons.
  35568. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35569. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35570. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35571. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35572. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35573. * @returns a new mesh
  35574. */
  35575. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35576. if (disposeSource === void 0) { disposeSource = true; }
  35577. var index;
  35578. if (!allow32BitsIndices) {
  35579. var totalVertices = 0;
  35580. // Counting vertices
  35581. for (index = 0; index < meshes.length; index++) {
  35582. if (meshes[index]) {
  35583. totalVertices += meshes[index].getTotalVertices();
  35584. if (totalVertices > 65536) {
  35585. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35586. return null;
  35587. }
  35588. }
  35589. }
  35590. }
  35591. // Merge
  35592. var vertexData = null;
  35593. var otherVertexData;
  35594. var indiceArray = new Array();
  35595. var source = null;
  35596. for (index = 0; index < meshes.length; index++) {
  35597. if (meshes[index]) {
  35598. var wm = meshes[index].computeWorldMatrix(true);
  35599. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35600. otherVertexData.transform(wm);
  35601. if (vertexData) {
  35602. vertexData.merge(otherVertexData, allow32BitsIndices);
  35603. }
  35604. else {
  35605. vertexData = otherVertexData;
  35606. source = meshes[index];
  35607. }
  35608. if (subdivideWithSubMeshes) {
  35609. indiceArray.push(meshes[index].getTotalIndices());
  35610. }
  35611. }
  35612. }
  35613. source = source;
  35614. if (!meshSubclass) {
  35615. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35616. }
  35617. vertexData.applyToMesh(meshSubclass);
  35618. // Setting properties
  35619. meshSubclass.material = source.material;
  35620. meshSubclass.checkCollisions = source.checkCollisions;
  35621. // Cleaning
  35622. if (disposeSource) {
  35623. for (index = 0; index < meshes.length; index++) {
  35624. if (meshes[index]) {
  35625. meshes[index].dispose();
  35626. }
  35627. }
  35628. }
  35629. // Subdivide
  35630. if (subdivideWithSubMeshes) {
  35631. //-- removal of global submesh
  35632. meshSubclass.releaseSubMeshes();
  35633. index = 0;
  35634. var offset = 0;
  35635. //-- apply subdivision according to index table
  35636. while (index < indiceArray.length) {
  35637. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35638. offset += indiceArray[index];
  35639. index++;
  35640. }
  35641. }
  35642. return meshSubclass;
  35643. };
  35644. /** @hidden */
  35645. Mesh.prototype.addInstance = function (instance) {
  35646. instance._indexInSourceMeshInstanceArray = this.instances.length;
  35647. this.instances.push(instance);
  35648. };
  35649. /** @hidden */
  35650. Mesh.prototype.removeInstance = function (instance) {
  35651. // Remove from mesh
  35652. var index = instance._indexInSourceMeshInstanceArray;
  35653. if (index != -1) {
  35654. if (index !== this.instances.length - 1) {
  35655. var last = this.instances[this.instances.length - 1];
  35656. this.instances[index] = last;
  35657. last._indexInSourceMeshInstanceArray = index;
  35658. }
  35659. instance._indexInSourceMeshInstanceArray = -1;
  35660. this.instances.pop();
  35661. }
  35662. };
  35663. // Consts
  35664. /**
  35665. * Mesh side orientation : usually the external or front surface
  35666. */
  35667. Mesh.FRONTSIDE = 0;
  35668. /**
  35669. * Mesh side orientation : usually the internal or back surface
  35670. */
  35671. Mesh.BACKSIDE = 1;
  35672. /**
  35673. * Mesh side orientation : both internal and external or front and back surfaces
  35674. */
  35675. Mesh.DOUBLESIDE = 2;
  35676. /**
  35677. * Mesh side orientation : by default, `FRONTSIDE`
  35678. */
  35679. Mesh.DEFAULTSIDE = 0;
  35680. /**
  35681. * Mesh cap setting : no cap
  35682. */
  35683. Mesh.NO_CAP = 0;
  35684. /**
  35685. * Mesh cap setting : one cap at the beginning of the mesh
  35686. */
  35687. Mesh.CAP_START = 1;
  35688. /**
  35689. * Mesh cap setting : one cap at the end of the mesh
  35690. */
  35691. Mesh.CAP_END = 2;
  35692. /**
  35693. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35694. */
  35695. Mesh.CAP_ALL = 3;
  35696. return Mesh;
  35697. }(BABYLON.AbstractMesh));
  35698. BABYLON.Mesh = Mesh;
  35699. })(BABYLON || (BABYLON = {}));
  35700. //# sourceMappingURL=babylon.mesh.js.map
  35701. var BABYLON;
  35702. (function (BABYLON) {
  35703. /**
  35704. * Base class for submeshes
  35705. */
  35706. var BaseSubMesh = /** @class */ (function () {
  35707. function BaseSubMesh() {
  35708. }
  35709. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35710. /**
  35711. * Gets associated effect
  35712. */
  35713. get: function () {
  35714. return this._materialEffect;
  35715. },
  35716. enumerable: true,
  35717. configurable: true
  35718. });
  35719. /**
  35720. * Sets associated effect (effect used to render this submesh)
  35721. * @param effect defines the effect to associate with
  35722. * @param defines defines the set of defines used to compile this effect
  35723. */
  35724. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35725. if (defines === void 0) { defines = null; }
  35726. if (this._materialEffect === effect) {
  35727. if (!effect) {
  35728. this._materialDefines = null;
  35729. }
  35730. return;
  35731. }
  35732. this._materialDefines = defines;
  35733. this._materialEffect = effect;
  35734. };
  35735. return BaseSubMesh;
  35736. }());
  35737. BABYLON.BaseSubMesh = BaseSubMesh;
  35738. /**
  35739. * Defines a subdivision inside a mesh
  35740. */
  35741. var SubMesh = /** @class */ (function (_super) {
  35742. __extends(SubMesh, _super);
  35743. /**
  35744. * Creates a new submesh
  35745. * @param materialIndex defines the material index to use
  35746. * @param verticesStart defines vertex index start
  35747. * @param verticesCount defines vertices count
  35748. * @param indexStart defines index start
  35749. * @param indexCount defines indices count
  35750. * @param mesh defines the parent mesh
  35751. * @param renderingMesh defines an optional rendering mesh
  35752. * @param createBoundingBox defines if bounding box should be created for this submesh
  35753. */
  35754. function SubMesh(
  35755. /** the material index to use */
  35756. materialIndex,
  35757. /** vertex index start */
  35758. verticesStart,
  35759. /** vertices count */
  35760. verticesCount,
  35761. /** index start */
  35762. indexStart,
  35763. /** indices count */
  35764. indexCount, mesh, renderingMesh, createBoundingBox) {
  35765. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35766. var _this = _super.call(this) || this;
  35767. _this.materialIndex = materialIndex;
  35768. _this.verticesStart = verticesStart;
  35769. _this.verticesCount = verticesCount;
  35770. _this.indexStart = indexStart;
  35771. _this.indexCount = indexCount;
  35772. /** @hidden */
  35773. _this._renderId = 0;
  35774. _this._mesh = mesh;
  35775. _this._renderingMesh = renderingMesh || mesh;
  35776. mesh.subMeshes.push(_this);
  35777. _this._trianglePlanes = [];
  35778. _this._id = mesh.subMeshes.length - 1;
  35779. if (createBoundingBox) {
  35780. _this.refreshBoundingInfo();
  35781. mesh.computeWorldMatrix(true);
  35782. }
  35783. return _this;
  35784. }
  35785. /**
  35786. * Add a new submesh to a mesh
  35787. * @param materialIndex defines the material index to use
  35788. * @param verticesStart defines vertex index start
  35789. * @param verticesCount defines vertices count
  35790. * @param indexStart defines index start
  35791. * @param indexCount defines indices count
  35792. * @param mesh defines the parent mesh
  35793. * @param renderingMesh defines an optional rendering mesh
  35794. * @param createBoundingBox defines if bounding box should be created for this submesh
  35795. * @returns the new submesh
  35796. */
  35797. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35798. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35799. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35800. };
  35801. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35802. /**
  35803. * Returns true if this submesh covers the entire parent mesh
  35804. * @ignorenaming
  35805. */
  35806. get: function () {
  35807. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. /**
  35813. * Returns the submesh BoudingInfo object
  35814. * @returns current bounding info (or mesh's one if the submesh is global)
  35815. */
  35816. SubMesh.prototype.getBoundingInfo = function () {
  35817. if (this.IsGlobal) {
  35818. return this._mesh.getBoundingInfo();
  35819. }
  35820. return this._boundingInfo;
  35821. };
  35822. /**
  35823. * Sets the submesh BoundingInfo
  35824. * @param boundingInfo defines the new bounding info to use
  35825. * @returns the SubMesh
  35826. */
  35827. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35828. this._boundingInfo = boundingInfo;
  35829. return this;
  35830. };
  35831. /**
  35832. * Returns the mesh of the current submesh
  35833. * @return the parent mesh
  35834. */
  35835. SubMesh.prototype.getMesh = function () {
  35836. return this._mesh;
  35837. };
  35838. /**
  35839. * Returns the rendering mesh of the submesh
  35840. * @returns the rendering mesh (could be different from parent mesh)
  35841. */
  35842. SubMesh.prototype.getRenderingMesh = function () {
  35843. return this._renderingMesh;
  35844. };
  35845. /**
  35846. * Returns the submesh material
  35847. * @returns null or the current material
  35848. */
  35849. SubMesh.prototype.getMaterial = function () {
  35850. var rootMaterial = this._renderingMesh.material;
  35851. if (rootMaterial === null || rootMaterial === undefined) {
  35852. return this._mesh.getScene().defaultMaterial;
  35853. }
  35854. else if (rootMaterial.getSubMaterial) {
  35855. var multiMaterial = rootMaterial;
  35856. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35857. if (this._currentMaterial !== effectiveMaterial) {
  35858. this._currentMaterial = effectiveMaterial;
  35859. this._materialDefines = null;
  35860. }
  35861. return effectiveMaterial;
  35862. }
  35863. return rootMaterial;
  35864. };
  35865. // Methods
  35866. /**
  35867. * Sets a new updated BoundingInfo object to the submesh
  35868. * @returns the SubMesh
  35869. */
  35870. SubMesh.prototype.refreshBoundingInfo = function () {
  35871. this._lastColliderWorldVertices = null;
  35872. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35873. return this;
  35874. }
  35875. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35876. if (!data) {
  35877. this._boundingInfo = this._mesh.getBoundingInfo();
  35878. return this;
  35879. }
  35880. var indices = this._renderingMesh.getIndices();
  35881. var extend;
  35882. //is this the only submesh?
  35883. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35884. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35885. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35886. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35887. }
  35888. else {
  35889. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35890. }
  35891. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35892. return this;
  35893. };
  35894. /** @hidden */
  35895. SubMesh.prototype._checkCollision = function (collider) {
  35896. var boundingInfo = this.getBoundingInfo();
  35897. return boundingInfo._checkCollision(collider);
  35898. };
  35899. /**
  35900. * Updates the submesh BoundingInfo
  35901. * @param world defines the world matrix to use to update the bounding info
  35902. * @returns the submesh
  35903. */
  35904. SubMesh.prototype.updateBoundingInfo = function (world) {
  35905. var boundingInfo = this.getBoundingInfo();
  35906. if (!boundingInfo) {
  35907. this.refreshBoundingInfo();
  35908. boundingInfo = this.getBoundingInfo();
  35909. }
  35910. boundingInfo.update(world);
  35911. return this;
  35912. };
  35913. /**
  35914. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35915. * @param frustumPlanes defines the frustum planes
  35916. * @returns true if the submesh is intersecting with the frustum
  35917. */
  35918. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35919. var boundingInfo = this.getBoundingInfo();
  35920. if (!boundingInfo) {
  35921. return false;
  35922. }
  35923. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35924. };
  35925. /**
  35926. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35927. * @param frustumPlanes defines the frustum planes
  35928. * @returns true if the submesh is inside the frustum
  35929. */
  35930. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35931. var boundingInfo = this.getBoundingInfo();
  35932. if (!boundingInfo) {
  35933. return false;
  35934. }
  35935. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35936. };
  35937. /**
  35938. * Renders the submesh
  35939. * @param enableAlphaMode defines if alpha needs to be used
  35940. * @returns the submesh
  35941. */
  35942. SubMesh.prototype.render = function (enableAlphaMode) {
  35943. this._renderingMesh.render(this, enableAlphaMode);
  35944. return this;
  35945. };
  35946. /**
  35947. * @hidden
  35948. */
  35949. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35950. if (!this._linesIndexBuffer) {
  35951. var linesIndices = [];
  35952. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35953. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35954. }
  35955. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35956. this._linesIndexCount = linesIndices.length;
  35957. }
  35958. return this._linesIndexBuffer;
  35959. };
  35960. /**
  35961. * Checks if the submesh intersects with a ray
  35962. * @param ray defines the ray to test
  35963. * @returns true is the passed ray intersects the submesh bounding box
  35964. */
  35965. SubMesh.prototype.canIntersects = function (ray) {
  35966. var boundingInfo = this.getBoundingInfo();
  35967. if (!boundingInfo) {
  35968. return false;
  35969. }
  35970. return ray.intersectsBox(boundingInfo.boundingBox);
  35971. };
  35972. /**
  35973. * Intersects current submesh with a ray
  35974. * @param ray defines the ray to test
  35975. * @param positions defines mesh's positions array
  35976. * @param indices defines mesh's indices array
  35977. * @param fastCheck defines if only bounding info should be used
  35978. * @returns intersection info or null if no intersection
  35979. */
  35980. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35981. var material = this.getMaterial();
  35982. if (!material) {
  35983. return null;
  35984. }
  35985. switch (material.fillMode) {
  35986. case BABYLON.Material.PointListDrawMode:
  35987. case BABYLON.Material.LineListDrawMode:
  35988. case BABYLON.Material.LineLoopDrawMode:
  35989. case BABYLON.Material.LineStripDrawMode:
  35990. case BABYLON.Material.TriangleFanDrawMode:
  35991. case BABYLON.Material.TriangleStripDrawMode:
  35992. return null;
  35993. }
  35994. // LineMesh first as it's also a Mesh...
  35995. if (BABYLON.LinesMesh) {
  35996. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35997. if (mesh instanceof BABYLON.LinesMesh) {
  35998. var linesMesh = mesh;
  35999. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  36000. }
  36001. }
  36002. return this._intersectTriangles(ray, positions, indices, fastCheck);
  36003. };
  36004. /** @hidden */
  36005. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  36006. var intersectInfo = null;
  36007. // Line test
  36008. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  36009. var p0 = positions[indices[index]];
  36010. var p1 = positions[indices[index + 1]];
  36011. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  36012. if (length < 0) {
  36013. continue;
  36014. }
  36015. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  36016. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  36017. if (fastCheck) {
  36018. break;
  36019. }
  36020. }
  36021. }
  36022. return intersectInfo;
  36023. };
  36024. /** @hidden */
  36025. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36026. var intersectInfo = null;
  36027. // Triangles test
  36028. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36029. var p0 = positions[indices[index]];
  36030. var p1 = positions[indices[index + 1]];
  36031. var p2 = positions[indices[index + 2]];
  36032. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36033. if (currentIntersectInfo) {
  36034. if (currentIntersectInfo.distance < 0) {
  36035. continue;
  36036. }
  36037. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36038. intersectInfo = currentIntersectInfo;
  36039. intersectInfo.faceId = index / 3;
  36040. if (fastCheck) {
  36041. break;
  36042. }
  36043. }
  36044. }
  36045. }
  36046. return intersectInfo;
  36047. };
  36048. /** @hidden */
  36049. SubMesh.prototype._rebuild = function () {
  36050. if (this._linesIndexBuffer) {
  36051. this._linesIndexBuffer = null;
  36052. }
  36053. };
  36054. // Clone
  36055. /**
  36056. * Creates a new submesh from the passed mesh
  36057. * @param newMesh defines the new hosting mesh
  36058. * @param newRenderingMesh defines an optional rendering mesh
  36059. * @returns the new submesh
  36060. */
  36061. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36062. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36063. if (!this.IsGlobal) {
  36064. var boundingInfo = this.getBoundingInfo();
  36065. if (!boundingInfo) {
  36066. return result;
  36067. }
  36068. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36069. }
  36070. return result;
  36071. };
  36072. // Dispose
  36073. /**
  36074. * Release associated resources
  36075. */
  36076. SubMesh.prototype.dispose = function () {
  36077. if (this._linesIndexBuffer) {
  36078. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36079. this._linesIndexBuffer = null;
  36080. }
  36081. // Remove from mesh
  36082. var index = this._mesh.subMeshes.indexOf(this);
  36083. this._mesh.subMeshes.splice(index, 1);
  36084. };
  36085. // Statics
  36086. /**
  36087. * Creates a new submesh from indices data
  36088. * @param materialIndex the index of the main mesh material
  36089. * @param startIndex the index where to start the copy in the mesh indices array
  36090. * @param indexCount the number of indices to copy then from the startIndex
  36091. * @param mesh the main mesh to create the submesh from
  36092. * @param renderingMesh the optional rendering mesh
  36093. * @returns a new submesh
  36094. */
  36095. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36096. var minVertexIndex = Number.MAX_VALUE;
  36097. var maxVertexIndex = -Number.MAX_VALUE;
  36098. renderingMesh = (renderingMesh || mesh);
  36099. var indices = renderingMesh.getIndices();
  36100. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36101. var vertexIndex = indices[index];
  36102. if (vertexIndex < minVertexIndex) {
  36103. minVertexIndex = vertexIndex;
  36104. }
  36105. if (vertexIndex > maxVertexIndex) {
  36106. maxVertexIndex = vertexIndex;
  36107. }
  36108. }
  36109. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36110. };
  36111. return SubMesh;
  36112. }(BaseSubMesh));
  36113. BABYLON.SubMesh = SubMesh;
  36114. })(BABYLON || (BABYLON = {}));
  36115. //# sourceMappingURL=babylon.subMesh.js.map
  36116. var __assign = (this && this.__assign) || function () {
  36117. __assign = Object.assign || function(t) {
  36118. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36119. s = arguments[i];
  36120. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36121. t[p] = s[p];
  36122. }
  36123. return t;
  36124. };
  36125. return __assign.apply(this, arguments);
  36126. };
  36127. var BABYLON;
  36128. (function (BABYLON) {
  36129. /**
  36130. * Manages the defines for the Material
  36131. */
  36132. var MaterialDefines = /** @class */ (function () {
  36133. function MaterialDefines() {
  36134. this._isDirty = true;
  36135. /** @hidden */
  36136. this._areLightsDirty = true;
  36137. /** @hidden */
  36138. this._areAttributesDirty = true;
  36139. /** @hidden */
  36140. this._areTexturesDirty = true;
  36141. /** @hidden */
  36142. this._areFresnelDirty = true;
  36143. /** @hidden */
  36144. this._areMiscDirty = true;
  36145. /** @hidden */
  36146. this._areImageProcessingDirty = true;
  36147. /** @hidden */
  36148. this._normals = false;
  36149. /** @hidden */
  36150. this._uvs = false;
  36151. /** @hidden */
  36152. this._needNormals = false;
  36153. /** @hidden */
  36154. this._needUVs = false;
  36155. }
  36156. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36157. /**
  36158. * Specifies if the material needs to be re-calculated
  36159. */
  36160. get: function () {
  36161. return this._isDirty;
  36162. },
  36163. enumerable: true,
  36164. configurable: true
  36165. });
  36166. /**
  36167. * Marks the material to indicate that it has been re-calculated
  36168. */
  36169. MaterialDefines.prototype.markAsProcessed = function () {
  36170. this._isDirty = false;
  36171. this._areAttributesDirty = false;
  36172. this._areTexturesDirty = false;
  36173. this._areFresnelDirty = false;
  36174. this._areLightsDirty = false;
  36175. this._areMiscDirty = false;
  36176. this._areImageProcessingDirty = false;
  36177. };
  36178. /**
  36179. * Marks the material to indicate that it needs to be re-calculated
  36180. */
  36181. MaterialDefines.prototype.markAsUnprocessed = function () {
  36182. this._isDirty = true;
  36183. };
  36184. /**
  36185. * Marks the material to indicate all of its defines need to be re-calculated
  36186. */
  36187. MaterialDefines.prototype.markAllAsDirty = function () {
  36188. this._areTexturesDirty = true;
  36189. this._areAttributesDirty = true;
  36190. this._areLightsDirty = true;
  36191. this._areFresnelDirty = true;
  36192. this._areMiscDirty = true;
  36193. this._areImageProcessingDirty = true;
  36194. this._isDirty = true;
  36195. };
  36196. /**
  36197. * Marks the material to indicate that image processing needs to be re-calculated
  36198. */
  36199. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36200. this._areImageProcessingDirty = true;
  36201. this._isDirty = true;
  36202. };
  36203. /**
  36204. * Marks the material to indicate the lights need to be re-calculated
  36205. */
  36206. MaterialDefines.prototype.markAsLightDirty = function () {
  36207. this._areLightsDirty = true;
  36208. this._isDirty = true;
  36209. };
  36210. /**
  36211. * Marks the attribute state as changed
  36212. */
  36213. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36214. this._areAttributesDirty = true;
  36215. this._isDirty = true;
  36216. };
  36217. /**
  36218. * Marks the texture state as changed
  36219. */
  36220. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36221. this._areTexturesDirty = true;
  36222. this._isDirty = true;
  36223. };
  36224. /**
  36225. * Marks the fresnel state as changed
  36226. */
  36227. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36228. this._areFresnelDirty = true;
  36229. this._isDirty = true;
  36230. };
  36231. /**
  36232. * Marks the misc state as changed
  36233. */
  36234. MaterialDefines.prototype.markAsMiscDirty = function () {
  36235. this._areMiscDirty = true;
  36236. this._isDirty = true;
  36237. };
  36238. /**
  36239. * Rebuilds the material defines
  36240. */
  36241. MaterialDefines.prototype.rebuild = function () {
  36242. if (this._keys) {
  36243. delete this._keys;
  36244. }
  36245. this._keys = [];
  36246. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36247. var key = _a[_i];
  36248. if (key[0] === "_") {
  36249. continue;
  36250. }
  36251. this._keys.push(key);
  36252. }
  36253. };
  36254. /**
  36255. * Specifies if two material defines are equal
  36256. * @param other - A material define instance to compare to
  36257. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36258. */
  36259. MaterialDefines.prototype.isEqual = function (other) {
  36260. if (this._keys.length !== other._keys.length) {
  36261. return false;
  36262. }
  36263. for (var index = 0; index < this._keys.length; index++) {
  36264. var prop = this._keys[index];
  36265. if (this[prop] !== other[prop]) {
  36266. return false;
  36267. }
  36268. }
  36269. return true;
  36270. };
  36271. /**
  36272. * Clones this instance's defines to another instance
  36273. * @param other - material defines to clone values to
  36274. */
  36275. MaterialDefines.prototype.cloneTo = function (other) {
  36276. if (this._keys.length !== other._keys.length) {
  36277. other._keys = this._keys.slice(0);
  36278. }
  36279. for (var index = 0; index < this._keys.length; index++) {
  36280. var prop = this._keys[index];
  36281. other[prop] = this[prop];
  36282. }
  36283. };
  36284. /**
  36285. * Resets the material define values
  36286. */
  36287. MaterialDefines.prototype.reset = function () {
  36288. for (var index = 0; index < this._keys.length; index++) {
  36289. var prop = this._keys[index];
  36290. var type = typeof this[prop];
  36291. switch (type) {
  36292. case "number":
  36293. this[prop] = 0;
  36294. break;
  36295. case "string":
  36296. this[prop] = "";
  36297. break;
  36298. default:
  36299. this[prop] = false;
  36300. break;
  36301. }
  36302. }
  36303. };
  36304. /**
  36305. * Converts the material define values to a string
  36306. * @returns - String of material define information
  36307. */
  36308. MaterialDefines.prototype.toString = function () {
  36309. var result = "";
  36310. for (var index = 0; index < this._keys.length; index++) {
  36311. var prop = this._keys[index];
  36312. var value = this[prop];
  36313. var type = typeof value;
  36314. switch (type) {
  36315. case "number":
  36316. case "string":
  36317. result += "#define " + prop + " " + value + "\n";
  36318. break;
  36319. default:
  36320. if (value) {
  36321. result += "#define " + prop + "\n";
  36322. }
  36323. break;
  36324. }
  36325. }
  36326. return result;
  36327. };
  36328. return MaterialDefines;
  36329. }());
  36330. BABYLON.MaterialDefines = MaterialDefines;
  36331. /**
  36332. * Base class for the main features of a material in Babylon.js
  36333. */
  36334. var Material = /** @class */ (function () {
  36335. /**
  36336. * Creates a material instance
  36337. * @param name defines the name of the material
  36338. * @param scene defines the scene to reference
  36339. * @param doNotAdd specifies if the material should be added to the scene
  36340. */
  36341. function Material(name, scene, doNotAdd) {
  36342. /**
  36343. * Specifies if the ready state should be checked on each call
  36344. */
  36345. this.checkReadyOnEveryCall = false;
  36346. /**
  36347. * Specifies if the ready state should be checked once
  36348. */
  36349. this.checkReadyOnlyOnce = false;
  36350. /**
  36351. * The state of the material
  36352. */
  36353. this.state = "";
  36354. /**
  36355. * The alpha value of the material
  36356. */
  36357. this._alpha = 1.0;
  36358. /**
  36359. * Specifies if back face culling is enabled
  36360. */
  36361. this._backFaceCulling = true;
  36362. /**
  36363. * Specifies if the material should be serialized
  36364. */
  36365. this.doNotSerialize = false;
  36366. /**
  36367. * @hidden
  36368. */
  36369. this._storeEffectOnSubMeshes = false;
  36370. /**
  36371. * An event triggered when the material is disposed
  36372. */
  36373. this.onDisposeObservable = new BABYLON.Observable();
  36374. /**
  36375. * Stores the value of the alpha mode
  36376. */
  36377. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36378. /**
  36379. * Stores the state of the need depth pre-pass value
  36380. */
  36381. this._needDepthPrePass = false;
  36382. /**
  36383. * Specifies if depth writing should be disabled
  36384. */
  36385. this.disableDepthWrite = false;
  36386. /**
  36387. * Specifies if depth writing should be forced
  36388. */
  36389. this.forceDepthWrite = false;
  36390. /**
  36391. * Specifies if there should be a separate pass for culling
  36392. */
  36393. this.separateCullingPass = false;
  36394. /**
  36395. * Stores the state specifing if fog should be enabled
  36396. */
  36397. this._fogEnabled = true;
  36398. /**
  36399. * Stores the size of points
  36400. */
  36401. this.pointSize = 1.0;
  36402. /**
  36403. * Stores the z offset value
  36404. */
  36405. this.zOffset = 0;
  36406. /**
  36407. * @hidden
  36408. * Specifies if the material was previously ready
  36409. */
  36410. this._wasPreviouslyReady = false;
  36411. /**
  36412. * Stores the fill mode state
  36413. */
  36414. this._fillMode = Material.TriangleFillMode;
  36415. /** @hidden */
  36416. this._indexInSceneMaterialArray = -1;
  36417. this.name = name;
  36418. this.id = name || BABYLON.Tools.RandomId();
  36419. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36420. this.uniqueId = this._scene.getUniqueId();
  36421. if (this._scene.useRightHandedSystem) {
  36422. this.sideOrientation = Material.ClockWiseSideOrientation;
  36423. }
  36424. else {
  36425. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36426. }
  36427. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36428. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36429. if (!doNotAdd) {
  36430. this._scene.addMaterial(this);
  36431. }
  36432. if (this._scene.useMaterialMeshMap) {
  36433. this.meshMap = {};
  36434. }
  36435. }
  36436. Object.defineProperty(Material, "TriangleFillMode", {
  36437. /**
  36438. * Returns the triangle fill mode
  36439. */
  36440. get: function () {
  36441. return Material._TriangleFillMode;
  36442. },
  36443. enumerable: true,
  36444. configurable: true
  36445. });
  36446. Object.defineProperty(Material, "WireFrameFillMode", {
  36447. /**
  36448. * Returns the wireframe mode
  36449. */
  36450. get: function () {
  36451. return Material._WireFrameFillMode;
  36452. },
  36453. enumerable: true,
  36454. configurable: true
  36455. });
  36456. Object.defineProperty(Material, "PointFillMode", {
  36457. /**
  36458. * Returns the point fill mode
  36459. */
  36460. get: function () {
  36461. return Material._PointFillMode;
  36462. },
  36463. enumerable: true,
  36464. configurable: true
  36465. });
  36466. Object.defineProperty(Material, "PointListDrawMode", {
  36467. /**
  36468. * Returns the point list draw mode
  36469. */
  36470. get: function () {
  36471. return Material._PointListDrawMode;
  36472. },
  36473. enumerable: true,
  36474. configurable: true
  36475. });
  36476. Object.defineProperty(Material, "LineListDrawMode", {
  36477. /**
  36478. * Returns the line list draw mode
  36479. */
  36480. get: function () {
  36481. return Material._LineListDrawMode;
  36482. },
  36483. enumerable: true,
  36484. configurable: true
  36485. });
  36486. Object.defineProperty(Material, "LineLoopDrawMode", {
  36487. /**
  36488. * Returns the line loop draw mode
  36489. */
  36490. get: function () {
  36491. return Material._LineLoopDrawMode;
  36492. },
  36493. enumerable: true,
  36494. configurable: true
  36495. });
  36496. Object.defineProperty(Material, "LineStripDrawMode", {
  36497. /**
  36498. * Returns the line strip draw mode
  36499. */
  36500. get: function () {
  36501. return Material._LineStripDrawMode;
  36502. },
  36503. enumerable: true,
  36504. configurable: true
  36505. });
  36506. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36507. /**
  36508. * Returns the triangle strip draw mode
  36509. */
  36510. get: function () {
  36511. return Material._TriangleStripDrawMode;
  36512. },
  36513. enumerable: true,
  36514. configurable: true
  36515. });
  36516. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36517. /**
  36518. * Returns the triangle fan draw mode
  36519. */
  36520. get: function () {
  36521. return Material._TriangleFanDrawMode;
  36522. },
  36523. enumerable: true,
  36524. configurable: true
  36525. });
  36526. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36527. /**
  36528. * Returns the clock-wise side orientation
  36529. */
  36530. get: function () {
  36531. return Material._ClockWiseSideOrientation;
  36532. },
  36533. enumerable: true,
  36534. configurable: true
  36535. });
  36536. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36537. /**
  36538. * Returns the counter clock-wise side orientation
  36539. */
  36540. get: function () {
  36541. return Material._CounterClockWiseSideOrientation;
  36542. },
  36543. enumerable: true,
  36544. configurable: true
  36545. });
  36546. Object.defineProperty(Material.prototype, "alpha", {
  36547. /**
  36548. * Gets the alpha value of the material
  36549. */
  36550. get: function () {
  36551. return this._alpha;
  36552. },
  36553. /**
  36554. * Sets the alpha value of the material
  36555. */
  36556. set: function (value) {
  36557. if (this._alpha === value) {
  36558. return;
  36559. }
  36560. this._alpha = value;
  36561. this.markAsDirty(Material.MiscDirtyFlag);
  36562. },
  36563. enumerable: true,
  36564. configurable: true
  36565. });
  36566. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36567. /**
  36568. * Gets the back-face culling state
  36569. */
  36570. get: function () {
  36571. return this._backFaceCulling;
  36572. },
  36573. /**
  36574. * Sets the back-face culling state
  36575. */
  36576. set: function (value) {
  36577. if (this._backFaceCulling === value) {
  36578. return;
  36579. }
  36580. this._backFaceCulling = value;
  36581. this.markAsDirty(Material.TextureDirtyFlag);
  36582. },
  36583. enumerable: true,
  36584. configurable: true
  36585. });
  36586. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36587. /**
  36588. * Gets a boolean indicating that current material needs to register RTT
  36589. */
  36590. get: function () {
  36591. return false;
  36592. },
  36593. enumerable: true,
  36594. configurable: true
  36595. });
  36596. Object.defineProperty(Material.prototype, "onDispose", {
  36597. /**
  36598. * Called during a dispose event
  36599. */
  36600. set: function (callback) {
  36601. if (this._onDisposeObserver) {
  36602. this.onDisposeObservable.remove(this._onDisposeObserver);
  36603. }
  36604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36605. },
  36606. enumerable: true,
  36607. configurable: true
  36608. });
  36609. Object.defineProperty(Material.prototype, "onBindObservable", {
  36610. /**
  36611. * An event triggered when the material is bound
  36612. */
  36613. get: function () {
  36614. if (!this._onBindObservable) {
  36615. this._onBindObservable = new BABYLON.Observable();
  36616. }
  36617. return this._onBindObservable;
  36618. },
  36619. enumerable: true,
  36620. configurable: true
  36621. });
  36622. Object.defineProperty(Material.prototype, "onBind", {
  36623. /**
  36624. * Called during a bind event
  36625. */
  36626. set: function (callback) {
  36627. if (this._onBindObserver) {
  36628. this.onBindObservable.remove(this._onBindObserver);
  36629. }
  36630. this._onBindObserver = this.onBindObservable.add(callback);
  36631. },
  36632. enumerable: true,
  36633. configurable: true
  36634. });
  36635. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36636. /**
  36637. * An event triggered when the material is unbound
  36638. */
  36639. get: function () {
  36640. if (!this._onUnBindObservable) {
  36641. this._onUnBindObservable = new BABYLON.Observable();
  36642. }
  36643. return this._onUnBindObservable;
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. Object.defineProperty(Material.prototype, "alphaMode", {
  36649. /**
  36650. * Gets the value of the alpha mode
  36651. */
  36652. get: function () {
  36653. return this._alphaMode;
  36654. },
  36655. /**
  36656. * Sets the value of the alpha mode.
  36657. *
  36658. * | Value | Type | Description |
  36659. * | --- | --- | --- |
  36660. * | 0 | ALPHA_DISABLE | |
  36661. * | 1 | ALPHA_ADD | |
  36662. * | 2 | ALPHA_COMBINE | |
  36663. * | 3 | ALPHA_SUBTRACT | |
  36664. * | 4 | ALPHA_MULTIPLY | |
  36665. * | 5 | ALPHA_MAXIMIZED | |
  36666. * | 6 | ALPHA_ONEONE | |
  36667. * | 7 | ALPHA_PREMULTIPLIED | |
  36668. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36669. * | 9 | ALPHA_INTERPOLATE | |
  36670. * | 10 | ALPHA_SCREENMODE | |
  36671. *
  36672. */
  36673. set: function (value) {
  36674. if (this._alphaMode === value) {
  36675. return;
  36676. }
  36677. this._alphaMode = value;
  36678. this.markAsDirty(Material.TextureDirtyFlag);
  36679. },
  36680. enumerable: true,
  36681. configurable: true
  36682. });
  36683. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36684. /**
  36685. * Gets the depth pre-pass value
  36686. */
  36687. get: function () {
  36688. return this._needDepthPrePass;
  36689. },
  36690. /**
  36691. * Sets the need depth pre-pass value
  36692. */
  36693. set: function (value) {
  36694. if (this._needDepthPrePass === value) {
  36695. return;
  36696. }
  36697. this._needDepthPrePass = value;
  36698. if (this._needDepthPrePass) {
  36699. this.checkReadyOnEveryCall = true;
  36700. }
  36701. },
  36702. enumerable: true,
  36703. configurable: true
  36704. });
  36705. Object.defineProperty(Material.prototype, "fogEnabled", {
  36706. /**
  36707. * Gets the value of the fog enabled state
  36708. */
  36709. get: function () {
  36710. return this._fogEnabled;
  36711. },
  36712. /**
  36713. * Sets the state for enabling fog
  36714. */
  36715. set: function (value) {
  36716. if (this._fogEnabled === value) {
  36717. return;
  36718. }
  36719. this._fogEnabled = value;
  36720. this.markAsDirty(Material.MiscDirtyFlag);
  36721. },
  36722. enumerable: true,
  36723. configurable: true
  36724. });
  36725. Object.defineProperty(Material.prototype, "wireframe", {
  36726. /**
  36727. * Gets a value specifying if wireframe mode is enabled
  36728. */
  36729. get: function () {
  36730. switch (this._fillMode) {
  36731. case Material.WireFrameFillMode:
  36732. case Material.LineListDrawMode:
  36733. case Material.LineLoopDrawMode:
  36734. case Material.LineStripDrawMode:
  36735. return true;
  36736. }
  36737. return this._scene.forceWireframe;
  36738. },
  36739. /**
  36740. * Sets the state of wireframe mode
  36741. */
  36742. set: function (value) {
  36743. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36744. },
  36745. enumerable: true,
  36746. configurable: true
  36747. });
  36748. Object.defineProperty(Material.prototype, "pointsCloud", {
  36749. /**
  36750. * Gets the value specifying if point clouds are enabled
  36751. */
  36752. get: function () {
  36753. switch (this._fillMode) {
  36754. case Material.PointFillMode:
  36755. case Material.PointListDrawMode:
  36756. return true;
  36757. }
  36758. return this._scene.forcePointsCloud;
  36759. },
  36760. /**
  36761. * Sets the state of point cloud mode
  36762. */
  36763. set: function (value) {
  36764. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36765. },
  36766. enumerable: true,
  36767. configurable: true
  36768. });
  36769. Object.defineProperty(Material.prototype, "fillMode", {
  36770. /**
  36771. * Gets the material fill mode
  36772. */
  36773. get: function () {
  36774. return this._fillMode;
  36775. },
  36776. /**
  36777. * Sets the material fill mode
  36778. */
  36779. set: function (value) {
  36780. if (this._fillMode === value) {
  36781. return;
  36782. }
  36783. this._fillMode = value;
  36784. this.markAsDirty(Material.MiscDirtyFlag);
  36785. },
  36786. enumerable: true,
  36787. configurable: true
  36788. });
  36789. /**
  36790. * Returns a string representation of the current material
  36791. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36792. * @returns a string with material information
  36793. */
  36794. Material.prototype.toString = function (fullDetails) {
  36795. var ret = "Name: " + this.name;
  36796. if (fullDetails) {
  36797. }
  36798. return ret;
  36799. };
  36800. /**
  36801. * Gets the class name of the material
  36802. * @returns a string with the class name of the material
  36803. */
  36804. Material.prototype.getClassName = function () {
  36805. return "Material";
  36806. };
  36807. Object.defineProperty(Material.prototype, "isFrozen", {
  36808. /**
  36809. * Specifies if updates for the material been locked
  36810. */
  36811. get: function () {
  36812. return this.checkReadyOnlyOnce;
  36813. },
  36814. enumerable: true,
  36815. configurable: true
  36816. });
  36817. /**
  36818. * Locks updates for the material
  36819. */
  36820. Material.prototype.freeze = function () {
  36821. this.checkReadyOnlyOnce = true;
  36822. };
  36823. /**
  36824. * Unlocks updates for the material
  36825. */
  36826. Material.prototype.unfreeze = function () {
  36827. this.checkReadyOnlyOnce = false;
  36828. };
  36829. /**
  36830. * Specifies if the material is ready to be used
  36831. * @param mesh defines the mesh to check
  36832. * @param useInstances specifies if instances should be used
  36833. * @returns a boolean indicating if the material is ready to be used
  36834. */
  36835. Material.prototype.isReady = function (mesh, useInstances) {
  36836. return true;
  36837. };
  36838. /**
  36839. * Specifies that the submesh is ready to be used
  36840. * @param mesh defines the mesh to check
  36841. * @param subMesh defines which submesh to check
  36842. * @param useInstances specifies that instances should be used
  36843. * @returns a boolean indicating that the submesh is ready or not
  36844. */
  36845. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36846. return false;
  36847. };
  36848. /**
  36849. * Returns the material effect
  36850. * @returns the effect associated with the material
  36851. */
  36852. Material.prototype.getEffect = function () {
  36853. return this._effect;
  36854. };
  36855. /**
  36856. * Returns the current scene
  36857. * @returns a Scene
  36858. */
  36859. Material.prototype.getScene = function () {
  36860. return this._scene;
  36861. };
  36862. /**
  36863. * Specifies if the material will require alpha blending
  36864. * @returns a boolean specifying if alpha blending is needed
  36865. */
  36866. Material.prototype.needAlphaBlending = function () {
  36867. return (this.alpha < 1.0);
  36868. };
  36869. /**
  36870. * Specifies if the mesh will require alpha blending
  36871. * @param mesh defines the mesh to check
  36872. * @returns a boolean specifying if alpha blending is needed for the mesh
  36873. */
  36874. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36875. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36876. };
  36877. /**
  36878. * Specifies if this material should be rendered in alpha test mode
  36879. * @returns a boolean specifying if an alpha test is needed.
  36880. */
  36881. Material.prototype.needAlphaTesting = function () {
  36882. return false;
  36883. };
  36884. /**
  36885. * Gets the texture used for the alpha test
  36886. * @returns the texture to use for alpha testing
  36887. */
  36888. Material.prototype.getAlphaTestTexture = function () {
  36889. return null;
  36890. };
  36891. /**
  36892. * Marks the material to indicate that it needs to be re-calculated
  36893. */
  36894. Material.prototype.markDirty = function () {
  36895. this._wasPreviouslyReady = false;
  36896. };
  36897. /** @hidden */
  36898. Material.prototype._preBind = function (effect, overrideOrientation) {
  36899. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36900. var engine = this._scene.getEngine();
  36901. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36902. var reverse = orientation === Material.ClockWiseSideOrientation;
  36903. engine.enableEffect(effect ? effect : this._effect);
  36904. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36905. return reverse;
  36906. };
  36907. /**
  36908. * Binds the material to the mesh
  36909. * @param world defines the world transformation matrix
  36910. * @param mesh defines the mesh to bind the material to
  36911. */
  36912. Material.prototype.bind = function (world, mesh) {
  36913. };
  36914. /**
  36915. * Binds the submesh to the material
  36916. * @param world defines the world transformation matrix
  36917. * @param mesh defines the mesh containing the submesh
  36918. * @param subMesh defines the submesh to bind the material to
  36919. */
  36920. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36921. };
  36922. /**
  36923. * Binds the world matrix to the material
  36924. * @param world defines the world transformation matrix
  36925. */
  36926. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36927. };
  36928. /**
  36929. * Binds the scene's uniform buffer to the effect.
  36930. * @param effect defines the effect to bind to the scene uniform buffer
  36931. * @param sceneUbo defines the uniform buffer storing scene data
  36932. */
  36933. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36934. sceneUbo.bindToEffect(effect, "Scene");
  36935. };
  36936. /**
  36937. * Binds the view matrix to the effect
  36938. * @param effect defines the effect to bind the view matrix to
  36939. */
  36940. Material.prototype.bindView = function (effect) {
  36941. if (!this._useUBO) {
  36942. effect.setMatrix("view", this.getScene().getViewMatrix());
  36943. }
  36944. else {
  36945. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36946. }
  36947. };
  36948. /**
  36949. * Binds the view projection matrix to the effect
  36950. * @param effect defines the effect to bind the view projection matrix to
  36951. */
  36952. Material.prototype.bindViewProjection = function (effect) {
  36953. if (!this._useUBO) {
  36954. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36955. }
  36956. else {
  36957. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36958. }
  36959. };
  36960. /**
  36961. * Specifies if material alpha testing should be turned on for the mesh
  36962. * @param mesh defines the mesh to check
  36963. */
  36964. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36965. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36966. };
  36967. /**
  36968. * Processes to execute after binding the material to a mesh
  36969. * @param mesh defines the rendered mesh
  36970. */
  36971. Material.prototype._afterBind = function (mesh) {
  36972. this._scene._cachedMaterial = this;
  36973. if (mesh) {
  36974. this._scene._cachedVisibility = mesh.visibility;
  36975. }
  36976. else {
  36977. this._scene._cachedVisibility = 1;
  36978. }
  36979. if (this._onBindObservable && mesh) {
  36980. this._onBindObservable.notifyObservers(mesh);
  36981. }
  36982. if (this.disableDepthWrite) {
  36983. var engine = this._scene.getEngine();
  36984. this._cachedDepthWriteState = engine.getDepthWrite();
  36985. engine.setDepthWrite(false);
  36986. }
  36987. };
  36988. /**
  36989. * Unbinds the material from the mesh
  36990. */
  36991. Material.prototype.unbind = function () {
  36992. if (this._onUnBindObservable) {
  36993. this._onUnBindObservable.notifyObservers(this);
  36994. }
  36995. if (this.disableDepthWrite) {
  36996. var engine = this._scene.getEngine();
  36997. engine.setDepthWrite(this._cachedDepthWriteState);
  36998. }
  36999. };
  37000. /**
  37001. * Gets the active textures from the material
  37002. * @returns an array of textures
  37003. */
  37004. Material.prototype.getActiveTextures = function () {
  37005. return [];
  37006. };
  37007. /**
  37008. * Specifies if the material uses a texture
  37009. * @param texture defines the texture to check against the material
  37010. * @returns a boolean specifying if the material uses the texture
  37011. */
  37012. Material.prototype.hasTexture = function (texture) {
  37013. return false;
  37014. };
  37015. /**
  37016. * Makes a duplicate of the material, and gives it a new name
  37017. * @param name defines the new name for the duplicated material
  37018. * @returns the cloned material
  37019. */
  37020. Material.prototype.clone = function (name) {
  37021. return null;
  37022. };
  37023. /**
  37024. * Gets the meshes bound to the material
  37025. * @returns an array of meshes bound to the material
  37026. */
  37027. Material.prototype.getBindedMeshes = function () {
  37028. var _this = this;
  37029. if (this.meshMap) {
  37030. var result = new Array();
  37031. for (var meshId in this.meshMap) {
  37032. var mesh = this.meshMap[meshId];
  37033. if (mesh) {
  37034. result.push(mesh);
  37035. }
  37036. }
  37037. return result;
  37038. }
  37039. else {
  37040. var meshes = this._scene.meshes;
  37041. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37042. }
  37043. };
  37044. /**
  37045. * Force shader compilation
  37046. * @param mesh defines the mesh associated with this material
  37047. * @param onCompiled defines a function to execute once the material is compiled
  37048. * @param options defines the options to configure the compilation
  37049. */
  37050. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37051. var _this = this;
  37052. var localOptions = __assign({ clipPlane: false }, options);
  37053. var subMesh = new BABYLON.BaseSubMesh();
  37054. var scene = this.getScene();
  37055. var checkReady = function () {
  37056. if (!_this._scene || !_this._scene.getEngine()) {
  37057. return;
  37058. }
  37059. if (subMesh._materialDefines) {
  37060. subMesh._materialDefines._renderId = -1;
  37061. }
  37062. var clipPlaneState = scene.clipPlane;
  37063. if (localOptions.clipPlane) {
  37064. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37065. }
  37066. if (_this._storeEffectOnSubMeshes) {
  37067. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37068. if (onCompiled) {
  37069. onCompiled(_this);
  37070. }
  37071. }
  37072. else {
  37073. setTimeout(checkReady, 16);
  37074. }
  37075. }
  37076. else {
  37077. if (_this.isReady(mesh)) {
  37078. if (onCompiled) {
  37079. onCompiled(_this);
  37080. }
  37081. }
  37082. else {
  37083. setTimeout(checkReady, 16);
  37084. }
  37085. }
  37086. if (localOptions.clipPlane) {
  37087. scene.clipPlane = clipPlaneState;
  37088. }
  37089. };
  37090. checkReady();
  37091. };
  37092. /**
  37093. * Force shader compilation
  37094. * @param mesh defines the mesh that will use this material
  37095. * @param options defines additional options for compiling the shaders
  37096. * @returns a promise that resolves when the compilation completes
  37097. */
  37098. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37099. var _this = this;
  37100. return new Promise(function (resolve) {
  37101. _this.forceCompilation(mesh, function () {
  37102. resolve();
  37103. }, options);
  37104. });
  37105. };
  37106. /**
  37107. * Marks a define in the material to indicate that it needs to be re-computed
  37108. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37109. */
  37110. Material.prototype.markAsDirty = function (flag) {
  37111. if (flag & Material.TextureDirtyFlag) {
  37112. this._markAllSubMeshesAsTexturesDirty();
  37113. }
  37114. if (flag & Material.LightDirtyFlag) {
  37115. this._markAllSubMeshesAsLightsDirty();
  37116. }
  37117. if (flag & Material.FresnelDirtyFlag) {
  37118. this._markAllSubMeshesAsFresnelDirty();
  37119. }
  37120. if (flag & Material.AttributesDirtyFlag) {
  37121. this._markAllSubMeshesAsAttributesDirty();
  37122. }
  37123. if (flag & Material.MiscDirtyFlag) {
  37124. this._markAllSubMeshesAsMiscDirty();
  37125. }
  37126. this.getScene().resetCachedMaterial();
  37127. };
  37128. /**
  37129. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37130. * @param func defines a function which checks material defines against the submeshes
  37131. */
  37132. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37133. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  37134. var mesh = _a[_i];
  37135. if (!mesh.subMeshes) {
  37136. continue;
  37137. }
  37138. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  37139. var subMesh = _c[_b];
  37140. if (subMesh.getMaterial() !== this) {
  37141. continue;
  37142. }
  37143. if (!subMesh._materialDefines) {
  37144. continue;
  37145. }
  37146. func(subMesh._materialDefines);
  37147. }
  37148. }
  37149. };
  37150. /**
  37151. * Indicates that image processing needs to be re-calculated for all submeshes
  37152. */
  37153. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37154. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  37155. };
  37156. /**
  37157. * Indicates that textures need to be re-calculated for all submeshes
  37158. */
  37159. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37160. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  37161. };
  37162. /**
  37163. * Indicates that fresnel needs to be re-calculated for all submeshes
  37164. */
  37165. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  37167. };
  37168. /**
  37169. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37170. */
  37171. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37172. this._markAllSubMeshesAsDirty(function (defines) {
  37173. defines.markAsFresnelDirty();
  37174. defines.markAsMiscDirty();
  37175. });
  37176. };
  37177. /**
  37178. * Indicates that lights need to be re-calculated for all submeshes
  37179. */
  37180. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37181. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  37182. };
  37183. /**
  37184. * Indicates that attributes need to be re-calculated for all submeshes
  37185. */
  37186. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37187. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  37188. };
  37189. /**
  37190. * Indicates that misc needs to be re-calculated for all submeshes
  37191. */
  37192. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37193. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  37194. };
  37195. /**
  37196. * Indicates that textures and misc need to be re-calculated for all submeshes
  37197. */
  37198. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37199. this._markAllSubMeshesAsDirty(function (defines) {
  37200. defines.markAsTexturesDirty();
  37201. defines.markAsMiscDirty();
  37202. });
  37203. };
  37204. /**
  37205. * Disposes the material
  37206. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37207. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37208. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37209. */
  37210. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37211. var scene = this.getScene();
  37212. // Animations
  37213. scene.stopAnimation(this);
  37214. scene.freeProcessedMaterials();
  37215. // Remove from scene
  37216. scene.removeMaterial(this);
  37217. if (notBoundToMesh !== true) {
  37218. // Remove from meshes
  37219. if (this.meshMap) {
  37220. for (var meshId in this.meshMap) {
  37221. var mesh = this.meshMap[meshId];
  37222. if (mesh) {
  37223. mesh.material = null; // will set the entry in the map to undefined
  37224. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37225. }
  37226. }
  37227. }
  37228. else {
  37229. var meshes = scene.meshes;
  37230. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37231. var mesh = meshes_1[_i];
  37232. if (mesh.material === this) {
  37233. mesh.material = null;
  37234. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37235. }
  37236. }
  37237. }
  37238. }
  37239. this._uniformBuffer.dispose();
  37240. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37241. if (forceDisposeEffect && this._effect) {
  37242. if (!this._storeEffectOnSubMeshes) {
  37243. scene.getEngine()._releaseEffect(this._effect);
  37244. }
  37245. this._effect = null;
  37246. }
  37247. // Callback
  37248. this.onDisposeObservable.notifyObservers(this);
  37249. this.onDisposeObservable.clear();
  37250. if (this._onBindObservable) {
  37251. this._onBindObservable.clear();
  37252. }
  37253. if (this._onUnBindObservable) {
  37254. this._onUnBindObservable.clear();
  37255. }
  37256. };
  37257. /** @hidden */
  37258. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37259. if (mesh.geometry) {
  37260. var geometry = (mesh.geometry);
  37261. var scene = this.getScene();
  37262. if (this._storeEffectOnSubMeshes) {
  37263. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37264. var subMesh = _a[_i];
  37265. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37266. if (forceDisposeEffect && subMesh._materialEffect) {
  37267. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37268. }
  37269. }
  37270. }
  37271. else {
  37272. geometry._releaseVertexArrayObject(this._effect);
  37273. }
  37274. }
  37275. };
  37276. /**
  37277. * Serializes this material
  37278. * @returns the serialized material object
  37279. */
  37280. Material.prototype.serialize = function () {
  37281. return BABYLON.SerializationHelper.Serialize(this);
  37282. };
  37283. /**
  37284. * Creates a MultiMaterial from parsed MultiMaterial data.
  37285. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37286. * @param scene defines the hosting scene
  37287. * @returns a new MultiMaterial
  37288. */
  37289. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37290. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37291. multiMaterial.id = parsedMultiMaterial.id;
  37292. if (BABYLON.Tags) {
  37293. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37294. }
  37295. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37296. var subMatId = parsedMultiMaterial.materials[matIndex];
  37297. if (subMatId) {
  37298. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37299. }
  37300. else {
  37301. multiMaterial.subMaterials.push(null);
  37302. }
  37303. }
  37304. return multiMaterial;
  37305. };
  37306. /**
  37307. * Creates a material from parsed material data
  37308. * @param parsedMaterial defines parsed material data
  37309. * @param scene defines the hosting scene
  37310. * @param rootUrl defines the root URL to use to load textures
  37311. * @returns a new material
  37312. */
  37313. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37314. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37315. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37316. }
  37317. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37318. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37319. if (!BABYLON.LegacyPBRMaterial) {
  37320. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37321. return;
  37322. }
  37323. }
  37324. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37325. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37326. };
  37327. // Triangle views
  37328. Material._TriangleFillMode = 0;
  37329. Material._WireFrameFillMode = 1;
  37330. Material._PointFillMode = 2;
  37331. // Draw modes
  37332. Material._PointListDrawMode = 3;
  37333. Material._LineListDrawMode = 4;
  37334. Material._LineLoopDrawMode = 5;
  37335. Material._LineStripDrawMode = 6;
  37336. Material._TriangleStripDrawMode = 7;
  37337. Material._TriangleFanDrawMode = 8;
  37338. /**
  37339. * Stores the clock-wise side orientation
  37340. */
  37341. Material._ClockWiseSideOrientation = 0;
  37342. /**
  37343. * Stores the counter clock-wise side orientation
  37344. */
  37345. Material._CounterClockWiseSideOrientation = 1;
  37346. /**
  37347. * The dirty texture flag value
  37348. */
  37349. Material.TextureDirtyFlag = 1;
  37350. /**
  37351. * The dirty light flag value
  37352. */
  37353. Material.LightDirtyFlag = 2;
  37354. /**
  37355. * The dirty fresnel flag value
  37356. */
  37357. Material.FresnelDirtyFlag = 4;
  37358. /**
  37359. * The dirty attribute flag value
  37360. */
  37361. Material.AttributesDirtyFlag = 8;
  37362. /**
  37363. * The dirty misc flag value
  37364. */
  37365. Material.MiscDirtyFlag = 16;
  37366. /**
  37367. * The all dirty flag value
  37368. */
  37369. Material.AllDirtyFlag = 31;
  37370. __decorate([
  37371. BABYLON.serialize()
  37372. ], Material.prototype, "id", void 0);
  37373. __decorate([
  37374. BABYLON.serialize()
  37375. ], Material.prototype, "uniqueId", void 0);
  37376. __decorate([
  37377. BABYLON.serialize()
  37378. ], Material.prototype, "name", void 0);
  37379. __decorate([
  37380. BABYLON.serialize()
  37381. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37382. __decorate([
  37383. BABYLON.serialize()
  37384. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37385. __decorate([
  37386. BABYLON.serialize()
  37387. ], Material.prototype, "state", void 0);
  37388. __decorate([
  37389. BABYLON.serialize("alpha")
  37390. ], Material.prototype, "_alpha", void 0);
  37391. __decorate([
  37392. BABYLON.serialize("backFaceCulling")
  37393. ], Material.prototype, "_backFaceCulling", void 0);
  37394. __decorate([
  37395. BABYLON.serialize()
  37396. ], Material.prototype, "sideOrientation", void 0);
  37397. __decorate([
  37398. BABYLON.serialize("alphaMode")
  37399. ], Material.prototype, "_alphaMode", void 0);
  37400. __decorate([
  37401. BABYLON.serialize()
  37402. ], Material.prototype, "_needDepthPrePass", void 0);
  37403. __decorate([
  37404. BABYLON.serialize()
  37405. ], Material.prototype, "disableDepthWrite", void 0);
  37406. __decorate([
  37407. BABYLON.serialize()
  37408. ], Material.prototype, "forceDepthWrite", void 0);
  37409. __decorate([
  37410. BABYLON.serialize()
  37411. ], Material.prototype, "separateCullingPass", void 0);
  37412. __decorate([
  37413. BABYLON.serialize("fogEnabled")
  37414. ], Material.prototype, "_fogEnabled", void 0);
  37415. __decorate([
  37416. BABYLON.serialize()
  37417. ], Material.prototype, "pointSize", void 0);
  37418. __decorate([
  37419. BABYLON.serialize()
  37420. ], Material.prototype, "zOffset", void 0);
  37421. __decorate([
  37422. BABYLON.serialize()
  37423. ], Material.prototype, "wireframe", null);
  37424. __decorate([
  37425. BABYLON.serialize()
  37426. ], Material.prototype, "pointsCloud", null);
  37427. __decorate([
  37428. BABYLON.serialize()
  37429. ], Material.prototype, "fillMode", null);
  37430. return Material;
  37431. }());
  37432. BABYLON.Material = Material;
  37433. })(BABYLON || (BABYLON = {}));
  37434. //# sourceMappingURL=babylon.material.js.map
  37435. var BABYLON;
  37436. (function (BABYLON) {
  37437. /**
  37438. * Uniform buffer objects.
  37439. *
  37440. * Handles blocks of uniform on the GPU.
  37441. *
  37442. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37443. *
  37444. * For more information, please refer to :
  37445. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37446. */
  37447. var UniformBuffer = /** @class */ (function () {
  37448. /**
  37449. * Instantiates a new Uniform buffer objects.
  37450. *
  37451. * Handles blocks of uniform on the GPU.
  37452. *
  37453. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37454. *
  37455. * For more information, please refer to :
  37456. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37457. * @param engine Define the engine the buffer is associated with
  37458. * @param data Define the data contained in the buffer
  37459. * @param dynamic Define if the buffer is updatable
  37460. */
  37461. function UniformBuffer(engine, data, dynamic) {
  37462. this._engine = engine;
  37463. this._noUBO = !engine.supportsUniformBuffers;
  37464. this._dynamic = dynamic;
  37465. this._data = data || [];
  37466. this._uniformLocations = {};
  37467. this._uniformSizes = {};
  37468. this._uniformLocationPointer = 0;
  37469. this._needSync = false;
  37470. if (this._noUBO) {
  37471. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37472. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37473. this.updateFloat = this._updateFloatForEffect;
  37474. this.updateFloat2 = this._updateFloat2ForEffect;
  37475. this.updateFloat3 = this._updateFloat3ForEffect;
  37476. this.updateFloat4 = this._updateFloat4ForEffect;
  37477. this.updateMatrix = this._updateMatrixForEffect;
  37478. this.updateVector3 = this._updateVector3ForEffect;
  37479. this.updateVector4 = this._updateVector4ForEffect;
  37480. this.updateColor3 = this._updateColor3ForEffect;
  37481. this.updateColor4 = this._updateColor4ForEffect;
  37482. }
  37483. else {
  37484. this._engine._uniformBuffers.push(this);
  37485. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37486. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37487. this.updateFloat = this._updateFloatForUniform;
  37488. this.updateFloat2 = this._updateFloat2ForUniform;
  37489. this.updateFloat3 = this._updateFloat3ForUniform;
  37490. this.updateFloat4 = this._updateFloat4ForUniform;
  37491. this.updateMatrix = this._updateMatrixForUniform;
  37492. this.updateVector3 = this._updateVector3ForUniform;
  37493. this.updateVector4 = this._updateVector4ForUniform;
  37494. this.updateColor3 = this._updateColor3ForUniform;
  37495. this.updateColor4 = this._updateColor4ForUniform;
  37496. }
  37497. }
  37498. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37499. /**
  37500. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37501. * or just falling back on setUniformXXX calls.
  37502. */
  37503. get: function () {
  37504. return !this._noUBO;
  37505. },
  37506. enumerable: true,
  37507. configurable: true
  37508. });
  37509. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37510. /**
  37511. * Indicates if the WebGL underlying uniform buffer is in sync
  37512. * with the javascript cache data.
  37513. */
  37514. get: function () {
  37515. return !this._needSync;
  37516. },
  37517. enumerable: true,
  37518. configurable: true
  37519. });
  37520. /**
  37521. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37522. * Also, a dynamic UniformBuffer will disable cache verification and always
  37523. * update the underlying WebGL uniform buffer to the GPU.
  37524. * @returns if Dynamic, otherwise false
  37525. */
  37526. UniformBuffer.prototype.isDynamic = function () {
  37527. return this._dynamic !== undefined;
  37528. };
  37529. /**
  37530. * The data cache on JS side.
  37531. * @returns the underlying data as a float array
  37532. */
  37533. UniformBuffer.prototype.getData = function () {
  37534. return this._bufferData;
  37535. };
  37536. /**
  37537. * The underlying WebGL Uniform buffer.
  37538. * @returns the webgl buffer
  37539. */
  37540. UniformBuffer.prototype.getBuffer = function () {
  37541. return this._buffer;
  37542. };
  37543. /**
  37544. * std140 layout specifies how to align data within an UBO structure.
  37545. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37546. * for specs.
  37547. */
  37548. UniformBuffer.prototype._fillAlignment = function (size) {
  37549. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37550. // and 4x4 matrices
  37551. // TODO : change if other types are used
  37552. var alignment;
  37553. if (size <= 2) {
  37554. alignment = size;
  37555. }
  37556. else {
  37557. alignment = 4;
  37558. }
  37559. if ((this._uniformLocationPointer % alignment) !== 0) {
  37560. var oldPointer = this._uniformLocationPointer;
  37561. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37562. var diff = this._uniformLocationPointer - oldPointer;
  37563. for (var i = 0; i < diff; i++) {
  37564. this._data.push(0);
  37565. }
  37566. }
  37567. };
  37568. /**
  37569. * Adds an uniform in the buffer.
  37570. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37571. * for the layout to be correct !
  37572. * @param name Name of the uniform, as used in the uniform block in the shader.
  37573. * @param size Data size, or data directly.
  37574. */
  37575. UniformBuffer.prototype.addUniform = function (name, size) {
  37576. if (this._noUBO) {
  37577. return;
  37578. }
  37579. if (this._uniformLocations[name] !== undefined) {
  37580. // Already existing uniform
  37581. return;
  37582. }
  37583. // This function must be called in the order of the shader layout !
  37584. // size can be the size of the uniform, or data directly
  37585. var data;
  37586. if (size instanceof Array) {
  37587. data = size;
  37588. size = data.length;
  37589. }
  37590. else {
  37591. size = size;
  37592. data = [];
  37593. // Fill with zeros
  37594. for (var i = 0; i < size; i++) {
  37595. data.push(0);
  37596. }
  37597. }
  37598. this._fillAlignment(size);
  37599. this._uniformSizes[name] = size;
  37600. this._uniformLocations[name] = this._uniformLocationPointer;
  37601. this._uniformLocationPointer += size;
  37602. for (var i = 0; i < size; i++) {
  37603. this._data.push(data[i]);
  37604. }
  37605. this._needSync = true;
  37606. };
  37607. /**
  37608. * Adds a Matrix 4x4 to the uniform buffer.
  37609. * @param name Name of the uniform, as used in the uniform block in the shader.
  37610. * @param mat A 4x4 matrix.
  37611. */
  37612. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37613. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37614. };
  37615. /**
  37616. * Adds a vec2 to the uniform buffer.
  37617. * @param name Name of the uniform, as used in the uniform block in the shader.
  37618. * @param x Define the x component value of the vec2
  37619. * @param y Define the y component value of the vec2
  37620. */
  37621. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37622. var temp = [x, y];
  37623. this.addUniform(name, temp);
  37624. };
  37625. /**
  37626. * Adds a vec3 to the uniform buffer.
  37627. * @param name Name of the uniform, as used in the uniform block in the shader.
  37628. * @param x Define the x component value of the vec3
  37629. * @param y Define the y component value of the vec3
  37630. * @param z Define the z component value of the vec3
  37631. */
  37632. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37633. var temp = [x, y, z];
  37634. this.addUniform(name, temp);
  37635. };
  37636. /**
  37637. * Adds a vec3 to the uniform buffer.
  37638. * @param name Name of the uniform, as used in the uniform block in the shader.
  37639. * @param color Define the vec3 from a Color
  37640. */
  37641. UniformBuffer.prototype.addColor3 = function (name, color) {
  37642. var temp = new Array();
  37643. color.toArray(temp);
  37644. this.addUniform(name, temp);
  37645. };
  37646. /**
  37647. * Adds a vec4 to the uniform buffer.
  37648. * @param name Name of the uniform, as used in the uniform block in the shader.
  37649. * @param color Define the rgb components from a Color
  37650. * @param alpha Define the a component of the vec4
  37651. */
  37652. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37653. var temp = new Array();
  37654. color.toArray(temp);
  37655. temp.push(alpha);
  37656. this.addUniform(name, temp);
  37657. };
  37658. /**
  37659. * Adds a vec3 to the uniform buffer.
  37660. * @param name Name of the uniform, as used in the uniform block in the shader.
  37661. * @param vector Define the vec3 components from a Vector
  37662. */
  37663. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37664. var temp = new Array();
  37665. vector.toArray(temp);
  37666. this.addUniform(name, temp);
  37667. };
  37668. /**
  37669. * Adds a Matrix 3x3 to the uniform buffer.
  37670. * @param name Name of the uniform, as used in the uniform block in the shader.
  37671. */
  37672. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37673. this.addUniform(name, 12);
  37674. };
  37675. /**
  37676. * Adds a Matrix 2x2 to the uniform buffer.
  37677. * @param name Name of the uniform, as used in the uniform block in the shader.
  37678. */
  37679. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37680. this.addUniform(name, 8);
  37681. };
  37682. /**
  37683. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37684. */
  37685. UniformBuffer.prototype.create = function () {
  37686. if (this._noUBO) {
  37687. return;
  37688. }
  37689. if (this._buffer) {
  37690. return; // nothing to do
  37691. }
  37692. // See spec, alignment must be filled as a vec4
  37693. this._fillAlignment(4);
  37694. this._bufferData = new Float32Array(this._data);
  37695. this._rebuild();
  37696. this._needSync = true;
  37697. };
  37698. /** @hidden */
  37699. UniformBuffer.prototype._rebuild = function () {
  37700. if (this._noUBO) {
  37701. return;
  37702. }
  37703. if (this._dynamic) {
  37704. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37705. }
  37706. else {
  37707. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37708. }
  37709. };
  37710. /**
  37711. * Updates the WebGL Uniform Buffer on the GPU.
  37712. * If the `dynamic` flag is set to true, no cache comparison is done.
  37713. * Otherwise, the buffer will be updated only if the cache differs.
  37714. */
  37715. UniformBuffer.prototype.update = function () {
  37716. if (!this._buffer) {
  37717. this.create();
  37718. return;
  37719. }
  37720. if (!this._dynamic && !this._needSync) {
  37721. return;
  37722. }
  37723. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37724. this._needSync = false;
  37725. };
  37726. /**
  37727. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37728. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37729. * @param data Define the flattened data
  37730. * @param size Define the size of the data.
  37731. */
  37732. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37733. var location = this._uniformLocations[uniformName];
  37734. if (location === undefined) {
  37735. if (this._buffer) {
  37736. // Cannot add an uniform if the buffer is already created
  37737. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37738. return;
  37739. }
  37740. this.addUniform(uniformName, size);
  37741. location = this._uniformLocations[uniformName];
  37742. }
  37743. if (!this._buffer) {
  37744. this.create();
  37745. }
  37746. if (!this._dynamic) {
  37747. // Cache for static uniform buffers
  37748. var changed = false;
  37749. for (var i = 0; i < size; i++) {
  37750. if (this._bufferData[location + i] !== data[i]) {
  37751. changed = true;
  37752. this._bufferData[location + i] = data[i];
  37753. }
  37754. }
  37755. this._needSync = this._needSync || changed;
  37756. }
  37757. else {
  37758. // No cache for dynamic
  37759. for (var i = 0; i < size; i++) {
  37760. this._bufferData[location + i] = data[i];
  37761. }
  37762. }
  37763. };
  37764. // Update methods
  37765. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37766. // To match std140, matrix must be realigned
  37767. for (var i = 0; i < 3; i++) {
  37768. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37769. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37770. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37771. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37772. }
  37773. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37774. };
  37775. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37776. this._currentEffect.setMatrix3x3(name, matrix);
  37777. };
  37778. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37779. this._currentEffect.setMatrix2x2(name, matrix);
  37780. };
  37781. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37782. // To match std140, matrix must be realigned
  37783. for (var i = 0; i < 2; i++) {
  37784. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37785. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37786. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37787. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37788. }
  37789. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37790. };
  37791. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37792. this._currentEffect.setFloat(name, x);
  37793. };
  37794. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37795. UniformBuffer._tempBuffer[0] = x;
  37796. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37797. };
  37798. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37799. if (suffix === void 0) { suffix = ""; }
  37800. this._currentEffect.setFloat2(name + suffix, x, y);
  37801. };
  37802. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37803. if (suffix === void 0) { suffix = ""; }
  37804. UniformBuffer._tempBuffer[0] = x;
  37805. UniformBuffer._tempBuffer[1] = y;
  37806. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37807. };
  37808. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37809. if (suffix === void 0) { suffix = ""; }
  37810. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37811. };
  37812. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37813. if (suffix === void 0) { suffix = ""; }
  37814. UniformBuffer._tempBuffer[0] = x;
  37815. UniformBuffer._tempBuffer[1] = y;
  37816. UniformBuffer._tempBuffer[2] = z;
  37817. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37818. };
  37819. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37820. if (suffix === void 0) { suffix = ""; }
  37821. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37822. };
  37823. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37824. if (suffix === void 0) { suffix = ""; }
  37825. UniformBuffer._tempBuffer[0] = x;
  37826. UniformBuffer._tempBuffer[1] = y;
  37827. UniformBuffer._tempBuffer[2] = z;
  37828. UniformBuffer._tempBuffer[3] = w;
  37829. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37830. };
  37831. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37832. this._currentEffect.setMatrix(name, mat);
  37833. };
  37834. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37835. this.updateUniform(name, mat.toArray(), 16);
  37836. };
  37837. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37838. this._currentEffect.setVector3(name, vector);
  37839. };
  37840. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37841. vector.toArray(UniformBuffer._tempBuffer);
  37842. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37843. };
  37844. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37845. this._currentEffect.setVector4(name, vector);
  37846. };
  37847. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37848. vector.toArray(UniformBuffer._tempBuffer);
  37849. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37850. };
  37851. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37852. if (suffix === void 0) { suffix = ""; }
  37853. this._currentEffect.setColor3(name + suffix, color);
  37854. };
  37855. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37856. if (suffix === void 0) { suffix = ""; }
  37857. color.toArray(UniformBuffer._tempBuffer);
  37858. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37859. };
  37860. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37861. if (suffix === void 0) { suffix = ""; }
  37862. this._currentEffect.setColor4(name + suffix, color, alpha);
  37863. };
  37864. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37865. if (suffix === void 0) { suffix = ""; }
  37866. color.toArray(UniformBuffer._tempBuffer);
  37867. UniformBuffer._tempBuffer[3] = alpha;
  37868. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37869. };
  37870. /**
  37871. * Sets a sampler uniform on the effect.
  37872. * @param name Define the name of the sampler.
  37873. * @param texture Define the texture to set in the sampler
  37874. */
  37875. UniformBuffer.prototype.setTexture = function (name, texture) {
  37876. this._currentEffect.setTexture(name, texture);
  37877. };
  37878. /**
  37879. * Directly updates the value of the uniform in the cache AND on the GPU.
  37880. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37881. * @param data Define the flattened data
  37882. */
  37883. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37884. this.updateUniform(uniformName, data, data.length);
  37885. this.update();
  37886. };
  37887. /**
  37888. * Binds this uniform buffer to an effect.
  37889. * @param effect Define the effect to bind the buffer to
  37890. * @param name Name of the uniform block in the shader.
  37891. */
  37892. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37893. this._currentEffect = effect;
  37894. if (this._noUBO || !this._buffer) {
  37895. return;
  37896. }
  37897. effect.bindUniformBuffer(this._buffer, name);
  37898. };
  37899. /**
  37900. * Disposes the uniform buffer.
  37901. */
  37902. UniformBuffer.prototype.dispose = function () {
  37903. if (this._noUBO) {
  37904. return;
  37905. }
  37906. var uniformBuffers = this._engine._uniformBuffers;
  37907. var index = uniformBuffers.indexOf(this);
  37908. if (index !== -1) {
  37909. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  37910. uniformBuffers.pop();
  37911. }
  37912. if (!this._buffer) {
  37913. return;
  37914. }
  37915. if (this._engine._releaseBuffer(this._buffer)) {
  37916. this._buffer = null;
  37917. }
  37918. };
  37919. // Pool for avoiding memory leaks
  37920. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37921. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37922. return UniformBuffer;
  37923. }());
  37924. BABYLON.UniformBuffer = UniformBuffer;
  37925. })(BABYLON || (BABYLON = {}));
  37926. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37927. var BABYLON;
  37928. (function (BABYLON) {
  37929. /**
  37930. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37931. */
  37932. var VertexData = /** @class */ (function () {
  37933. function VertexData() {
  37934. }
  37935. /**
  37936. * Uses the passed data array to set the set the values for the specified kind of data
  37937. * @param data a linear array of floating numbers
  37938. * @param kind the type of data that is being set, eg positions, colors etc
  37939. */
  37940. VertexData.prototype.set = function (data, kind) {
  37941. switch (kind) {
  37942. case BABYLON.VertexBuffer.PositionKind:
  37943. this.positions = data;
  37944. break;
  37945. case BABYLON.VertexBuffer.NormalKind:
  37946. this.normals = data;
  37947. break;
  37948. case BABYLON.VertexBuffer.TangentKind:
  37949. this.tangents = data;
  37950. break;
  37951. case BABYLON.VertexBuffer.UVKind:
  37952. this.uvs = data;
  37953. break;
  37954. case BABYLON.VertexBuffer.UV2Kind:
  37955. this.uvs2 = data;
  37956. break;
  37957. case BABYLON.VertexBuffer.UV3Kind:
  37958. this.uvs3 = data;
  37959. break;
  37960. case BABYLON.VertexBuffer.UV4Kind:
  37961. this.uvs4 = data;
  37962. break;
  37963. case BABYLON.VertexBuffer.UV5Kind:
  37964. this.uvs5 = data;
  37965. break;
  37966. case BABYLON.VertexBuffer.UV6Kind:
  37967. this.uvs6 = data;
  37968. break;
  37969. case BABYLON.VertexBuffer.ColorKind:
  37970. this.colors = data;
  37971. break;
  37972. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37973. this.matricesIndices = data;
  37974. break;
  37975. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37976. this.matricesWeights = data;
  37977. break;
  37978. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37979. this.matricesIndicesExtra = data;
  37980. break;
  37981. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37982. this.matricesWeightsExtra = data;
  37983. break;
  37984. }
  37985. };
  37986. /**
  37987. * Associates the vertexData to the passed Mesh.
  37988. * Sets it as updatable or not (default `false`)
  37989. * @param mesh the mesh the vertexData is applied to
  37990. * @param updatable when used and having the value true allows new data to update the vertexData
  37991. * @returns the VertexData
  37992. */
  37993. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37994. this._applyTo(mesh, updatable);
  37995. return this;
  37996. };
  37997. /**
  37998. * Associates the vertexData to the passed Geometry.
  37999. * Sets it as updatable or not (default `false`)
  38000. * @param geometry the geometry the vertexData is applied to
  38001. * @param updatable when used and having the value true allows new data to update the vertexData
  38002. * @returns VertexData
  38003. */
  38004. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38005. this._applyTo(geometry, updatable);
  38006. return this;
  38007. };
  38008. /**
  38009. * Updates the associated mesh
  38010. * @param mesh the mesh to be updated
  38011. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38012. * @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
  38013. * @returns VertexData
  38014. */
  38015. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38016. this._update(mesh);
  38017. return this;
  38018. };
  38019. /**
  38020. * Updates the associated geometry
  38021. * @param geometry the geometry to be updated
  38022. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38023. * @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
  38024. * @returns VertexData.
  38025. */
  38026. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38027. this._update(geometry);
  38028. return this;
  38029. };
  38030. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38031. if (updatable === void 0) { updatable = false; }
  38032. if (this.positions) {
  38033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38034. }
  38035. if (this.normals) {
  38036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38037. }
  38038. if (this.tangents) {
  38039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38040. }
  38041. if (this.uvs) {
  38042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38043. }
  38044. if (this.uvs2) {
  38045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38046. }
  38047. if (this.uvs3) {
  38048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38049. }
  38050. if (this.uvs4) {
  38051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38052. }
  38053. if (this.uvs5) {
  38054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38055. }
  38056. if (this.uvs6) {
  38057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38058. }
  38059. if (this.colors) {
  38060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38061. }
  38062. if (this.matricesIndices) {
  38063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38064. }
  38065. if (this.matricesWeights) {
  38066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38067. }
  38068. if (this.matricesIndicesExtra) {
  38069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38070. }
  38071. if (this.matricesWeightsExtra) {
  38072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38073. }
  38074. if (this.indices) {
  38075. meshOrGeometry.setIndices(this.indices, null, updatable);
  38076. }
  38077. else {
  38078. meshOrGeometry.setIndices([], null);
  38079. }
  38080. return this;
  38081. };
  38082. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38083. if (this.positions) {
  38084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38085. }
  38086. if (this.normals) {
  38087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38088. }
  38089. if (this.tangents) {
  38090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38091. }
  38092. if (this.uvs) {
  38093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38094. }
  38095. if (this.uvs2) {
  38096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38097. }
  38098. if (this.uvs3) {
  38099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38100. }
  38101. if (this.uvs4) {
  38102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38103. }
  38104. if (this.uvs5) {
  38105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38106. }
  38107. if (this.uvs6) {
  38108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38109. }
  38110. if (this.colors) {
  38111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38112. }
  38113. if (this.matricesIndices) {
  38114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38115. }
  38116. if (this.matricesWeights) {
  38117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38118. }
  38119. if (this.matricesIndicesExtra) {
  38120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38121. }
  38122. if (this.matricesWeightsExtra) {
  38123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38124. }
  38125. if (this.indices) {
  38126. meshOrGeometry.setIndices(this.indices, null);
  38127. }
  38128. return this;
  38129. };
  38130. /**
  38131. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38132. * @param matrix the transforming matrix
  38133. * @returns the VertexData
  38134. */
  38135. VertexData.prototype.transform = function (matrix) {
  38136. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38137. var transformed = BABYLON.Vector3.Zero();
  38138. var index;
  38139. if (this.positions) {
  38140. var position = BABYLON.Vector3.Zero();
  38141. for (index = 0; index < this.positions.length; index += 3) {
  38142. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38143. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38144. this.positions[index] = transformed.x;
  38145. this.positions[index + 1] = transformed.y;
  38146. this.positions[index + 2] = transformed.z;
  38147. }
  38148. }
  38149. if (this.normals) {
  38150. var normal = BABYLON.Vector3.Zero();
  38151. for (index = 0; index < this.normals.length; index += 3) {
  38152. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38153. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38154. this.normals[index] = transformed.x;
  38155. this.normals[index + 1] = transformed.y;
  38156. this.normals[index + 2] = transformed.z;
  38157. }
  38158. }
  38159. if (this.tangents) {
  38160. var tangent = BABYLON.Vector4.Zero();
  38161. var tangentTransformed = BABYLON.Vector4.Zero();
  38162. for (index = 0; index < this.tangents.length; index += 4) {
  38163. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38164. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38165. this.tangents[index] = tangentTransformed.x;
  38166. this.tangents[index + 1] = tangentTransformed.y;
  38167. this.tangents[index + 2] = tangentTransformed.z;
  38168. this.tangents[index + 3] = tangentTransformed.w;
  38169. }
  38170. }
  38171. if (flip && this.indices) {
  38172. for (index = 0; index < this.indices.length; index += 3) {
  38173. var tmp = this.indices[index + 1];
  38174. this.indices[index + 1] = this.indices[index + 2];
  38175. this.indices[index + 2] = tmp;
  38176. }
  38177. }
  38178. return this;
  38179. };
  38180. /**
  38181. * Merges the passed VertexData into the current one
  38182. * @param other the VertexData to be merged into the current one
  38183. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38184. * @returns the modified VertexData
  38185. */
  38186. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38187. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38188. this._validate();
  38189. other._validate();
  38190. if (!this.normals !== !other.normals ||
  38191. !this.tangents !== !other.tangents ||
  38192. !this.uvs !== !other.uvs ||
  38193. !this.uvs2 !== !other.uvs2 ||
  38194. !this.uvs3 !== !other.uvs3 ||
  38195. !this.uvs4 !== !other.uvs4 ||
  38196. !this.uvs5 !== !other.uvs5 ||
  38197. !this.uvs6 !== !other.uvs6 ||
  38198. !this.colors !== !other.colors ||
  38199. !this.matricesIndices !== !other.matricesIndices ||
  38200. !this.matricesWeights !== !other.matricesWeights ||
  38201. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38202. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38203. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38204. }
  38205. if (other.indices) {
  38206. if (!this.indices) {
  38207. this.indices = [];
  38208. }
  38209. var offset = this.positions ? this.positions.length / 3 : 0;
  38210. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38211. if (isSrcTypedArray) {
  38212. var len = this.indices.length + other.indices.length;
  38213. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38214. temp.set(this.indices);
  38215. var decal = this.indices.length;
  38216. for (var index = 0; index < other.indices.length; index++) {
  38217. temp[decal + index] = other.indices[index] + offset;
  38218. }
  38219. this.indices = temp;
  38220. }
  38221. else {
  38222. for (var index = 0; index < other.indices.length; index++) {
  38223. this.indices.push(other.indices[index] + offset);
  38224. }
  38225. }
  38226. }
  38227. this.positions = this._mergeElement(this.positions, other.positions);
  38228. this.normals = this._mergeElement(this.normals, other.normals);
  38229. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38230. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38231. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38232. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38233. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38234. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38235. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38236. this.colors = this._mergeElement(this.colors, other.colors);
  38237. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38238. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38239. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38240. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38241. return this;
  38242. };
  38243. VertexData.prototype._mergeElement = function (source, other) {
  38244. if (!source) {
  38245. return other;
  38246. }
  38247. if (!other) {
  38248. return source;
  38249. }
  38250. var len = other.length + source.length;
  38251. var isSrcTypedArray = source instanceof Float32Array;
  38252. var isOthTypedArray = other instanceof Float32Array;
  38253. // use non-loop method when the source is Float32Array
  38254. if (isSrcTypedArray) {
  38255. var ret32 = new Float32Array(len);
  38256. ret32.set(source);
  38257. ret32.set(other, source.length);
  38258. return ret32;
  38259. // source is number[], when other is also use concat
  38260. }
  38261. else if (!isOthTypedArray) {
  38262. return source.concat(other);
  38263. // source is a number[], but other is a Float32Array, loop required
  38264. }
  38265. else {
  38266. var ret = source.slice(0); // copy source to a separate array
  38267. for (var i = 0, len = other.length; i < len; i++) {
  38268. ret.push(other[i]);
  38269. }
  38270. return ret;
  38271. }
  38272. };
  38273. VertexData.prototype._validate = function () {
  38274. if (!this.positions) {
  38275. throw new Error("Positions are required");
  38276. }
  38277. var getElementCount = function (kind, values) {
  38278. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38279. if ((values.length % stride) !== 0) {
  38280. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38281. }
  38282. return values.length / stride;
  38283. };
  38284. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38285. var validateElementCount = function (kind, values) {
  38286. var elementCount = getElementCount(kind, values);
  38287. if (elementCount !== positionsElementCount) {
  38288. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38289. }
  38290. };
  38291. if (this.normals) {
  38292. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38293. }
  38294. if (this.tangents) {
  38295. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38296. }
  38297. if (this.uvs) {
  38298. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38299. }
  38300. if (this.uvs2) {
  38301. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38302. }
  38303. if (this.uvs3) {
  38304. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38305. }
  38306. if (this.uvs4) {
  38307. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38308. }
  38309. if (this.uvs5) {
  38310. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38311. }
  38312. if (this.uvs6) {
  38313. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38314. }
  38315. if (this.colors) {
  38316. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38317. }
  38318. if (this.matricesIndices) {
  38319. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38320. }
  38321. if (this.matricesWeights) {
  38322. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38323. }
  38324. if (this.matricesIndicesExtra) {
  38325. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38326. }
  38327. if (this.matricesWeightsExtra) {
  38328. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38329. }
  38330. };
  38331. /**
  38332. * Serializes the VertexData
  38333. * @returns a serialized object
  38334. */
  38335. VertexData.prototype.serialize = function () {
  38336. var serializationObject = this.serialize();
  38337. if (this.positions) {
  38338. serializationObject.positions = this.positions;
  38339. }
  38340. if (this.normals) {
  38341. serializationObject.normals = this.normals;
  38342. }
  38343. if (this.tangents) {
  38344. serializationObject.tangents = this.tangents;
  38345. }
  38346. if (this.uvs) {
  38347. serializationObject.uvs = this.uvs;
  38348. }
  38349. if (this.uvs2) {
  38350. serializationObject.uvs2 = this.uvs2;
  38351. }
  38352. if (this.uvs3) {
  38353. serializationObject.uvs3 = this.uvs3;
  38354. }
  38355. if (this.uvs4) {
  38356. serializationObject.uvs4 = this.uvs4;
  38357. }
  38358. if (this.uvs5) {
  38359. serializationObject.uvs5 = this.uvs5;
  38360. }
  38361. if (this.uvs6) {
  38362. serializationObject.uvs6 = this.uvs6;
  38363. }
  38364. if (this.colors) {
  38365. serializationObject.colors = this.colors;
  38366. }
  38367. if (this.matricesIndices) {
  38368. serializationObject.matricesIndices = this.matricesIndices;
  38369. serializationObject.matricesIndices._isExpanded = true;
  38370. }
  38371. if (this.matricesWeights) {
  38372. serializationObject.matricesWeights = this.matricesWeights;
  38373. }
  38374. if (this.matricesIndicesExtra) {
  38375. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38376. serializationObject.matricesIndicesExtra._isExpanded = true;
  38377. }
  38378. if (this.matricesWeightsExtra) {
  38379. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38380. }
  38381. serializationObject.indices = this.indices;
  38382. return serializationObject;
  38383. };
  38384. // Statics
  38385. /**
  38386. * Extracts the vertexData from a mesh
  38387. * @param mesh the mesh from which to extract the VertexData
  38388. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38389. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38390. * @returns the object VertexData associated to the passed mesh
  38391. */
  38392. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38393. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38394. };
  38395. /**
  38396. * Extracts the vertexData from the geometry
  38397. * @param geometry the geometry from which to extract the VertexData
  38398. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38399. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38400. * @returns the object VertexData associated to the passed mesh
  38401. */
  38402. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38403. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38404. };
  38405. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38406. var result = new VertexData();
  38407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38408. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38409. }
  38410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38411. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38412. }
  38413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38414. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38415. }
  38416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38417. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38418. }
  38419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38420. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38421. }
  38422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38423. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38424. }
  38425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38426. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38427. }
  38428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38429. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38430. }
  38431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38432. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38433. }
  38434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38435. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38436. }
  38437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38438. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38439. }
  38440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38441. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38442. }
  38443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38444. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38445. }
  38446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38447. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38448. }
  38449. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38450. return result;
  38451. };
  38452. /**
  38453. * Creates the VertexData for a Ribbon
  38454. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38455. * * pathArray array of paths, each of which an array of successive Vector3
  38456. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38457. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38458. * * 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
  38459. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38460. * * 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)
  38461. * * 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)
  38462. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38463. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38464. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38465. * @returns the VertexData of the ribbon
  38466. */
  38467. VertexData.CreateRibbon = function (options) {
  38468. var pathArray = options.pathArray;
  38469. var closeArray = options.closeArray || false;
  38470. var closePath = options.closePath || false;
  38471. var invertUV = options.invertUV || false;
  38472. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38473. var offset = options.offset || defaultOffset;
  38474. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38476. var customUV = options.uvs;
  38477. var customColors = options.colors;
  38478. var positions = [];
  38479. var indices = [];
  38480. var normals = [];
  38481. var uvs = [];
  38482. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38483. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38484. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38485. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38486. var minlg; // minimal length among all paths from pathArray
  38487. var lg = []; // array of path lengths : nb of vertex per path
  38488. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38489. var p; // path iterator
  38490. var i; // point iterator
  38491. var j; // point iterator
  38492. // if single path in pathArray
  38493. if (pathArray.length < 2) {
  38494. var ar1 = [];
  38495. var ar2 = [];
  38496. for (i = 0; i < pathArray[0].length - offset; i++) {
  38497. ar1.push(pathArray[0][i]);
  38498. ar2.push(pathArray[0][i + offset]);
  38499. }
  38500. pathArray = [ar1, ar2];
  38501. }
  38502. // positions and horizontal distances (u)
  38503. var idc = 0;
  38504. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38505. var path;
  38506. var l;
  38507. minlg = pathArray[0].length;
  38508. var vectlg;
  38509. var dist;
  38510. for (p = 0; p < pathArray.length; p++) {
  38511. uTotalDistance[p] = 0;
  38512. us[p] = [0];
  38513. path = pathArray[p];
  38514. l = path.length;
  38515. minlg = (minlg < l) ? minlg : l;
  38516. j = 0;
  38517. while (j < l) {
  38518. positions.push(path[j].x, path[j].y, path[j].z);
  38519. if (j > 0) {
  38520. vectlg = path[j].subtract(path[j - 1]).length();
  38521. dist = vectlg + uTotalDistance[p];
  38522. us[p].push(dist);
  38523. uTotalDistance[p] = dist;
  38524. }
  38525. j++;
  38526. }
  38527. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38528. j--;
  38529. positions.push(path[0].x, path[0].y, path[0].z);
  38530. vectlg = path[j].subtract(path[0]).length();
  38531. dist = vectlg + uTotalDistance[p];
  38532. us[p].push(dist);
  38533. uTotalDistance[p] = dist;
  38534. }
  38535. lg[p] = l + closePathCorr;
  38536. idx[p] = idc;
  38537. idc += (l + closePathCorr);
  38538. }
  38539. // vertical distances (v)
  38540. var path1;
  38541. var path2;
  38542. var vertex1 = null;
  38543. var vertex2 = null;
  38544. for (i = 0; i < minlg + closePathCorr; i++) {
  38545. vTotalDistance[i] = 0;
  38546. vs[i] = [0];
  38547. for (p = 0; p < pathArray.length - 1; p++) {
  38548. path1 = pathArray[p];
  38549. path2 = pathArray[p + 1];
  38550. if (i === minlg) { // closePath
  38551. vertex1 = path1[0];
  38552. vertex2 = path2[0];
  38553. }
  38554. else {
  38555. vertex1 = path1[i];
  38556. vertex2 = path2[i];
  38557. }
  38558. vectlg = vertex2.subtract(vertex1).length();
  38559. dist = vectlg + vTotalDistance[i];
  38560. vs[i].push(dist);
  38561. vTotalDistance[i] = dist;
  38562. }
  38563. if (closeArray && vertex2 && vertex1) {
  38564. path1 = pathArray[p];
  38565. path2 = pathArray[0];
  38566. if (i === minlg) { // closePath
  38567. vertex2 = path2[0];
  38568. }
  38569. vectlg = vertex2.subtract(vertex1).length();
  38570. dist = vectlg + vTotalDistance[i];
  38571. vTotalDistance[i] = dist;
  38572. }
  38573. }
  38574. // uvs
  38575. var u;
  38576. var v;
  38577. if (customUV) {
  38578. for (p = 0; p < customUV.length; p++) {
  38579. uvs.push(customUV[p].x, customUV[p].y);
  38580. }
  38581. }
  38582. else {
  38583. for (p = 0; p < pathArray.length; p++) {
  38584. for (i = 0; i < minlg + closePathCorr; i++) {
  38585. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38586. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38587. if (invertUV) {
  38588. uvs.push(v, u);
  38589. }
  38590. else {
  38591. uvs.push(u, v);
  38592. }
  38593. }
  38594. }
  38595. }
  38596. // indices
  38597. p = 0; // path index
  38598. var pi = 0; // positions array index
  38599. var l1 = lg[p] - 1; // path1 length
  38600. var l2 = lg[p + 1] - 1; // path2 length
  38601. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38602. var shft = idx[1] - idx[0]; // shift
  38603. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38604. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38605. // 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
  38606. indices.push(pi, pi + shft, pi + 1);
  38607. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38608. pi += 1;
  38609. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38610. p++;
  38611. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38612. shft = idx[0] - idx[p];
  38613. l1 = lg[p] - 1;
  38614. l2 = lg[0] - 1;
  38615. }
  38616. else {
  38617. shft = idx[p + 1] - idx[p];
  38618. l1 = lg[p] - 1;
  38619. l2 = lg[p + 1] - 1;
  38620. }
  38621. pi = idx[p];
  38622. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38623. }
  38624. }
  38625. // normals
  38626. VertexData.ComputeNormals(positions, indices, normals);
  38627. if (closePath) { // update both the first and last vertex normals to their average value
  38628. var indexFirst = 0;
  38629. var indexLast = 0;
  38630. for (p = 0; p < pathArray.length; p++) {
  38631. indexFirst = idx[p] * 3;
  38632. if (p + 1 < pathArray.length) {
  38633. indexLast = (idx[p + 1] - 1) * 3;
  38634. }
  38635. else {
  38636. indexLast = normals.length - 3;
  38637. }
  38638. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38639. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38640. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38641. normals[indexLast] = normals[indexFirst];
  38642. normals[indexLast + 1] = normals[indexFirst + 1];
  38643. normals[indexLast + 2] = normals[indexFirst + 2];
  38644. }
  38645. }
  38646. // sides
  38647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38648. // Colors
  38649. var colors = null;
  38650. if (customColors) {
  38651. colors = new Float32Array(customColors.length * 4);
  38652. for (var c = 0; c < customColors.length; c++) {
  38653. colors[c * 4] = customColors[c].r;
  38654. colors[c * 4 + 1] = customColors[c].g;
  38655. colors[c * 4 + 2] = customColors[c].b;
  38656. colors[c * 4 + 3] = customColors[c].a;
  38657. }
  38658. }
  38659. // Result
  38660. var vertexData = new VertexData();
  38661. var positions32 = new Float32Array(positions);
  38662. var normals32 = new Float32Array(normals);
  38663. var uvs32 = new Float32Array(uvs);
  38664. vertexData.indices = indices;
  38665. vertexData.positions = positions32;
  38666. vertexData.normals = normals32;
  38667. vertexData.uvs = uvs32;
  38668. if (colors) {
  38669. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38670. }
  38671. if (closePath) {
  38672. vertexData._idx = idx;
  38673. }
  38674. return vertexData;
  38675. };
  38676. /**
  38677. * Creates the VertexData for a box
  38678. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38679. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38680. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38681. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38682. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38683. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38684. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38685. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38686. * * 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)
  38687. * * 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)
  38688. * @returns the VertexData of the box
  38689. */
  38690. VertexData.CreateBox = function (options) {
  38691. var normalsSource = [
  38692. new BABYLON.Vector3(0, 0, 1),
  38693. new BABYLON.Vector3(0, 0, -1),
  38694. new BABYLON.Vector3(1, 0, 0),
  38695. new BABYLON.Vector3(-1, 0, 0),
  38696. new BABYLON.Vector3(0, 1, 0),
  38697. new BABYLON.Vector3(0, -1, 0)
  38698. ];
  38699. var indices = [];
  38700. var positions = [];
  38701. var normals = [];
  38702. var uvs = [];
  38703. var width = options.width || options.size || 1;
  38704. var height = options.height || options.size || 1;
  38705. var depth = options.depth || options.size || 1;
  38706. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38707. var faceUV = options.faceUV || new Array(6);
  38708. var faceColors = options.faceColors;
  38709. var colors = [];
  38710. // default face colors and UV if undefined
  38711. for (var f = 0; f < 6; f++) {
  38712. if (faceUV[f] === undefined) {
  38713. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38714. }
  38715. if (faceColors && faceColors[f] === undefined) {
  38716. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38717. }
  38718. }
  38719. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38720. // Create each face in turn.
  38721. for (var index = 0; index < normalsSource.length; index++) {
  38722. var normal = normalsSource[index];
  38723. // Get two vectors perpendicular to the face normal and to each other.
  38724. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38725. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38726. // Six indices (two triangles) per face.
  38727. var verticesLength = positions.length / 3;
  38728. indices.push(verticesLength);
  38729. indices.push(verticesLength + 1);
  38730. indices.push(verticesLength + 2);
  38731. indices.push(verticesLength);
  38732. indices.push(verticesLength + 2);
  38733. indices.push(verticesLength + 3);
  38734. // Four vertices per face.
  38735. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38736. positions.push(vertex.x, vertex.y, vertex.z);
  38737. normals.push(normal.x, normal.y, normal.z);
  38738. uvs.push(faceUV[index].z, faceUV[index].w);
  38739. if (faceColors) {
  38740. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38741. }
  38742. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38743. positions.push(vertex.x, vertex.y, vertex.z);
  38744. normals.push(normal.x, normal.y, normal.z);
  38745. uvs.push(faceUV[index].x, faceUV[index].w);
  38746. if (faceColors) {
  38747. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38748. }
  38749. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38750. positions.push(vertex.x, vertex.y, vertex.z);
  38751. normals.push(normal.x, normal.y, normal.z);
  38752. uvs.push(faceUV[index].x, faceUV[index].y);
  38753. if (faceColors) {
  38754. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38755. }
  38756. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38757. positions.push(vertex.x, vertex.y, vertex.z);
  38758. normals.push(normal.x, normal.y, normal.z);
  38759. uvs.push(faceUV[index].z, faceUV[index].y);
  38760. if (faceColors) {
  38761. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38762. }
  38763. }
  38764. // sides
  38765. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38766. // Result
  38767. var vertexData = new VertexData();
  38768. vertexData.indices = indices;
  38769. vertexData.positions = positions;
  38770. vertexData.normals = normals;
  38771. vertexData.uvs = uvs;
  38772. if (faceColors) {
  38773. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38774. vertexData.colors = totalColors;
  38775. }
  38776. return vertexData;
  38777. };
  38778. /**
  38779. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38780. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38781. * * segments sets the number of horizontal strips optional, default 32
  38782. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38783. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38784. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38785. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38786. * * 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
  38787. * * 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
  38788. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38789. * * 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)
  38790. * * 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)
  38791. * @returns the VertexData of the ellipsoid
  38792. */
  38793. VertexData.CreateSphere = function (options) {
  38794. var segments = options.segments || 32;
  38795. var diameterX = options.diameterX || options.diameter || 1;
  38796. var diameterY = options.diameterY || options.diameter || 1;
  38797. var diameterZ = options.diameterZ || options.diameter || 1;
  38798. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38799. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38801. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38802. var totalZRotationSteps = 2 + segments;
  38803. var totalYRotationSteps = 2 * totalZRotationSteps;
  38804. var indices = [];
  38805. var positions = [];
  38806. var normals = [];
  38807. var uvs = [];
  38808. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38809. var normalizedZ = zRotationStep / totalZRotationSteps;
  38810. var angleZ = normalizedZ * Math.PI * slice;
  38811. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38812. var normalizedY = yRotationStep / totalYRotationSteps;
  38813. var angleY = normalizedY * Math.PI * 2 * arc;
  38814. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38815. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38816. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38817. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38818. var vertex = complete.multiply(radius);
  38819. var normal = complete.divide(radius).normalize();
  38820. positions.push(vertex.x, vertex.y, vertex.z);
  38821. normals.push(normal.x, normal.y, normal.z);
  38822. uvs.push(normalizedY, normalizedZ);
  38823. }
  38824. if (zRotationStep > 0) {
  38825. var verticesCount = positions.length / 3;
  38826. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38827. indices.push((firstIndex));
  38828. indices.push((firstIndex + 1));
  38829. indices.push(firstIndex + totalYRotationSteps + 1);
  38830. indices.push((firstIndex + totalYRotationSteps + 1));
  38831. indices.push((firstIndex + 1));
  38832. indices.push((firstIndex + totalYRotationSteps + 2));
  38833. }
  38834. }
  38835. }
  38836. // Sides
  38837. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38838. // Result
  38839. var vertexData = new VertexData();
  38840. vertexData.indices = indices;
  38841. vertexData.positions = positions;
  38842. vertexData.normals = normals;
  38843. vertexData.uvs = uvs;
  38844. return vertexData;
  38845. };
  38846. /**
  38847. * Creates the VertexData for a cylinder, cone or prism
  38848. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38849. * * height sets the height (y direction) of the cylinder, optional, default 2
  38850. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38851. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38852. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38853. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38854. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38855. * * 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
  38856. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38857. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38858. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38859. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38860. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38861. * * 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)
  38862. * * 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)
  38863. * @returns the VertexData of the cylinder, cone or prism
  38864. */
  38865. VertexData.CreateCylinder = function (options) {
  38866. var height = options.height || 2;
  38867. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38868. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38869. var tessellation = options.tessellation || 24;
  38870. var subdivisions = options.subdivisions || 1;
  38871. var hasRings = options.hasRings ? true : false;
  38872. var enclose = options.enclose ? true : false;
  38873. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38875. var faceUV = options.faceUV || new Array(3);
  38876. var faceColors = options.faceColors;
  38877. // default face colors and UV if undefined
  38878. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38879. var ringNb = (hasRings) ? subdivisions : 1;
  38880. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38881. var f;
  38882. for (f = 0; f < surfaceNb; f++) {
  38883. if (faceColors && faceColors[f] === undefined) {
  38884. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38885. }
  38886. }
  38887. for (f = 0; f < surfaceNb; f++) {
  38888. if (faceUV && faceUV[f] === undefined) {
  38889. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38890. }
  38891. }
  38892. var indices = new Array();
  38893. var positions = new Array();
  38894. var normals = new Array();
  38895. var uvs = new Array();
  38896. var colors = new Array();
  38897. var angle_step = Math.PI * 2 * arc / tessellation;
  38898. var angle;
  38899. var h;
  38900. var radius;
  38901. var tan = (diameterBottom - diameterTop) / 2 / height;
  38902. var ringVertex = BABYLON.Vector3.Zero();
  38903. var ringNormal = BABYLON.Vector3.Zero();
  38904. var ringFirstVertex = BABYLON.Vector3.Zero();
  38905. var ringFirstNormal = BABYLON.Vector3.Zero();
  38906. var quadNormal = BABYLON.Vector3.Zero();
  38907. var Y = BABYLON.Axis.Y;
  38908. // positions, normals, uvs
  38909. var i;
  38910. var j;
  38911. var r;
  38912. var ringIdx = 1;
  38913. var s = 1; // surface index
  38914. var cs = 0;
  38915. var v = 0;
  38916. for (i = 0; i <= subdivisions; i++) {
  38917. h = i / subdivisions;
  38918. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38919. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38920. for (r = 0; r < ringIdx; r++) {
  38921. if (hasRings) {
  38922. s += r;
  38923. }
  38924. if (enclose) {
  38925. s += 2 * r;
  38926. }
  38927. for (j = 0; j <= tessellation; j++) {
  38928. angle = j * angle_step;
  38929. // position
  38930. ringVertex.x = Math.cos(-angle) * radius;
  38931. ringVertex.y = -height / 2 + h * height;
  38932. ringVertex.z = Math.sin(-angle) * radius;
  38933. // normal
  38934. if (diameterTop === 0 && i === subdivisions) {
  38935. // if no top cap, reuse former normals
  38936. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38937. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38938. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38939. }
  38940. else {
  38941. ringNormal.x = ringVertex.x;
  38942. ringNormal.z = ringVertex.z;
  38943. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38944. ringNormal.normalize();
  38945. }
  38946. // keep first ring vertex values for enclose
  38947. if (j === 0) {
  38948. ringFirstVertex.copyFrom(ringVertex);
  38949. ringFirstNormal.copyFrom(ringNormal);
  38950. }
  38951. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38952. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38953. if (hasRings) {
  38954. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38955. }
  38956. else {
  38957. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38958. }
  38959. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38960. if (faceColors) {
  38961. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38962. }
  38963. }
  38964. // if enclose, add four vertices and their dedicated normals
  38965. if (arc !== 1 && enclose) {
  38966. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38967. positions.push(0, ringVertex.y, 0);
  38968. positions.push(0, ringVertex.y, 0);
  38969. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38970. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38971. quadNormal.normalize();
  38972. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38973. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38974. quadNormal.normalize();
  38975. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38976. if (hasRings) {
  38977. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38978. }
  38979. else {
  38980. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38981. }
  38982. uvs.push(faceUV[s + 1].x, v);
  38983. uvs.push(faceUV[s + 1].z, v);
  38984. if (hasRings) {
  38985. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38986. }
  38987. else {
  38988. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38989. }
  38990. uvs.push(faceUV[s + 2].x, v);
  38991. uvs.push(faceUV[s + 2].z, v);
  38992. if (faceColors) {
  38993. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38994. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38995. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38996. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38997. }
  38998. }
  38999. if (cs !== s) {
  39000. cs = s;
  39001. }
  39002. }
  39003. }
  39004. // indices
  39005. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39006. var s;
  39007. i = 0;
  39008. for (s = 0; s < subdivisions; s++) {
  39009. var i0 = 0;
  39010. var i1 = 0;
  39011. var i2 = 0;
  39012. var i3 = 0;
  39013. for (j = 0; j < tessellation; j++) {
  39014. i0 = i * (e + 1) + j;
  39015. i1 = (i + 1) * (e + 1) + j;
  39016. i2 = i * (e + 1) + (j + 1);
  39017. i3 = (i + 1) * (e + 1) + (j + 1);
  39018. indices.push(i0, i1, i2);
  39019. indices.push(i3, i2, i1);
  39020. }
  39021. if (arc !== 1 && enclose) { // if enclose, add two quads
  39022. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39023. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39024. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39025. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39026. }
  39027. i = (hasRings) ? (i + 2) : (i + 1);
  39028. }
  39029. // Caps
  39030. var createCylinderCap = function (isTop) {
  39031. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39032. if (radius === 0) {
  39033. return;
  39034. }
  39035. // Cap positions, normals & uvs
  39036. var angle;
  39037. var circleVector;
  39038. var i;
  39039. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39040. var c = null;
  39041. if (faceColors) {
  39042. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39043. }
  39044. // cap center
  39045. var vbase = positions.length / 3;
  39046. var offset = isTop ? height / 2 : -height / 2;
  39047. var center = new BABYLON.Vector3(0, offset, 0);
  39048. positions.push(center.x, center.y, center.z);
  39049. normals.push(0, isTop ? 1 : -1, 0);
  39050. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39051. if (c) {
  39052. colors.push(c.r, c.g, c.b, c.a);
  39053. }
  39054. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39055. for (i = 0; i <= tessellation; i++) {
  39056. angle = Math.PI * 2 * i * arc / tessellation;
  39057. var cos = Math.cos(-angle);
  39058. var sin = Math.sin(-angle);
  39059. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39060. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39061. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39062. normals.push(0, isTop ? 1 : -1, 0);
  39063. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39064. if (c) {
  39065. colors.push(c.r, c.g, c.b, c.a);
  39066. }
  39067. }
  39068. // Cap indices
  39069. for (i = 0; i < tessellation; i++) {
  39070. if (!isTop) {
  39071. indices.push(vbase);
  39072. indices.push(vbase + (i + 1));
  39073. indices.push(vbase + (i + 2));
  39074. }
  39075. else {
  39076. indices.push(vbase);
  39077. indices.push(vbase + (i + 2));
  39078. indices.push(vbase + (i + 1));
  39079. }
  39080. }
  39081. };
  39082. // add caps to geometry
  39083. createCylinderCap(false);
  39084. createCylinderCap(true);
  39085. // Sides
  39086. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39087. var vertexData = new VertexData();
  39088. vertexData.indices = indices;
  39089. vertexData.positions = positions;
  39090. vertexData.normals = normals;
  39091. vertexData.uvs = uvs;
  39092. if (faceColors) {
  39093. vertexData.colors = colors;
  39094. }
  39095. return vertexData;
  39096. };
  39097. /**
  39098. * Creates the VertexData for a torus
  39099. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39100. * * diameter the diameter of the torus, optional default 1
  39101. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39102. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39103. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39104. * * 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)
  39105. * * 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)
  39106. * @returns the VertexData of the torus
  39107. */
  39108. VertexData.CreateTorus = function (options) {
  39109. var indices = [];
  39110. var positions = [];
  39111. var normals = [];
  39112. var uvs = [];
  39113. var diameter = options.diameter || 1;
  39114. var thickness = options.thickness || 0.5;
  39115. var tessellation = options.tessellation || 16;
  39116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39117. var stride = tessellation + 1;
  39118. for (var i = 0; i <= tessellation; i++) {
  39119. var u = i / tessellation;
  39120. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39121. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39122. for (var j = 0; j <= tessellation; j++) {
  39123. var v = 1 - j / tessellation;
  39124. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39125. var dx = Math.cos(innerAngle);
  39126. var dy = Math.sin(innerAngle);
  39127. // Create a vertex.
  39128. var normal = new BABYLON.Vector3(dx, dy, 0);
  39129. var position = normal.scale(thickness / 2);
  39130. var textureCoordinate = new BABYLON.Vector2(u, v);
  39131. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39132. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39133. positions.push(position.x, position.y, position.z);
  39134. normals.push(normal.x, normal.y, normal.z);
  39135. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39136. // And create indices for two triangles.
  39137. var nextI = (i + 1) % stride;
  39138. var nextJ = (j + 1) % stride;
  39139. indices.push(i * stride + j);
  39140. indices.push(i * stride + nextJ);
  39141. indices.push(nextI * stride + j);
  39142. indices.push(i * stride + nextJ);
  39143. indices.push(nextI * stride + nextJ);
  39144. indices.push(nextI * stride + j);
  39145. }
  39146. }
  39147. // Sides
  39148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39149. // Result
  39150. var vertexData = new VertexData();
  39151. vertexData.indices = indices;
  39152. vertexData.positions = positions;
  39153. vertexData.normals = normals;
  39154. vertexData.uvs = uvs;
  39155. return vertexData;
  39156. };
  39157. /**
  39158. * Creates the VertexData of the LineSystem
  39159. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39160. * - lines an array of lines, each line being an array of successive Vector3
  39161. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39162. * @returns the VertexData of the LineSystem
  39163. */
  39164. VertexData.CreateLineSystem = function (options) {
  39165. var indices = [];
  39166. var positions = [];
  39167. var lines = options.lines;
  39168. var colors = options.colors;
  39169. var vertexColors = [];
  39170. var idx = 0;
  39171. for (var l = 0; l < lines.length; l++) {
  39172. var points = lines[l];
  39173. for (var index = 0; index < points.length; index++) {
  39174. positions.push(points[index].x, points[index].y, points[index].z);
  39175. if (colors) {
  39176. var color = colors[l];
  39177. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39178. }
  39179. if (index > 0) {
  39180. indices.push(idx - 1);
  39181. indices.push(idx);
  39182. }
  39183. idx++;
  39184. }
  39185. }
  39186. var vertexData = new VertexData();
  39187. vertexData.indices = indices;
  39188. vertexData.positions = positions;
  39189. if (colors) {
  39190. vertexData.colors = vertexColors;
  39191. }
  39192. return vertexData;
  39193. };
  39194. /**
  39195. * Create the VertexData for a DashedLines
  39196. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39197. * - points an array successive Vector3
  39198. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39199. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39200. * - dashNb the intended total number of dashes, optional, default 200
  39201. * @returns the VertexData for the DashedLines
  39202. */
  39203. VertexData.CreateDashedLines = function (options) {
  39204. var dashSize = options.dashSize || 3;
  39205. var gapSize = options.gapSize || 1;
  39206. var dashNb = options.dashNb || 200;
  39207. var points = options.points;
  39208. var positions = new Array();
  39209. var indices = new Array();
  39210. var curvect = BABYLON.Vector3.Zero();
  39211. var lg = 0;
  39212. var nb = 0;
  39213. var shft = 0;
  39214. var dashshft = 0;
  39215. var curshft = 0;
  39216. var idx = 0;
  39217. var i = 0;
  39218. for (i = 0; i < points.length - 1; i++) {
  39219. points[i + 1].subtractToRef(points[i], curvect);
  39220. lg += curvect.length();
  39221. }
  39222. shft = lg / dashNb;
  39223. dashshft = dashSize * shft / (dashSize + gapSize);
  39224. for (i = 0; i < points.length - 1; i++) {
  39225. points[i + 1].subtractToRef(points[i], curvect);
  39226. nb = Math.floor(curvect.length() / shft);
  39227. curvect.normalize();
  39228. for (var j = 0; j < nb; j++) {
  39229. curshft = shft * j;
  39230. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39231. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39232. indices.push(idx, idx + 1);
  39233. idx += 2;
  39234. }
  39235. }
  39236. // Result
  39237. var vertexData = new VertexData();
  39238. vertexData.positions = positions;
  39239. vertexData.indices = indices;
  39240. return vertexData;
  39241. };
  39242. /**
  39243. * Creates the VertexData for a Ground
  39244. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39245. * - width the width (x direction) of the ground, optional, default 1
  39246. * - height the height (z direction) of the ground, optional, default 1
  39247. * - subdivisions the number of subdivisions per side, optional, default 1
  39248. * @returns the VertexData of the Ground
  39249. */
  39250. VertexData.CreateGround = function (options) {
  39251. var indices = [];
  39252. var positions = [];
  39253. var normals = [];
  39254. var uvs = [];
  39255. var row, col;
  39256. var width = options.width || 1;
  39257. var height = options.height || 1;
  39258. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39259. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39260. for (row = 0; row <= subdivisionsY; row++) {
  39261. for (col = 0; col <= subdivisionsX; col++) {
  39262. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39263. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39264. positions.push(position.x, position.y, position.z);
  39265. normals.push(normal.x, normal.y, normal.z);
  39266. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39267. }
  39268. }
  39269. for (row = 0; row < subdivisionsY; row++) {
  39270. for (col = 0; col < subdivisionsX; col++) {
  39271. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39272. indices.push(col + 1 + row * (subdivisionsX + 1));
  39273. indices.push(col + row * (subdivisionsX + 1));
  39274. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39275. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39276. indices.push(col + row * (subdivisionsX + 1));
  39277. }
  39278. }
  39279. // Result
  39280. var vertexData = new VertexData();
  39281. vertexData.indices = indices;
  39282. vertexData.positions = positions;
  39283. vertexData.normals = normals;
  39284. vertexData.uvs = uvs;
  39285. return vertexData;
  39286. };
  39287. /**
  39288. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39289. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39290. * * xmin the ground minimum X coordinate, optional, default -1
  39291. * * zmin the ground minimum Z coordinate, optional, default -1
  39292. * * xmax the ground maximum X coordinate, optional, default 1
  39293. * * zmax the ground maximum Z coordinate, optional, default 1
  39294. * * 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}
  39295. * * 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}
  39296. * @returns the VertexData of the TiledGround
  39297. */
  39298. VertexData.CreateTiledGround = function (options) {
  39299. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39300. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39301. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39302. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39303. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39304. var precision = options.precision || { w: 1, h: 1 };
  39305. var indices = new Array();
  39306. var positions = new Array();
  39307. var normals = new Array();
  39308. var uvs = new Array();
  39309. var row, col, tileRow, tileCol;
  39310. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39311. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39312. precision.w = (precision.w < 1) ? 1 : precision.w;
  39313. precision.h = (precision.h < 1) ? 1 : precision.h;
  39314. var tileSize = {
  39315. 'w': (xmax - xmin) / subdivisions.w,
  39316. 'h': (zmax - zmin) / subdivisions.h
  39317. };
  39318. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39319. // Indices
  39320. var base = positions.length / 3;
  39321. var rowLength = precision.w + 1;
  39322. for (row = 0; row < precision.h; row++) {
  39323. for (col = 0; col < precision.w; col++) {
  39324. var square = [
  39325. base + col + row * rowLength,
  39326. base + (col + 1) + row * rowLength,
  39327. base + (col + 1) + (row + 1) * rowLength,
  39328. base + col + (row + 1) * rowLength
  39329. ];
  39330. indices.push(square[1]);
  39331. indices.push(square[2]);
  39332. indices.push(square[3]);
  39333. indices.push(square[0]);
  39334. indices.push(square[1]);
  39335. indices.push(square[3]);
  39336. }
  39337. }
  39338. // Position, normals and uvs
  39339. var position = BABYLON.Vector3.Zero();
  39340. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39341. for (row = 0; row <= precision.h; row++) {
  39342. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39343. for (col = 0; col <= precision.w; col++) {
  39344. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39345. position.y = 0;
  39346. positions.push(position.x, position.y, position.z);
  39347. normals.push(normal.x, normal.y, normal.z);
  39348. uvs.push(col / precision.w, row / precision.h);
  39349. }
  39350. }
  39351. }
  39352. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39353. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39354. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39355. }
  39356. }
  39357. // Result
  39358. var vertexData = new VertexData();
  39359. vertexData.indices = indices;
  39360. vertexData.positions = positions;
  39361. vertexData.normals = normals;
  39362. vertexData.uvs = uvs;
  39363. return vertexData;
  39364. };
  39365. /**
  39366. * Creates the VertexData of the Ground designed from a heightmap
  39367. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39368. * * width the width (x direction) of the ground
  39369. * * height the height (z direction) of the ground
  39370. * * subdivisions the number of subdivisions per side
  39371. * * minHeight the minimum altitude on the ground, optional, default 0
  39372. * * maxHeight the maximum altitude on the ground, optional default 1
  39373. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39374. * * buffer the array holding the image color data
  39375. * * bufferWidth the width of image
  39376. * * bufferHeight the height of image
  39377. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39378. * @returns the VertexData of the Ground designed from a heightmap
  39379. */
  39380. VertexData.CreateGroundFromHeightMap = function (options) {
  39381. var indices = [];
  39382. var positions = [];
  39383. var normals = [];
  39384. var uvs = [];
  39385. var row, col;
  39386. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39387. var alphaFilter = options.alphaFilter || 0.0;
  39388. // Vertices
  39389. for (row = 0; row <= options.subdivisions; row++) {
  39390. for (col = 0; col <= options.subdivisions; col++) {
  39391. 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));
  39392. // Compute height
  39393. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39394. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39395. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39396. var r = options.buffer[pos] / 255.0;
  39397. var g = options.buffer[pos + 1] / 255.0;
  39398. var b = options.buffer[pos + 2] / 255.0;
  39399. var a = options.buffer[pos + 3] / 255.0;
  39400. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39401. // If our alpha channel is not within our filter then we will assign a 'special' height
  39402. // Then when building the indices, we will ignore any vertex that is using the special height
  39403. if (a >= alphaFilter) {
  39404. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39405. }
  39406. else {
  39407. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39408. }
  39409. // Add vertex
  39410. positions.push(position.x, position.y, position.z);
  39411. normals.push(0, 0, 0);
  39412. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39413. }
  39414. }
  39415. // Indices
  39416. for (row = 0; row < options.subdivisions; row++) {
  39417. for (col = 0; col < options.subdivisions; col++) {
  39418. // Calculate Indices
  39419. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39420. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39421. var idx3 = (col + row * (options.subdivisions + 1));
  39422. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39423. // Check that all indices are visible (based on our special height)
  39424. // Only display the vertex if all Indices are visible
  39425. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39426. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39427. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39428. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39429. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39430. indices.push(idx1);
  39431. indices.push(idx2);
  39432. indices.push(idx3);
  39433. }
  39434. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39435. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39436. indices.push(idx4);
  39437. indices.push(idx1);
  39438. indices.push(idx3);
  39439. }
  39440. }
  39441. }
  39442. // Normals
  39443. VertexData.ComputeNormals(positions, indices, normals);
  39444. // Result
  39445. var vertexData = new VertexData();
  39446. vertexData.indices = indices;
  39447. vertexData.positions = positions;
  39448. vertexData.normals = normals;
  39449. vertexData.uvs = uvs;
  39450. return vertexData;
  39451. };
  39452. /**
  39453. * Creates the VertexData for a Plane
  39454. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39455. * * size sets the width and height of the plane to the value of size, optional default 1
  39456. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39457. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39458. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39459. * * 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)
  39460. * * 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)
  39461. * @returns the VertexData of the box
  39462. */
  39463. VertexData.CreatePlane = function (options) {
  39464. var indices = [];
  39465. var positions = [];
  39466. var normals = [];
  39467. var uvs = [];
  39468. var width = options.width || options.size || 1;
  39469. var height = options.height || options.size || 1;
  39470. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39471. // Vertices
  39472. var halfWidth = width / 2.0;
  39473. var halfHeight = height / 2.0;
  39474. positions.push(-halfWidth, -halfHeight, 0);
  39475. normals.push(0, 0, -1.0);
  39476. uvs.push(0.0, 0.0);
  39477. positions.push(halfWidth, -halfHeight, 0);
  39478. normals.push(0, 0, -1.0);
  39479. uvs.push(1.0, 0.0);
  39480. positions.push(halfWidth, halfHeight, 0);
  39481. normals.push(0, 0, -1.0);
  39482. uvs.push(1.0, 1.0);
  39483. positions.push(-halfWidth, halfHeight, 0);
  39484. normals.push(0, 0, -1.0);
  39485. uvs.push(0.0, 1.0);
  39486. // Indices
  39487. indices.push(0);
  39488. indices.push(1);
  39489. indices.push(2);
  39490. indices.push(0);
  39491. indices.push(2);
  39492. indices.push(3);
  39493. // Sides
  39494. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39495. // Result
  39496. var vertexData = new VertexData();
  39497. vertexData.indices = indices;
  39498. vertexData.positions = positions;
  39499. vertexData.normals = normals;
  39500. vertexData.uvs = uvs;
  39501. return vertexData;
  39502. };
  39503. /**
  39504. * Creates the VertexData of the Disc or regular Polygon
  39505. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39506. * * radius the radius of the disc, optional default 0.5
  39507. * * tessellation the number of polygon sides, optional, default 64
  39508. * * 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
  39509. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39510. * * 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)
  39511. * * 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)
  39512. * @returns the VertexData of the box
  39513. */
  39514. VertexData.CreateDisc = function (options) {
  39515. var positions = new Array();
  39516. var indices = new Array();
  39517. var normals = new Array();
  39518. var uvs = new Array();
  39519. var radius = options.radius || 0.5;
  39520. var tessellation = options.tessellation || 64;
  39521. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39522. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39523. // positions and uvs
  39524. positions.push(0, 0, 0); // disc center first
  39525. uvs.push(0.5, 0.5);
  39526. var theta = Math.PI * 2 * arc;
  39527. var step = theta / tessellation;
  39528. for (var a = 0; a < theta; a += step) {
  39529. var x = Math.cos(a);
  39530. var y = Math.sin(a);
  39531. var u = (x + 1) / 2;
  39532. var v = (1 - y) / 2;
  39533. positions.push(radius * x, radius * y, 0);
  39534. uvs.push(u, v);
  39535. }
  39536. if (arc === 1) {
  39537. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39538. uvs.push(uvs[2], uvs[3]);
  39539. }
  39540. //indices
  39541. var vertexNb = positions.length / 3;
  39542. for (var i = 1; i < vertexNb - 1; i++) {
  39543. indices.push(i + 1, 0, i);
  39544. }
  39545. // result
  39546. VertexData.ComputeNormals(positions, indices, normals);
  39547. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39548. var vertexData = new VertexData();
  39549. vertexData.indices = indices;
  39550. vertexData.positions = positions;
  39551. vertexData.normals = normals;
  39552. vertexData.uvs = uvs;
  39553. return vertexData;
  39554. };
  39555. /**
  39556. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39557. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39558. * @param polygon a mesh built from polygonTriangulation.build()
  39559. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39560. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39561. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39562. * @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)
  39563. * @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)
  39564. * @returns the VertexData of the Polygon
  39565. */
  39566. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39567. var faceUV = fUV || new Array(3);
  39568. var faceColors = fColors;
  39569. var colors = [];
  39570. // default face colors and UV if undefined
  39571. for (var f = 0; f < 3; f++) {
  39572. if (faceUV[f] === undefined) {
  39573. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39574. }
  39575. if (faceColors && faceColors[f] === undefined) {
  39576. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39577. }
  39578. }
  39579. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39580. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39581. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39582. var indices = polygon.getIndices();
  39583. // set face colours and textures
  39584. var idx = 0;
  39585. var face = 0;
  39586. for (var index = 0; index < normals.length; index += 3) {
  39587. //Edge Face no. 1
  39588. if (Math.abs(normals[index + 1]) < 0.001) {
  39589. face = 1;
  39590. }
  39591. //Top Face no. 0
  39592. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39593. face = 0;
  39594. }
  39595. //Bottom Face no. 2
  39596. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39597. face = 2;
  39598. }
  39599. idx = index / 3;
  39600. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39601. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39602. if (faceColors) {
  39603. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39604. }
  39605. }
  39606. // sides
  39607. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39608. // Result
  39609. var vertexData = new VertexData();
  39610. vertexData.indices = indices;
  39611. vertexData.positions = positions;
  39612. vertexData.normals = normals;
  39613. vertexData.uvs = uvs;
  39614. if (faceColors) {
  39615. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39616. vertexData.colors = totalColors;
  39617. }
  39618. return vertexData;
  39619. };
  39620. /**
  39621. * Creates the VertexData of the IcoSphere
  39622. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39623. * * radius the radius of the IcoSphere, optional default 1
  39624. * * radiusX allows stretching in the x direction, optional, default radius
  39625. * * radiusY allows stretching in the y direction, optional, default radius
  39626. * * radiusZ allows stretching in the z direction, optional, default radius
  39627. * * flat when true creates a flat shaded mesh, optional, default true
  39628. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39629. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39630. * * 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)
  39631. * * 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)
  39632. * @returns the VertexData of the IcoSphere
  39633. */
  39634. VertexData.CreateIcoSphere = function (options) {
  39635. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39636. var radius = options.radius || 1;
  39637. var flat = (options.flat === undefined) ? true : options.flat;
  39638. var subdivisions = options.subdivisions || 4;
  39639. var radiusX = options.radiusX || radius;
  39640. var radiusY = options.radiusY || radius;
  39641. var radiusZ = options.radiusZ || radius;
  39642. var t = (1 + Math.sqrt(5)) / 2;
  39643. // 12 vertex x,y,z
  39644. var ico_vertices = [
  39645. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39646. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39647. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39648. ];
  39649. // index of 3 vertex makes a face of icopshere
  39650. var ico_indices = [
  39651. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39652. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39653. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39654. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39655. ];
  39656. // vertex for uv have aliased position, not for UV
  39657. var vertices_unalias_id = [
  39658. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39659. // vertex alias
  39660. 0,
  39661. 2,
  39662. 3,
  39663. 3,
  39664. 3,
  39665. 4,
  39666. 7,
  39667. 8,
  39668. 9,
  39669. 9,
  39670. 10,
  39671. 11 // 23: B + 12
  39672. ];
  39673. // uv as integer step (not pixels !)
  39674. var ico_vertexuv = [
  39675. 5, 1, 3, 1, 6, 4, 0, 0,
  39676. 5, 3, 4, 2, 2, 2, 4, 0,
  39677. 2, 0, 1, 1, 6, 0, 6, 2,
  39678. // vertex alias (for same vertex on different faces)
  39679. 0, 4,
  39680. 3, 3,
  39681. 4, 4,
  39682. 3, 1,
  39683. 4, 2,
  39684. 4, 4,
  39685. 0, 2,
  39686. 1, 1,
  39687. 2, 2,
  39688. 3, 3,
  39689. 1, 3,
  39690. 2, 4 // 23: B + 12
  39691. ];
  39692. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39693. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39694. // First island of uv mapping
  39695. // v = 4h 3+ 2
  39696. // v = 3h 9+ 4
  39697. // v = 2h 9+ 5 B
  39698. // v = 1h 9 1 0
  39699. // v = 0h 3 8 7 A
  39700. // u = 0 1 2 3 4 5 6 *a
  39701. // Second island of uv mapping
  39702. // v = 4h 0+ B+ 4+
  39703. // v = 3h A+ 2+
  39704. // v = 2h 7+ 6 3+
  39705. // v = 1h 8+ 3+
  39706. // v = 0h
  39707. // u = 0 1 2 3 4 5 6 *a
  39708. // Face layout on texture UV mapping
  39709. // ============
  39710. // \ 4 /\ 16 / ======
  39711. // \ / \ / /\ 11 /
  39712. // \/ 7 \/ / \ /
  39713. // ======= / 10 \/
  39714. // /\ 17 /\ =======
  39715. // / \ / \ \ 15 /\
  39716. // / 8 \/ 12 \ \ / \
  39717. // ============ \/ 6 \
  39718. // \ 18 /\ ============
  39719. // \ / \ \ 5 /\ 0 /
  39720. // \/ 13 \ \ / \ /
  39721. // ======= \/ 1 \/
  39722. // =============
  39723. // /\ 19 /\ 2 /\
  39724. // / \ / \ / \
  39725. // / 14 \/ 9 \/ 3 \
  39726. // ===================
  39727. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39728. var ustep = 138 / 1024;
  39729. var vstep = 239 / 1024;
  39730. var uoffset = 60 / 1024;
  39731. var voffset = 26 / 1024;
  39732. // Second island should have margin, not to touch the first island
  39733. // avoid any borderline artefact in pixel rounding
  39734. var island_u_offset = -40 / 1024;
  39735. var island_v_offset = +20 / 1024;
  39736. // face is either island 0 or 1 :
  39737. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39738. var island = [
  39739. 0, 0, 0, 0, 1,
  39740. 0, 0, 1, 1, 0,
  39741. 0, 0, 1, 1, 0,
  39742. 0, 1, 1, 1, 0 // 15 - 19
  39743. ];
  39744. var indices = new Array();
  39745. var positions = new Array();
  39746. var normals = new Array();
  39747. var uvs = new Array();
  39748. var current_indice = 0;
  39749. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39750. var face_vertex_pos = new Array(3);
  39751. var face_vertex_uv = new Array(3);
  39752. var v012;
  39753. for (v012 = 0; v012 < 3; v012++) {
  39754. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39755. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39756. }
  39757. // create all with normals
  39758. for (var face = 0; face < 20; face++) {
  39759. // 3 vertex per face
  39760. for (v012 = 0; v012 < 3; v012++) {
  39761. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39762. var v_id = ico_indices[3 * face + v012];
  39763. // vertex have 3D position (x,y,z)
  39764. 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]);
  39765. // Normalize to get normal, then scale to radius
  39766. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39767. // uv Coordinates from vertex ID
  39768. 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);
  39769. }
  39770. // Subdivide the face (interpolate pos, norm, uv)
  39771. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39772. // - norm is linear interpolation of vertex corner normal
  39773. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39774. // - uv is linear interpolation
  39775. //
  39776. // Topology is as below for sub-divide by 2
  39777. // vertex shown as v0,v1,v2
  39778. // interp index is i1 to progress in range [v0,v1[
  39779. // interp index is i2 to progress in range [v0,v2[
  39780. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39781. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39782. //
  39783. //
  39784. // i2 v2
  39785. // ^ ^
  39786. // / / \
  39787. // / / \
  39788. // / / \
  39789. // / / (0,1) \
  39790. // / #---------\
  39791. // / / \ (0,0)'/ \
  39792. // / / \ / \
  39793. // / / \ / \
  39794. // / / (0,0) \ / (1,0) \
  39795. // / #---------#---------\
  39796. // v0 v1
  39797. //
  39798. // --------------------> i1
  39799. //
  39800. // interp of (i1,i2):
  39801. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39802. // along i1 : lerp(x0,x1, i1/(S-i2))
  39803. //
  39804. // centroid of triangle is needed to get help normal computation
  39805. // (c1,c2) are used for centroid location
  39806. var interp_vertex = function (i1, i2, c1, c2) {
  39807. // vertex is interpolated from
  39808. // - face_vertex_pos[0..2]
  39809. // - face_vertex_uv[0..2]
  39810. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39811. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39812. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39813. pos_interp.normalize();
  39814. var vertex_normal;
  39815. if (flat) {
  39816. // in flat mode, recalculate normal as face centroid normal
  39817. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39818. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39819. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39820. }
  39821. else {
  39822. // in smooth mode, recalculate normal from each single vertex position
  39823. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39824. }
  39825. // Vertex normal need correction due to X,Y,Z radius scaling
  39826. vertex_normal.x /= radiusX;
  39827. vertex_normal.y /= radiusY;
  39828. vertex_normal.z /= radiusZ;
  39829. vertex_normal.normalize();
  39830. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39831. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39832. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39833. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39834. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39835. uvs.push(uv_interp.x, uv_interp.y);
  39836. // push each vertex has member of a face
  39837. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39838. indices.push(current_indice);
  39839. current_indice++;
  39840. };
  39841. for (var i2 = 0; i2 < subdivisions; i2++) {
  39842. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39843. // face : (i1,i2) for /\ :
  39844. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39845. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39846. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39847. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39848. if (i1 + i2 + 1 < subdivisions) {
  39849. // face : (i1,i2)' for \/ :
  39850. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39851. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39852. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39853. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39854. }
  39855. }
  39856. }
  39857. }
  39858. // Sides
  39859. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39860. // Result
  39861. var vertexData = new VertexData();
  39862. vertexData.indices = indices;
  39863. vertexData.positions = positions;
  39864. vertexData.normals = normals;
  39865. vertexData.uvs = uvs;
  39866. return vertexData;
  39867. };
  39868. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39869. /**
  39870. * Creates the VertexData for a Polyhedron
  39871. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39872. * * type provided types are:
  39873. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39874. * * 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)
  39875. * * size the size of the IcoSphere, optional default 1
  39876. * * sizeX allows stretching in the x direction, optional, default size
  39877. * * sizeY allows stretching in the y direction, optional, default size
  39878. * * sizeZ allows stretching in the z direction, optional, default size
  39879. * * 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
  39880. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39881. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39882. * * flat when true creates a flat shaded mesh, optional, default true
  39883. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39884. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39885. * * 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)
  39886. * * 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)
  39887. * @returns the VertexData of the Polyhedron
  39888. */
  39889. VertexData.CreatePolyhedron = function (options) {
  39890. // provided polyhedron types :
  39891. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39892. // 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)
  39893. var polyhedra = [];
  39894. 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]] };
  39895. 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]] };
  39896. polyhedra[2] = {
  39897. 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]],
  39898. 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]]
  39899. };
  39900. polyhedra[3] = {
  39901. 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]],
  39902. 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]]
  39903. };
  39904. polyhedra[4] = {
  39905. 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]],
  39906. 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]]
  39907. };
  39908. 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]] };
  39909. 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]] };
  39910. 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]] };
  39911. 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]] };
  39912. 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]] };
  39913. 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]] };
  39914. 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]] };
  39915. 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]] };
  39916. 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]] };
  39917. polyhedra[14] = {
  39918. 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]],
  39919. 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]]
  39920. };
  39921. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39922. var size = options.size;
  39923. var sizeX = options.sizeX || size || 1;
  39924. var sizeY = options.sizeY || size || 1;
  39925. var sizeZ = options.sizeZ || size || 1;
  39926. var data = options.custom || polyhedra[type];
  39927. var nbfaces = data.face.length;
  39928. var faceUV = options.faceUV || new Array(nbfaces);
  39929. var faceColors = options.faceColors;
  39930. var flat = (options.flat === undefined) ? true : options.flat;
  39931. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39932. var positions = new Array();
  39933. var indices = new Array();
  39934. var normals = new Array();
  39935. var uvs = new Array();
  39936. var colors = new Array();
  39937. var index = 0;
  39938. var faceIdx = 0; // face cursor in the array "indexes"
  39939. var indexes = new Array();
  39940. var i = 0;
  39941. var f = 0;
  39942. var u, v, ang, x, y, tmp;
  39943. // default face colors and UV if undefined
  39944. if (flat) {
  39945. for (f = 0; f < nbfaces; f++) {
  39946. if (faceColors && faceColors[f] === undefined) {
  39947. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39948. }
  39949. if (faceUV && faceUV[f] === undefined) {
  39950. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39951. }
  39952. }
  39953. }
  39954. if (!flat) {
  39955. for (i = 0; i < data.vertex.length; i++) {
  39956. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39957. uvs.push(0, 0);
  39958. }
  39959. for (f = 0; f < nbfaces; f++) {
  39960. for (i = 0; i < data.face[f].length - 2; i++) {
  39961. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39962. }
  39963. }
  39964. }
  39965. else {
  39966. for (f = 0; f < nbfaces; f++) {
  39967. var fl = data.face[f].length; // number of vertices of the current face
  39968. ang = 2 * Math.PI / fl;
  39969. x = 0.5 * Math.tan(ang / 2);
  39970. y = 0.5;
  39971. // positions, uvs, colors
  39972. for (i = 0; i < fl; i++) {
  39973. // positions
  39974. 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);
  39975. indexes.push(index);
  39976. index++;
  39977. // uvs
  39978. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39979. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39980. uvs.push(u, v);
  39981. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39982. y = x * Math.sin(ang) + y * Math.cos(ang);
  39983. x = tmp;
  39984. // colors
  39985. if (faceColors) {
  39986. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39987. }
  39988. }
  39989. // indices from indexes
  39990. for (i = 0; i < fl - 2; i++) {
  39991. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39992. }
  39993. faceIdx += fl;
  39994. }
  39995. }
  39996. VertexData.ComputeNormals(positions, indices, normals);
  39997. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39998. var vertexData = new VertexData();
  39999. vertexData.positions = positions;
  40000. vertexData.indices = indices;
  40001. vertexData.normals = normals;
  40002. vertexData.uvs = uvs;
  40003. if (faceColors && flat) {
  40004. vertexData.colors = colors;
  40005. }
  40006. return vertexData;
  40007. };
  40008. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40009. /**
  40010. * Creates the VertexData for a TorusKnot
  40011. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40012. * * radius the radius of the torus knot, optional, default 2
  40013. * * tube the thickness of the tube, optional, default 0.5
  40014. * * radialSegments the number of sides on each tube segments, optional, default 32
  40015. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40016. * * p the number of windings around the z axis, optional, default 2
  40017. * * q the number of windings around the x axis, optional, default 3
  40018. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40019. * * 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)
  40020. * * 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)
  40021. * @returns the VertexData of the Torus Knot
  40022. */
  40023. VertexData.CreateTorusKnot = function (options) {
  40024. var indices = new Array();
  40025. var positions = new Array();
  40026. var normals = new Array();
  40027. var uvs = new Array();
  40028. var radius = options.radius || 2;
  40029. var tube = options.tube || 0.5;
  40030. var radialSegments = options.radialSegments || 32;
  40031. var tubularSegments = options.tubularSegments || 32;
  40032. var p = options.p || 2;
  40033. var q = options.q || 3;
  40034. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40035. // Helper
  40036. var getPos = function (angle) {
  40037. var cu = Math.cos(angle);
  40038. var su = Math.sin(angle);
  40039. var quOverP = q / p * angle;
  40040. var cs = Math.cos(quOverP);
  40041. var tx = radius * (2 + cs) * 0.5 * cu;
  40042. var ty = radius * (2 + cs) * su * 0.5;
  40043. var tz = radius * Math.sin(quOverP) * 0.5;
  40044. return new BABYLON.Vector3(tx, ty, tz);
  40045. };
  40046. // Vertices
  40047. var i;
  40048. var j;
  40049. for (i = 0; i <= radialSegments; i++) {
  40050. var modI = i % radialSegments;
  40051. var u = modI / radialSegments * 2 * p * Math.PI;
  40052. var p1 = getPos(u);
  40053. var p2 = getPos(u + 0.01);
  40054. var tang = p2.subtract(p1);
  40055. var n = p2.add(p1);
  40056. var bitan = BABYLON.Vector3.Cross(tang, n);
  40057. n = BABYLON.Vector3.Cross(bitan, tang);
  40058. bitan.normalize();
  40059. n.normalize();
  40060. for (j = 0; j < tubularSegments; j++) {
  40061. var modJ = j % tubularSegments;
  40062. var v = modJ / tubularSegments * 2 * Math.PI;
  40063. var cx = -tube * Math.cos(v);
  40064. var cy = tube * Math.sin(v);
  40065. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40066. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40067. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40068. uvs.push(i / radialSegments);
  40069. uvs.push(j / tubularSegments);
  40070. }
  40071. }
  40072. for (i = 0; i < radialSegments; i++) {
  40073. for (j = 0; j < tubularSegments; j++) {
  40074. var jNext = (j + 1) % tubularSegments;
  40075. var a = i * tubularSegments + j;
  40076. var b = (i + 1) * tubularSegments + j;
  40077. var c = (i + 1) * tubularSegments + jNext;
  40078. var d = i * tubularSegments + jNext;
  40079. indices.push(d);
  40080. indices.push(b);
  40081. indices.push(a);
  40082. indices.push(d);
  40083. indices.push(c);
  40084. indices.push(b);
  40085. }
  40086. }
  40087. // Normals
  40088. VertexData.ComputeNormals(positions, indices, normals);
  40089. // Sides
  40090. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40091. // Result
  40092. var vertexData = new VertexData();
  40093. vertexData.indices = indices;
  40094. vertexData.positions = positions;
  40095. vertexData.normals = normals;
  40096. vertexData.uvs = uvs;
  40097. return vertexData;
  40098. };
  40099. // Tools
  40100. /**
  40101. * Compute normals for given positions and indices
  40102. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40103. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40104. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40105. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40106. * * facetNormals : optional array of facet normals (vector3)
  40107. * * facetPositions : optional array of facet positions (vector3)
  40108. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40109. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40110. * * bInfo : optional bounding info, required for facetPartitioning computation
  40111. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40112. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40113. * * useRightHandedSystem: optional boolean to for right handed system computation
  40114. * * depthSort : optional boolean to enable the facet depth sort computation
  40115. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40116. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40117. */
  40118. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40119. // temporary scalar variables
  40120. var index = 0; // facet index
  40121. var p1p2x = 0.0; // p1p2 vector x coordinate
  40122. var p1p2y = 0.0; // p1p2 vector y coordinate
  40123. var p1p2z = 0.0; // p1p2 vector z coordinate
  40124. var p3p2x = 0.0; // p3p2 vector x coordinate
  40125. var p3p2y = 0.0; // p3p2 vector y coordinate
  40126. var p3p2z = 0.0; // p3p2 vector z coordinate
  40127. var faceNormalx = 0.0; // facet normal x coordinate
  40128. var faceNormaly = 0.0; // facet normal y coordinate
  40129. var faceNormalz = 0.0; // facet normal z coordinate
  40130. var length = 0.0; // facet normal length before normalization
  40131. var v1x = 0; // vector1 x index in the positions array
  40132. var v1y = 0; // vector1 y index in the positions array
  40133. var v1z = 0; // vector1 z index in the positions array
  40134. var v2x = 0; // vector2 x index in the positions array
  40135. var v2y = 0; // vector2 y index in the positions array
  40136. var v2z = 0; // vector2 z index in the positions array
  40137. var v3x = 0; // vector3 x index in the positions array
  40138. var v3y = 0; // vector3 y index in the positions array
  40139. var v3z = 0; // vector3 z index in the positions array
  40140. var computeFacetNormals = false;
  40141. var computeFacetPositions = false;
  40142. var computeFacetPartitioning = false;
  40143. var computeDepthSort = false;
  40144. var faceNormalSign = 1;
  40145. var ratio = 0;
  40146. var distanceTo = null;
  40147. if (options) {
  40148. computeFacetNormals = (options.facetNormals) ? true : false;
  40149. computeFacetPositions = (options.facetPositions) ? true : false;
  40150. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40151. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40152. ratio = options.ratio || 0;
  40153. computeDepthSort = (options.depthSort) ? true : false;
  40154. distanceTo = (options.distanceTo);
  40155. if (computeDepthSort) {
  40156. if (distanceTo === undefined) {
  40157. distanceTo = BABYLON.Vector3.Zero();
  40158. }
  40159. var depthSortedFacets = options.depthSortedFacets;
  40160. }
  40161. }
  40162. // facetPartitioning reinit if needed
  40163. var xSubRatio = 0;
  40164. var ySubRatio = 0;
  40165. var zSubRatio = 0;
  40166. var subSq = 0;
  40167. if (computeFacetPartitioning && options && options.bbSize) {
  40168. var ox = 0; // X partitioning index for facet position
  40169. var oy = 0; // Y partinioning index for facet position
  40170. var oz = 0; // Z partinioning index for facet position
  40171. var b1x = 0; // X partitioning index for facet v1 vertex
  40172. var b1y = 0; // Y partitioning index for facet v1 vertex
  40173. var b1z = 0; // z partitioning index for facet v1 vertex
  40174. var b2x = 0; // X partitioning index for facet v2 vertex
  40175. var b2y = 0; // Y partitioning index for facet v2 vertex
  40176. var b2z = 0; // Z partitioning index for facet v2 vertex
  40177. var b3x = 0; // X partitioning index for facet v3 vertex
  40178. var b3y = 0; // Y partitioning index for facet v3 vertex
  40179. var b3z = 0; // Z partitioning index for facet v3 vertex
  40180. var block_idx_o = 0; // facet barycenter block index
  40181. var block_idx_v1 = 0; // v1 vertex block index
  40182. var block_idx_v2 = 0; // v2 vertex block index
  40183. var block_idx_v3 = 0; // v3 vertex block index
  40184. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40185. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40186. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40187. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40188. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40189. subSq = options.subDiv.max * options.subDiv.max;
  40190. options.facetPartitioning.length = 0;
  40191. }
  40192. // reset the normals
  40193. for (index = 0; index < positions.length; index++) {
  40194. normals[index] = 0.0;
  40195. }
  40196. // Loop : 1 indice triplet = 1 facet
  40197. var nbFaces = (indices.length / 3) | 0;
  40198. for (index = 0; index < nbFaces; index++) {
  40199. // get the indexes of the coordinates of each vertex of the facet
  40200. v1x = indices[index * 3] * 3;
  40201. v1y = v1x + 1;
  40202. v1z = v1x + 2;
  40203. v2x = indices[index * 3 + 1] * 3;
  40204. v2y = v2x + 1;
  40205. v2z = v2x + 2;
  40206. v3x = indices[index * 3 + 2] * 3;
  40207. v3y = v3x + 1;
  40208. v3z = v3x + 2;
  40209. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40210. p1p2y = positions[v1y] - positions[v2y];
  40211. p1p2z = positions[v1z] - positions[v2z];
  40212. p3p2x = positions[v3x] - positions[v2x];
  40213. p3p2y = positions[v3y] - positions[v2y];
  40214. p3p2z = positions[v3z] - positions[v2z];
  40215. // compute the face normal with the cross product
  40216. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40217. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40218. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40219. // normalize this normal and store it in the array facetData
  40220. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40221. length = (length === 0) ? 1.0 : length;
  40222. faceNormalx /= length;
  40223. faceNormaly /= length;
  40224. faceNormalz /= length;
  40225. if (computeFacetNormals && options) {
  40226. options.facetNormals[index].x = faceNormalx;
  40227. options.facetNormals[index].y = faceNormaly;
  40228. options.facetNormals[index].z = faceNormalz;
  40229. }
  40230. if (computeFacetPositions && options) {
  40231. // compute and the facet barycenter coordinates in the array facetPositions
  40232. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40233. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40234. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40235. }
  40236. if (computeFacetPartitioning && options) {
  40237. // store the facet indexes in arrays in the main facetPartitioning array :
  40238. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40239. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40240. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40241. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40242. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40243. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40244. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40245. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40246. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40247. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40248. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40249. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40250. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40251. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40252. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40253. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40254. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40255. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40256. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40257. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40258. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40259. // push each facet index in each block containing the vertex
  40260. options.facetPartitioning[block_idx_v1].push(index);
  40261. if (block_idx_v2 != block_idx_v1) {
  40262. options.facetPartitioning[block_idx_v2].push(index);
  40263. }
  40264. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40265. options.facetPartitioning[block_idx_v3].push(index);
  40266. }
  40267. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40268. options.facetPartitioning[block_idx_o].push(index);
  40269. }
  40270. }
  40271. if (computeDepthSort && options && options.facetPositions) {
  40272. var dsf = depthSortedFacets[index];
  40273. dsf.ind = index * 3;
  40274. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40275. }
  40276. // compute the normals anyway
  40277. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40278. normals[v1y] += faceNormaly;
  40279. normals[v1z] += faceNormalz;
  40280. normals[v2x] += faceNormalx;
  40281. normals[v2y] += faceNormaly;
  40282. normals[v2z] += faceNormalz;
  40283. normals[v3x] += faceNormalx;
  40284. normals[v3y] += faceNormaly;
  40285. normals[v3z] += faceNormalz;
  40286. }
  40287. // last normalization of each normal
  40288. for (index = 0; index < normals.length / 3; index++) {
  40289. faceNormalx = normals[index * 3];
  40290. faceNormaly = normals[index * 3 + 1];
  40291. faceNormalz = normals[index * 3 + 2];
  40292. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40293. length = (length === 0) ? 1.0 : length;
  40294. faceNormalx /= length;
  40295. faceNormaly /= length;
  40296. faceNormalz /= length;
  40297. normals[index * 3] = faceNormalx;
  40298. normals[index * 3 + 1] = faceNormaly;
  40299. normals[index * 3 + 2] = faceNormalz;
  40300. }
  40301. };
  40302. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40303. var li = indices.length;
  40304. var ln = normals.length;
  40305. var i;
  40306. var n;
  40307. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40308. switch (sideOrientation) {
  40309. case BABYLON.Mesh.FRONTSIDE:
  40310. // nothing changed
  40311. break;
  40312. case BABYLON.Mesh.BACKSIDE:
  40313. var tmp;
  40314. // indices
  40315. for (i = 0; i < li; i += 3) {
  40316. tmp = indices[i];
  40317. indices[i] = indices[i + 2];
  40318. indices[i + 2] = tmp;
  40319. }
  40320. // normals
  40321. for (n = 0; n < ln; n++) {
  40322. normals[n] = -normals[n];
  40323. }
  40324. break;
  40325. case BABYLON.Mesh.DOUBLESIDE:
  40326. // positions
  40327. var lp = positions.length;
  40328. var l = lp / 3;
  40329. for (var p = 0; p < lp; p++) {
  40330. positions[lp + p] = positions[p];
  40331. }
  40332. // indices
  40333. for (i = 0; i < li; i += 3) {
  40334. indices[i + li] = indices[i + 2] + l;
  40335. indices[i + 1 + li] = indices[i + 1] + l;
  40336. indices[i + 2 + li] = indices[i] + l;
  40337. }
  40338. // normals
  40339. for (n = 0; n < ln; n++) {
  40340. normals[ln + n] = -normals[n];
  40341. }
  40342. // uvs
  40343. var lu = uvs.length;
  40344. var u = 0;
  40345. for (u = 0; u < lu; u++) {
  40346. uvs[u + lu] = uvs[u];
  40347. }
  40348. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40349. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40350. u = 0;
  40351. for (i = 0; i < lu / 2; i++) {
  40352. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40353. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40354. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40355. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40356. u += 2;
  40357. }
  40358. break;
  40359. }
  40360. };
  40361. /**
  40362. * Applies VertexData created from the imported parameters to the geometry
  40363. * @param parsedVertexData the parsed data from an imported file
  40364. * @param geometry the geometry to apply the VertexData to
  40365. */
  40366. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40367. var vertexData = new VertexData();
  40368. // positions
  40369. var positions = parsedVertexData.positions;
  40370. if (positions) {
  40371. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40372. }
  40373. // normals
  40374. var normals = parsedVertexData.normals;
  40375. if (normals) {
  40376. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40377. }
  40378. // tangents
  40379. var tangents = parsedVertexData.tangents;
  40380. if (tangents) {
  40381. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40382. }
  40383. // uvs
  40384. var uvs = parsedVertexData.uvs;
  40385. if (uvs) {
  40386. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40387. }
  40388. // uv2s
  40389. var uv2s = parsedVertexData.uv2s;
  40390. if (uv2s) {
  40391. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40392. }
  40393. // uv3s
  40394. var uv3s = parsedVertexData.uv3s;
  40395. if (uv3s) {
  40396. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40397. }
  40398. // uv4s
  40399. var uv4s = parsedVertexData.uv4s;
  40400. if (uv4s) {
  40401. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40402. }
  40403. // uv5s
  40404. var uv5s = parsedVertexData.uv5s;
  40405. if (uv5s) {
  40406. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40407. }
  40408. // uv6s
  40409. var uv6s = parsedVertexData.uv6s;
  40410. if (uv6s) {
  40411. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40412. }
  40413. // colors
  40414. var colors = parsedVertexData.colors;
  40415. if (colors) {
  40416. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40417. }
  40418. // matricesIndices
  40419. var matricesIndices = parsedVertexData.matricesIndices;
  40420. if (matricesIndices) {
  40421. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40422. }
  40423. // matricesWeights
  40424. var matricesWeights = parsedVertexData.matricesWeights;
  40425. if (matricesWeights) {
  40426. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40427. }
  40428. // indices
  40429. var indices = parsedVertexData.indices;
  40430. if (indices) {
  40431. vertexData.indices = indices;
  40432. }
  40433. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40434. };
  40435. return VertexData;
  40436. }());
  40437. BABYLON.VertexData = VertexData;
  40438. })(BABYLON || (BABYLON = {}));
  40439. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40440. var BABYLON;
  40441. (function (BABYLON) {
  40442. /**
  40443. * Class used to store geometry data (vertex buffers + index buffer)
  40444. */
  40445. var Geometry = /** @class */ (function () {
  40446. /**
  40447. * Creates a new geometry
  40448. * @param id defines the unique ID
  40449. * @param scene defines the hosting scene
  40450. * @param vertexData defines the VertexData used to get geometry data
  40451. * @param updatable defines if geometry must be updatable (false by default)
  40452. * @param mesh defines the mesh that will be associated with the geometry
  40453. */
  40454. function Geometry(id, scene, vertexData, updatable, mesh) {
  40455. if (updatable === void 0) { updatable = false; }
  40456. if (mesh === void 0) { mesh = null; }
  40457. /**
  40458. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40459. */
  40460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40461. this._totalVertices = 0;
  40462. this._isDisposed = false;
  40463. this._indexBufferIsUpdatable = false;
  40464. this.id = id;
  40465. this._engine = scene.getEngine();
  40466. this._meshes = [];
  40467. this._scene = scene;
  40468. //Init vertex buffer cache
  40469. this._vertexBuffers = {};
  40470. this._indices = [];
  40471. this._updatable = updatable;
  40472. // vertexData
  40473. if (vertexData) {
  40474. this.setAllVerticesData(vertexData, updatable);
  40475. }
  40476. else {
  40477. this._totalVertices = 0;
  40478. this._indices = [];
  40479. }
  40480. if (this._engine.getCaps().vertexArrayObject) {
  40481. this._vertexArrayObjects = {};
  40482. }
  40483. // applyToMesh
  40484. if (mesh) {
  40485. if (mesh.getClassName() === "LinesMesh") {
  40486. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40487. this._updateExtend();
  40488. }
  40489. this.applyToMesh(mesh);
  40490. mesh.computeWorldMatrix(true);
  40491. }
  40492. }
  40493. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40494. /**
  40495. * 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
  40496. */
  40497. get: function () {
  40498. return this._boundingBias;
  40499. },
  40500. /**
  40501. * 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
  40502. */
  40503. set: function (value) {
  40504. if (this._boundingBias) {
  40505. if (this._boundingBias.equals(value)) {
  40506. return;
  40507. }
  40508. this._boundingBias.copyFrom(value);
  40509. }
  40510. else {
  40511. this._boundingBias = value.clone();
  40512. }
  40513. this._updateBoundingInfo(true, null);
  40514. },
  40515. enumerable: true,
  40516. configurable: true
  40517. });
  40518. /**
  40519. * Static function used to attach a new empty geometry to a mesh
  40520. * @param mesh defines the mesh to attach the geometry to
  40521. * @returns the new Geometry
  40522. */
  40523. Geometry.CreateGeometryForMesh = function (mesh) {
  40524. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40525. geometry.applyToMesh(mesh);
  40526. return geometry;
  40527. };
  40528. Object.defineProperty(Geometry.prototype, "extend", {
  40529. /**
  40530. * Gets the current extend of the geometry
  40531. */
  40532. get: function () {
  40533. return this._extend;
  40534. },
  40535. enumerable: true,
  40536. configurable: true
  40537. });
  40538. /**
  40539. * Gets the hosting scene
  40540. * @returns the hosting Scene
  40541. */
  40542. Geometry.prototype.getScene = function () {
  40543. return this._scene;
  40544. };
  40545. /**
  40546. * Gets the hosting engine
  40547. * @returns the hosting Engine
  40548. */
  40549. Geometry.prototype.getEngine = function () {
  40550. return this._engine;
  40551. };
  40552. /**
  40553. * Defines if the geometry is ready to use
  40554. * @returns true if the geometry is ready to be used
  40555. */
  40556. Geometry.prototype.isReady = function () {
  40557. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40558. };
  40559. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40560. /**
  40561. * Gets a value indicating that the geometry should not be serialized
  40562. */
  40563. get: function () {
  40564. for (var index = 0; index < this._meshes.length; index++) {
  40565. if (!this._meshes[index].doNotSerialize) {
  40566. return false;
  40567. }
  40568. }
  40569. return true;
  40570. },
  40571. enumerable: true,
  40572. configurable: true
  40573. });
  40574. /** @hidden */
  40575. Geometry.prototype._rebuild = function () {
  40576. if (this._vertexArrayObjects) {
  40577. this._vertexArrayObjects = {};
  40578. }
  40579. // Index buffer
  40580. if (this._meshes.length !== 0 && this._indices) {
  40581. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40582. }
  40583. // Vertex buffers
  40584. for (var key in this._vertexBuffers) {
  40585. var vertexBuffer = this._vertexBuffers[key];
  40586. vertexBuffer._rebuild();
  40587. }
  40588. };
  40589. /**
  40590. * Affects all geometry data in one call
  40591. * @param vertexData defines the geometry data
  40592. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40593. */
  40594. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40595. vertexData.applyToGeometry(this, updatable);
  40596. this.notifyUpdate();
  40597. };
  40598. /**
  40599. * Set specific vertex data
  40600. * @param kind defines the data kind (Position, normal, etc...)
  40601. * @param data defines the vertex data to use
  40602. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40603. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40604. */
  40605. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40606. if (updatable === void 0) { updatable = false; }
  40607. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40608. this.setVerticesBuffer(buffer);
  40609. };
  40610. /**
  40611. * Removes a specific vertex data
  40612. * @param kind defines the data kind (Position, normal, etc...)
  40613. */
  40614. Geometry.prototype.removeVerticesData = function (kind) {
  40615. if (this._vertexBuffers[kind]) {
  40616. this._vertexBuffers[kind].dispose();
  40617. delete this._vertexBuffers[kind];
  40618. }
  40619. };
  40620. /**
  40621. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40622. * @param buffer defines the vertex buffer to use
  40623. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40624. */
  40625. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40626. if (totalVertices === void 0) { totalVertices = null; }
  40627. var kind = buffer.getKind();
  40628. if (this._vertexBuffers[kind]) {
  40629. this._vertexBuffers[kind].dispose();
  40630. }
  40631. this._vertexBuffers[kind] = buffer;
  40632. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40633. var data = buffer.getData();
  40634. if (totalVertices != null) {
  40635. this._totalVertices = totalVertices;
  40636. }
  40637. else {
  40638. if (data != null) {
  40639. this._totalVertices = data.length / (buffer.byteStride / 4);
  40640. }
  40641. }
  40642. this._updateExtend(data);
  40643. this._resetPointsArrayCache();
  40644. var meshes = this._meshes;
  40645. var numOfMeshes = meshes.length;
  40646. for (var index = 0; index < numOfMeshes; index++) {
  40647. var mesh = meshes[index];
  40648. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40649. mesh._createGlobalSubMesh(false);
  40650. mesh.computeWorldMatrix(true);
  40651. }
  40652. }
  40653. this.notifyUpdate(kind);
  40654. if (this._vertexArrayObjects) {
  40655. this._disposeVertexArrayObjects();
  40656. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40657. }
  40658. };
  40659. /**
  40660. * Update a specific vertex buffer
  40661. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40662. * It will do nothing if the buffer is not updatable
  40663. * @param kind defines the data kind (Position, normal, etc...)
  40664. * @param data defines the data to use
  40665. * @param offset defines the offset in the target buffer where to store the data
  40666. * @param useBytes set to true if the offset is in bytes
  40667. */
  40668. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40669. if (useBytes === void 0) { useBytes = false; }
  40670. var vertexBuffer = this.getVertexBuffer(kind);
  40671. if (!vertexBuffer) {
  40672. return;
  40673. }
  40674. vertexBuffer.updateDirectly(data, offset, useBytes);
  40675. this.notifyUpdate(kind);
  40676. };
  40677. /**
  40678. * Update a specific vertex buffer
  40679. * This function will create a new buffer if the current one is not updatable
  40680. * @param kind defines the data kind (Position, normal, etc...)
  40681. * @param data defines the data to use
  40682. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40683. */
  40684. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40685. if (updateExtends === void 0) { updateExtends = false; }
  40686. var vertexBuffer = this.getVertexBuffer(kind);
  40687. if (!vertexBuffer) {
  40688. return;
  40689. }
  40690. vertexBuffer.update(data);
  40691. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40692. this._updateBoundingInfo(updateExtends, data);
  40693. }
  40694. this.notifyUpdate(kind);
  40695. };
  40696. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40697. if (updateExtends) {
  40698. this._updateExtend(data);
  40699. }
  40700. var meshes = this._meshes;
  40701. var numOfMeshes = meshes.length;
  40702. this._resetPointsArrayCache();
  40703. for (var index = 0; index < numOfMeshes; index++) {
  40704. var mesh = meshes[index];
  40705. if (updateExtends) {
  40706. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40707. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40708. var subMesh = mesh.subMeshes[subIndex];
  40709. subMesh.refreshBoundingInfo();
  40710. }
  40711. }
  40712. }
  40713. };
  40714. /** @hidden */
  40715. Geometry.prototype._bind = function (effect, indexToBind) {
  40716. if (!effect) {
  40717. return;
  40718. }
  40719. if (indexToBind === undefined) {
  40720. indexToBind = this._indexBuffer;
  40721. }
  40722. var vbs = this.getVertexBuffers();
  40723. if (!vbs) {
  40724. return;
  40725. }
  40726. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40727. this._engine.bindBuffers(vbs, indexToBind, effect);
  40728. return;
  40729. }
  40730. // Using VAO
  40731. if (!this._vertexArrayObjects[effect.key]) {
  40732. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40733. }
  40734. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40735. };
  40736. /**
  40737. * Gets total number of vertices
  40738. * @returns the total number of vertices
  40739. */
  40740. Geometry.prototype.getTotalVertices = function () {
  40741. if (!this.isReady()) {
  40742. return 0;
  40743. }
  40744. return this._totalVertices;
  40745. };
  40746. /**
  40747. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40748. * @param kind defines the data kind (Position, normal, etc...)
  40749. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40750. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40751. * @returns a float array containing vertex data
  40752. */
  40753. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40754. var vertexBuffer = this.getVertexBuffer(kind);
  40755. if (!vertexBuffer) {
  40756. return null;
  40757. }
  40758. var data = vertexBuffer.getData();
  40759. if (!data) {
  40760. return null;
  40761. }
  40762. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40763. var count = this._totalVertices * vertexBuffer.getSize();
  40764. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40765. var copy_1 = [];
  40766. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  40767. return copy_1;
  40768. }
  40769. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40770. if (data instanceof Array) {
  40771. var offset = vertexBuffer.byteOffset / 4;
  40772. return BABYLON.Tools.Slice(data, offset, offset + count);
  40773. }
  40774. else if (data instanceof ArrayBuffer) {
  40775. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40776. }
  40777. else {
  40778. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40779. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40780. var result = new Float32Array(count);
  40781. var source = new Float32Array(data.buffer, offset, count);
  40782. result.set(source);
  40783. return result;
  40784. }
  40785. return new Float32Array(data.buffer, offset, count);
  40786. }
  40787. }
  40788. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40789. return BABYLON.Tools.Slice(data);
  40790. }
  40791. return data;
  40792. };
  40793. /**
  40794. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40795. * @param kind defines the data kind (Position, normal, etc...)
  40796. * @returns true if the vertex buffer with the specified kind is updatable
  40797. */
  40798. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40799. var vb = this._vertexBuffers[kind];
  40800. if (!vb) {
  40801. return false;
  40802. }
  40803. return vb.isUpdatable();
  40804. };
  40805. /**
  40806. * Gets a specific vertex buffer
  40807. * @param kind defines the data kind (Position, normal, etc...)
  40808. * @returns a VertexBuffer
  40809. */
  40810. Geometry.prototype.getVertexBuffer = function (kind) {
  40811. if (!this.isReady()) {
  40812. return null;
  40813. }
  40814. return this._vertexBuffers[kind];
  40815. };
  40816. /**
  40817. * Returns all vertex buffers
  40818. * @return an object holding all vertex buffers indexed by kind
  40819. */
  40820. Geometry.prototype.getVertexBuffers = function () {
  40821. if (!this.isReady()) {
  40822. return null;
  40823. }
  40824. return this._vertexBuffers;
  40825. };
  40826. /**
  40827. * Gets a boolean indicating if specific vertex buffer is present
  40828. * @param kind defines the data kind (Position, normal, etc...)
  40829. * @returns true if data is present
  40830. */
  40831. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40832. if (!this._vertexBuffers) {
  40833. if (this._delayInfo) {
  40834. return this._delayInfo.indexOf(kind) !== -1;
  40835. }
  40836. return false;
  40837. }
  40838. return this._vertexBuffers[kind] !== undefined;
  40839. };
  40840. /**
  40841. * Gets a list of all attached data kinds (Position, normal, etc...)
  40842. * @returns a list of string containing all kinds
  40843. */
  40844. Geometry.prototype.getVerticesDataKinds = function () {
  40845. var result = [];
  40846. var kind;
  40847. if (!this._vertexBuffers && this._delayInfo) {
  40848. for (kind in this._delayInfo) {
  40849. result.push(kind);
  40850. }
  40851. }
  40852. else {
  40853. for (kind in this._vertexBuffers) {
  40854. result.push(kind);
  40855. }
  40856. }
  40857. return result;
  40858. };
  40859. /**
  40860. * Update index buffer
  40861. * @param indices defines the indices to store in the index buffer
  40862. * @param offset defines the offset in the target buffer where to store the data
  40863. */
  40864. Geometry.prototype.updateIndices = function (indices, offset) {
  40865. if (!this._indexBuffer) {
  40866. return;
  40867. }
  40868. if (!this._indexBufferIsUpdatable) {
  40869. this.setIndices(indices, null, true);
  40870. }
  40871. else {
  40872. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40873. }
  40874. };
  40875. /**
  40876. * Creates a new index buffer
  40877. * @param indices defines the indices to store in the index buffer
  40878. * @param totalVertices defines the total number of vertices (could be null)
  40879. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40880. */
  40881. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40882. if (totalVertices === void 0) { totalVertices = null; }
  40883. if (updatable === void 0) { updatable = false; }
  40884. if (this._indexBuffer) {
  40885. this._engine._releaseBuffer(this._indexBuffer);
  40886. }
  40887. this._disposeVertexArrayObjects();
  40888. this._indices = indices;
  40889. this._indexBufferIsUpdatable = updatable;
  40890. if (this._meshes.length !== 0 && this._indices) {
  40891. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40892. }
  40893. if (totalVertices != undefined) { // including null and undefined
  40894. this._totalVertices = totalVertices;
  40895. }
  40896. var meshes = this._meshes;
  40897. var numOfMeshes = meshes.length;
  40898. for (var index = 0; index < numOfMeshes; index++) {
  40899. meshes[index]._createGlobalSubMesh(true);
  40900. }
  40901. this.notifyUpdate();
  40902. };
  40903. /**
  40904. * Return the total number of indices
  40905. * @returns the total number of indices
  40906. */
  40907. Geometry.prototype.getTotalIndices = function () {
  40908. if (!this.isReady()) {
  40909. return 0;
  40910. }
  40911. return this._indices.length;
  40912. };
  40913. /**
  40914. * Gets the index buffer array
  40915. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40916. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40917. * @returns the index buffer array
  40918. */
  40919. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40920. if (!this.isReady()) {
  40921. return null;
  40922. }
  40923. var orig = this._indices;
  40924. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40925. return orig;
  40926. }
  40927. else {
  40928. var len = orig.length;
  40929. var copy = [];
  40930. for (var i = 0; i < len; i++) {
  40931. copy.push(orig[i]);
  40932. }
  40933. return copy;
  40934. }
  40935. };
  40936. /**
  40937. * Gets the index buffer
  40938. * @return the index buffer
  40939. */
  40940. Geometry.prototype.getIndexBuffer = function () {
  40941. if (!this.isReady()) {
  40942. return null;
  40943. }
  40944. return this._indexBuffer;
  40945. };
  40946. /** @hidden */
  40947. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40948. if (effect === void 0) { effect = null; }
  40949. if (!effect || !this._vertexArrayObjects) {
  40950. return;
  40951. }
  40952. if (this._vertexArrayObjects[effect.key]) {
  40953. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40954. delete this._vertexArrayObjects[effect.key];
  40955. }
  40956. };
  40957. /**
  40958. * Release the associated resources for a specific mesh
  40959. * @param mesh defines the source mesh
  40960. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40961. */
  40962. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40963. var meshes = this._meshes;
  40964. var index = meshes.indexOf(mesh);
  40965. if (index === -1) {
  40966. return;
  40967. }
  40968. meshes.splice(index, 1);
  40969. mesh._geometry = null;
  40970. if (meshes.length === 0 && shouldDispose) {
  40971. this.dispose();
  40972. }
  40973. };
  40974. /**
  40975. * Apply current geometry to a given mesh
  40976. * @param mesh defines the mesh to apply geometry to
  40977. */
  40978. Geometry.prototype.applyToMesh = function (mesh) {
  40979. if (mesh._geometry === this) {
  40980. return;
  40981. }
  40982. var previousGeometry = mesh._geometry;
  40983. if (previousGeometry) {
  40984. previousGeometry.releaseForMesh(mesh);
  40985. }
  40986. var meshes = this._meshes;
  40987. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40988. mesh._geometry = this;
  40989. this._scene.pushGeometry(this);
  40990. meshes.push(mesh);
  40991. if (this.isReady()) {
  40992. this._applyToMesh(mesh);
  40993. }
  40994. else {
  40995. mesh._boundingInfo = this._boundingInfo;
  40996. }
  40997. };
  40998. Geometry.prototype._updateExtend = function (data) {
  40999. if (data === void 0) { data = null; }
  41000. if (!data) {
  41001. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41002. }
  41003. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41004. };
  41005. Geometry.prototype._applyToMesh = function (mesh) {
  41006. var numOfMeshes = this._meshes.length;
  41007. // vertexBuffers
  41008. for (var kind in this._vertexBuffers) {
  41009. if (numOfMeshes === 1) {
  41010. this._vertexBuffers[kind].create();
  41011. }
  41012. var buffer = this._vertexBuffers[kind].getBuffer();
  41013. if (buffer) {
  41014. buffer.references = numOfMeshes;
  41015. }
  41016. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41017. if (!this._extend) {
  41018. this._updateExtend();
  41019. }
  41020. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41021. mesh._createGlobalSubMesh(false);
  41022. //bounding info was just created again, world matrix should be applied again.
  41023. mesh._updateBoundingInfo();
  41024. }
  41025. }
  41026. // indexBuffer
  41027. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41028. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41029. }
  41030. if (this._indexBuffer) {
  41031. this._indexBuffer.references = numOfMeshes;
  41032. }
  41033. // morphTargets
  41034. mesh._syncGeometryWithMorphTargetManager();
  41035. };
  41036. Geometry.prototype.notifyUpdate = function (kind) {
  41037. if (this.onGeometryUpdated) {
  41038. this.onGeometryUpdated(this, kind);
  41039. }
  41040. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41041. var mesh = _a[_i];
  41042. mesh._markSubMeshesAsAttributesDirty();
  41043. }
  41044. };
  41045. /**
  41046. * Load the geometry if it was flagged as delay loaded
  41047. * @param scene defines the hosting scene
  41048. * @param onLoaded defines a callback called when the geometry is loaded
  41049. */
  41050. Geometry.prototype.load = function (scene, onLoaded) {
  41051. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41052. return;
  41053. }
  41054. if (this.isReady()) {
  41055. if (onLoaded) {
  41056. onLoaded();
  41057. }
  41058. return;
  41059. }
  41060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41061. this._queueLoad(scene, onLoaded);
  41062. };
  41063. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41064. var _this = this;
  41065. if (!this.delayLoadingFile) {
  41066. return;
  41067. }
  41068. scene._addPendingData(this);
  41069. scene._loadFile(this.delayLoadingFile, function (data) {
  41070. if (!_this._delayLoadingFunction) {
  41071. return;
  41072. }
  41073. _this._delayLoadingFunction(JSON.parse(data), _this);
  41074. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41075. _this._delayInfo = [];
  41076. scene._removePendingData(_this);
  41077. var meshes = _this._meshes;
  41078. var numOfMeshes = meshes.length;
  41079. for (var index = 0; index < numOfMeshes; index++) {
  41080. _this._applyToMesh(meshes[index]);
  41081. }
  41082. if (onLoaded) {
  41083. onLoaded();
  41084. }
  41085. }, undefined, true);
  41086. };
  41087. /**
  41088. * Invert the geometry to move from a right handed system to a left handed one.
  41089. */
  41090. Geometry.prototype.toLeftHanded = function () {
  41091. // Flip faces
  41092. var tIndices = this.getIndices(false);
  41093. if (tIndices != null && tIndices.length > 0) {
  41094. for (var i = 0; i < tIndices.length; i += 3) {
  41095. var tTemp = tIndices[i + 0];
  41096. tIndices[i + 0] = tIndices[i + 2];
  41097. tIndices[i + 2] = tTemp;
  41098. }
  41099. this.setIndices(tIndices);
  41100. }
  41101. // Negate position.z
  41102. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41103. if (tPositions != null && tPositions.length > 0) {
  41104. for (var i = 0; i < tPositions.length; i += 3) {
  41105. tPositions[i + 2] = -tPositions[i + 2];
  41106. }
  41107. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41108. }
  41109. // Negate normal.z
  41110. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41111. if (tNormals != null && tNormals.length > 0) {
  41112. for (var i = 0; i < tNormals.length; i += 3) {
  41113. tNormals[i + 2] = -tNormals[i + 2];
  41114. }
  41115. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41116. }
  41117. };
  41118. // Cache
  41119. /** @hidden */
  41120. Geometry.prototype._resetPointsArrayCache = function () {
  41121. this._positions = null;
  41122. };
  41123. /** @hidden */
  41124. Geometry.prototype._generatePointsArray = function () {
  41125. if (this._positions) {
  41126. return true;
  41127. }
  41128. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41129. if (!data || data.length === 0) {
  41130. return false;
  41131. }
  41132. this._positions = [];
  41133. for (var index = 0; index < data.length; index += 3) {
  41134. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41135. }
  41136. return true;
  41137. };
  41138. /**
  41139. * Gets a value indicating if the geometry is disposed
  41140. * @returns true if the geometry was disposed
  41141. */
  41142. Geometry.prototype.isDisposed = function () {
  41143. return this._isDisposed;
  41144. };
  41145. Geometry.prototype._disposeVertexArrayObjects = function () {
  41146. if (this._vertexArrayObjects) {
  41147. for (var kind in this._vertexArrayObjects) {
  41148. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41149. }
  41150. this._vertexArrayObjects = {};
  41151. }
  41152. };
  41153. /**
  41154. * Free all associated resources
  41155. */
  41156. Geometry.prototype.dispose = function () {
  41157. var meshes = this._meshes;
  41158. var numOfMeshes = meshes.length;
  41159. var index;
  41160. for (index = 0; index < numOfMeshes; index++) {
  41161. this.releaseForMesh(meshes[index]);
  41162. }
  41163. this._meshes = [];
  41164. this._disposeVertexArrayObjects();
  41165. for (var kind in this._vertexBuffers) {
  41166. this._vertexBuffers[kind].dispose();
  41167. }
  41168. this._vertexBuffers = {};
  41169. this._totalVertices = 0;
  41170. if (this._indexBuffer) {
  41171. this._engine._releaseBuffer(this._indexBuffer);
  41172. }
  41173. this._indexBuffer = null;
  41174. this._indices = [];
  41175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41176. this.delayLoadingFile = null;
  41177. this._delayLoadingFunction = null;
  41178. this._delayInfo = [];
  41179. this._boundingInfo = null;
  41180. this._scene.removeGeometry(this);
  41181. this._isDisposed = true;
  41182. };
  41183. /**
  41184. * Clone the current geometry into a new geometry
  41185. * @param id defines the unique ID of the new geometry
  41186. * @returns a new geometry object
  41187. */
  41188. Geometry.prototype.copy = function (id) {
  41189. var vertexData = new BABYLON.VertexData();
  41190. vertexData.indices = [];
  41191. var indices = this.getIndices();
  41192. if (indices) {
  41193. for (var index = 0; index < indices.length; index++) {
  41194. vertexData.indices.push(indices[index]);
  41195. }
  41196. }
  41197. var updatable = false;
  41198. var stopChecking = false;
  41199. var kind;
  41200. for (kind in this._vertexBuffers) {
  41201. // using slice() to make a copy of the array and not just reference it
  41202. var data = this.getVerticesData(kind);
  41203. if (data instanceof Float32Array) {
  41204. vertexData.set(new Float32Array(data), kind);
  41205. }
  41206. else {
  41207. vertexData.set(data.slice(0), kind);
  41208. }
  41209. if (!stopChecking) {
  41210. var vb = this.getVertexBuffer(kind);
  41211. if (vb) {
  41212. updatable = vb.isUpdatable();
  41213. stopChecking = !updatable;
  41214. }
  41215. }
  41216. }
  41217. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41218. geometry.delayLoadState = this.delayLoadState;
  41219. geometry.delayLoadingFile = this.delayLoadingFile;
  41220. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41221. for (kind in this._delayInfo) {
  41222. geometry._delayInfo = geometry._delayInfo || [];
  41223. geometry._delayInfo.push(kind);
  41224. }
  41225. // Bounding info
  41226. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41227. return geometry;
  41228. };
  41229. /**
  41230. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41231. * @return a JSON representation of the current geometry data (without the vertices data)
  41232. */
  41233. Geometry.prototype.serialize = function () {
  41234. var serializationObject = {};
  41235. serializationObject.id = this.id;
  41236. serializationObject.updatable = this._updatable;
  41237. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41239. }
  41240. return serializationObject;
  41241. };
  41242. Geometry.prototype.toNumberArray = function (origin) {
  41243. if (Array.isArray(origin)) {
  41244. return origin;
  41245. }
  41246. else {
  41247. return Array.prototype.slice.call(origin);
  41248. }
  41249. };
  41250. /**
  41251. * Serialize all vertices data into a JSON oject
  41252. * @returns a JSON representation of the current geometry data
  41253. */
  41254. Geometry.prototype.serializeVerticeData = function () {
  41255. var serializationObject = this.serialize();
  41256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41257. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41259. serializationObject.positions._updatable = true;
  41260. }
  41261. }
  41262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41263. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41264. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41265. serializationObject.normals._updatable = true;
  41266. }
  41267. }
  41268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41269. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41271. serializationObject.tangets._updatable = true;
  41272. }
  41273. }
  41274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41275. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41277. serializationObject.uvs._updatable = true;
  41278. }
  41279. }
  41280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41281. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41282. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41283. serializationObject.uv2s._updatable = true;
  41284. }
  41285. }
  41286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41287. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41288. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41289. serializationObject.uv3s._updatable = true;
  41290. }
  41291. }
  41292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41293. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41294. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41295. serializationObject.uv4s._updatable = true;
  41296. }
  41297. }
  41298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41299. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41300. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41301. serializationObject.uv5s._updatable = true;
  41302. }
  41303. }
  41304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41305. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41306. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41307. serializationObject.uv6s._updatable = true;
  41308. }
  41309. }
  41310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41311. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41312. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41313. serializationObject.colors._updatable = true;
  41314. }
  41315. }
  41316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41317. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41318. serializationObject.matricesIndices._isExpanded = true;
  41319. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41320. serializationObject.matricesIndices._updatable = true;
  41321. }
  41322. }
  41323. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41324. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41325. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41326. serializationObject.matricesWeights._updatable = true;
  41327. }
  41328. }
  41329. serializationObject.indices = this.toNumberArray(this.getIndices());
  41330. return serializationObject;
  41331. };
  41332. // Statics
  41333. /**
  41334. * Extracts a clone of a mesh geometry
  41335. * @param mesh defines the source mesh
  41336. * @param id defines the unique ID of the new geometry object
  41337. * @returns the new geometry object
  41338. */
  41339. Geometry.ExtractFromMesh = function (mesh, id) {
  41340. var geometry = mesh._geometry;
  41341. if (!geometry) {
  41342. return null;
  41343. }
  41344. return geometry.copy(id);
  41345. };
  41346. /**
  41347. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41348. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41349. * Be aware Math.random() could cause collisions, but:
  41350. * "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"
  41351. * @returns a string containing a new GUID
  41352. */
  41353. Geometry.RandomId = function () {
  41354. return BABYLON.Tools.RandomId();
  41355. };
  41356. /** @hidden */
  41357. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41358. var scene = mesh.getScene();
  41359. // Geometry
  41360. var geometryId = parsedGeometry.geometryId;
  41361. if (geometryId) {
  41362. var geometry = scene.getGeometryByID(geometryId);
  41363. if (geometry) {
  41364. geometry.applyToMesh(mesh);
  41365. }
  41366. }
  41367. else if (parsedGeometry instanceof ArrayBuffer) {
  41368. var binaryInfo = mesh._binaryInfo;
  41369. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41370. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41371. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41372. }
  41373. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41374. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41375. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41376. }
  41377. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41378. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41379. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41380. }
  41381. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41382. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41383. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41384. }
  41385. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41386. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41387. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41388. }
  41389. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41390. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41391. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41392. }
  41393. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41394. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41395. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41396. }
  41397. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41398. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41399. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41400. }
  41401. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41402. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41403. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41404. }
  41405. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41406. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41407. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41408. }
  41409. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41410. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41411. var floatIndices = [];
  41412. for (var i = 0; i < matricesIndicesData.length; i++) {
  41413. var index = matricesIndicesData[i];
  41414. floatIndices.push(index & 0x000000FF);
  41415. floatIndices.push((index & 0x0000FF00) >> 8);
  41416. floatIndices.push((index & 0x00FF0000) >> 16);
  41417. floatIndices.push(index >> 24);
  41418. }
  41419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41420. }
  41421. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41422. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41424. }
  41425. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41426. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41427. mesh.setIndices(indicesData, null);
  41428. }
  41429. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41430. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41431. mesh.subMeshes = [];
  41432. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41433. var materialIndex = subMeshesData[(i * 5) + 0];
  41434. var verticesStart = subMeshesData[(i * 5) + 1];
  41435. var verticesCount = subMeshesData[(i * 5) + 2];
  41436. var indexStart = subMeshesData[(i * 5) + 3];
  41437. var indexCount = subMeshesData[(i * 5) + 4];
  41438. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41439. }
  41440. }
  41441. }
  41442. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41443. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41444. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41445. if (parsedGeometry.tangents) {
  41446. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41447. }
  41448. if (parsedGeometry.uvs) {
  41449. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41450. }
  41451. if (parsedGeometry.uvs2) {
  41452. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41453. }
  41454. if (parsedGeometry.uvs3) {
  41455. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41456. }
  41457. if (parsedGeometry.uvs4) {
  41458. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41459. }
  41460. if (parsedGeometry.uvs5) {
  41461. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41462. }
  41463. if (parsedGeometry.uvs6) {
  41464. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41465. }
  41466. if (parsedGeometry.colors) {
  41467. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41468. }
  41469. if (parsedGeometry.matricesIndices) {
  41470. if (!parsedGeometry.matricesIndices._isExpanded) {
  41471. var floatIndices = [];
  41472. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41473. var matricesIndex = parsedGeometry.matricesIndices[i];
  41474. floatIndices.push(matricesIndex & 0x000000FF);
  41475. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41476. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41477. floatIndices.push(matricesIndex >> 24);
  41478. }
  41479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41480. }
  41481. else {
  41482. delete parsedGeometry.matricesIndices._isExpanded;
  41483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41484. }
  41485. }
  41486. if (parsedGeometry.matricesIndicesExtra) {
  41487. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41488. var floatIndices = [];
  41489. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41490. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41491. floatIndices.push(matricesIndex & 0x000000FF);
  41492. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41493. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41494. floatIndices.push(matricesIndex >> 24);
  41495. }
  41496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41497. }
  41498. else {
  41499. delete parsedGeometry.matricesIndices._isExpanded;
  41500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41501. }
  41502. }
  41503. if (parsedGeometry.matricesWeights) {
  41504. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41506. }
  41507. if (parsedGeometry.matricesWeightsExtra) {
  41508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41509. }
  41510. mesh.setIndices(parsedGeometry.indices, null);
  41511. }
  41512. // SubMeshes
  41513. if (parsedGeometry.subMeshes) {
  41514. mesh.subMeshes = [];
  41515. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41516. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41517. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41518. }
  41519. }
  41520. // Flat shading
  41521. if (mesh._shouldGenerateFlatShading) {
  41522. mesh.convertToFlatShadedMesh();
  41523. delete mesh._shouldGenerateFlatShading;
  41524. }
  41525. // Update
  41526. mesh.computeWorldMatrix(true);
  41527. scene.onMeshImportedObservable.notifyObservers(mesh);
  41528. };
  41529. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41530. var epsilon = 1e-3;
  41531. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41532. return;
  41533. }
  41534. var noInfluenceBoneIndex = 0.0;
  41535. if (parsedGeometry.skeletonId > -1) {
  41536. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41537. if (!skeleton) {
  41538. return;
  41539. }
  41540. noInfluenceBoneIndex = skeleton.bones.length;
  41541. }
  41542. else {
  41543. return;
  41544. }
  41545. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41546. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41547. var matricesWeights = parsedGeometry.matricesWeights;
  41548. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41549. var influencers = parsedGeometry.numBoneInfluencer;
  41550. var size = matricesWeights.length;
  41551. for (var i = 0; i < size; i += 4) {
  41552. var weight = 0.0;
  41553. var firstZeroWeight = -1;
  41554. for (var j = 0; j < 4; j++) {
  41555. var w = matricesWeights[i + j];
  41556. weight += w;
  41557. if (w < epsilon && firstZeroWeight < 0) {
  41558. firstZeroWeight = j;
  41559. }
  41560. }
  41561. if (matricesWeightsExtra) {
  41562. for (var j = 0; j < 4; j++) {
  41563. var w = matricesWeightsExtra[i + j];
  41564. weight += w;
  41565. if (w < epsilon && firstZeroWeight < 0) {
  41566. firstZeroWeight = j + 4;
  41567. }
  41568. }
  41569. }
  41570. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41571. firstZeroWeight = influencers - 1;
  41572. }
  41573. if (weight > epsilon) {
  41574. var mweight = 1.0 / weight;
  41575. for (var j = 0; j < 4; j++) {
  41576. matricesWeights[i + j] *= mweight;
  41577. }
  41578. if (matricesWeightsExtra) {
  41579. for (var j = 0; j < 4; j++) {
  41580. matricesWeightsExtra[i + j] *= mweight;
  41581. }
  41582. }
  41583. }
  41584. else {
  41585. if (firstZeroWeight >= 4) {
  41586. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41587. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41588. }
  41589. else {
  41590. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41591. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41592. }
  41593. }
  41594. }
  41595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41596. if (parsedGeometry.matricesWeightsExtra) {
  41597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41598. }
  41599. };
  41600. /**
  41601. * Create a new geometry from persisted data (Using .babylon file format)
  41602. * @param parsedVertexData defines the persisted data
  41603. * @param scene defines the hosting scene
  41604. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41605. * @returns the new geometry object
  41606. */
  41607. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41608. if (scene.getGeometryByID(parsedVertexData.id)) {
  41609. return null; // null since geometry could be something else than a box...
  41610. }
  41611. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41612. if (BABYLON.Tags) {
  41613. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41614. }
  41615. if (parsedVertexData.delayLoadingFile) {
  41616. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41617. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41618. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41619. geometry._delayInfo = [];
  41620. if (parsedVertexData.hasUVs) {
  41621. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41622. }
  41623. if (parsedVertexData.hasUVs2) {
  41624. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41625. }
  41626. if (parsedVertexData.hasUVs3) {
  41627. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41628. }
  41629. if (parsedVertexData.hasUVs4) {
  41630. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41631. }
  41632. if (parsedVertexData.hasUVs5) {
  41633. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41634. }
  41635. if (parsedVertexData.hasUVs6) {
  41636. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41637. }
  41638. if (parsedVertexData.hasColors) {
  41639. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41640. }
  41641. if (parsedVertexData.hasMatricesIndices) {
  41642. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41643. }
  41644. if (parsedVertexData.hasMatricesWeights) {
  41645. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41646. }
  41647. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41648. }
  41649. else {
  41650. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41651. }
  41652. scene.pushGeometry(geometry, true);
  41653. return geometry;
  41654. };
  41655. return Geometry;
  41656. }());
  41657. BABYLON.Geometry = Geometry;
  41658. // Primitives
  41659. /// Abstract class
  41660. /**
  41661. * Abstract class used to provide common services for all typed geometries
  41662. * @hidden
  41663. */
  41664. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41665. __extends(_PrimitiveGeometry, _super);
  41666. /**
  41667. * Creates a new typed geometry
  41668. * @param id defines the unique ID of the geometry
  41669. * @param scene defines the hosting scene
  41670. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41671. * @param mesh defines the hosting mesh (can be null)
  41672. */
  41673. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41674. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41675. if (mesh === void 0) { mesh = null; }
  41676. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41677. _this._canBeRegenerated = _canBeRegenerated;
  41678. _this._beingRegenerated = true;
  41679. _this.regenerate();
  41680. _this._beingRegenerated = false;
  41681. return _this;
  41682. }
  41683. /**
  41684. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41685. * @returns true if the geometry can be regenerated
  41686. */
  41687. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41688. return this._canBeRegenerated;
  41689. };
  41690. /**
  41691. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41692. */
  41693. _PrimitiveGeometry.prototype.regenerate = function () {
  41694. if (!this._canBeRegenerated) {
  41695. return;
  41696. }
  41697. this._beingRegenerated = true;
  41698. this.setAllVerticesData(this._regenerateVertexData(), false);
  41699. this._beingRegenerated = false;
  41700. };
  41701. /**
  41702. * Clone the geometry
  41703. * @param id defines the unique ID of the new geometry
  41704. * @returns the new geometry
  41705. */
  41706. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41707. return _super.prototype.copy.call(this, id);
  41708. };
  41709. // overrides
  41710. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41711. if (!this._beingRegenerated) {
  41712. return;
  41713. }
  41714. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41715. };
  41716. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41717. if (!this._beingRegenerated) {
  41718. return;
  41719. }
  41720. _super.prototype.setVerticesData.call(this, kind, data, false);
  41721. };
  41722. // to override
  41723. /** @hidden */
  41724. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41725. throw new Error("Abstract method");
  41726. };
  41727. _PrimitiveGeometry.prototype.copy = function (id) {
  41728. throw new Error("Must be overriden in sub-classes.");
  41729. };
  41730. _PrimitiveGeometry.prototype.serialize = function () {
  41731. var serializationObject = _super.prototype.serialize.call(this);
  41732. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41733. return serializationObject;
  41734. };
  41735. return _PrimitiveGeometry;
  41736. }(Geometry));
  41737. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41738. /**
  41739. * Creates a ribbon geometry
  41740. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41741. */
  41742. var RibbonGeometry = /** @class */ (function (_super) {
  41743. __extends(RibbonGeometry, _super);
  41744. /**
  41745. * Creates a ribbon geometry
  41746. * @param id defines the unique ID of the geometry
  41747. * @param scene defines the hosting scene
  41748. * @param pathArray defines the array of paths to use
  41749. * @param closeArray defines if the last path and the first path must be joined
  41750. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41751. * @param offset defines the offset between points
  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. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41755. */
  41756. function RibbonGeometry(id, scene,
  41757. /**
  41758. * Defines the array of paths to use
  41759. */
  41760. pathArray,
  41761. /**
  41762. * Defines if the last and first points of each path in your pathArray must be joined
  41763. */
  41764. closeArray,
  41765. /**
  41766. * Defines if the last and first points of each path in your pathArray must be joined
  41767. */
  41768. closePath,
  41769. /**
  41770. * Defines the offset between points
  41771. */
  41772. offset, canBeRegenerated, mesh,
  41773. /**
  41774. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41775. */
  41776. side) {
  41777. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41779. _this.pathArray = pathArray;
  41780. _this.closeArray = closeArray;
  41781. _this.closePath = closePath;
  41782. _this.offset = offset;
  41783. _this.side = side;
  41784. return _this;
  41785. }
  41786. /** @hidden */
  41787. RibbonGeometry.prototype._regenerateVertexData = function () {
  41788. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41789. };
  41790. RibbonGeometry.prototype.copy = function (id) {
  41791. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41792. };
  41793. return RibbonGeometry;
  41794. }(_PrimitiveGeometry));
  41795. BABYLON.RibbonGeometry = RibbonGeometry;
  41796. /**
  41797. * Creates a box geometry
  41798. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41799. */
  41800. var BoxGeometry = /** @class */ (function (_super) {
  41801. __extends(BoxGeometry, _super);
  41802. /**
  41803. * Creates a box geometry
  41804. * @param id defines the unique ID of the geometry
  41805. * @param scene defines the hosting scene
  41806. * @param size defines the zise of the box (width, height and depth are the same)
  41807. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41808. * @param mesh defines the hosting mesh (can be null)
  41809. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41810. */
  41811. function BoxGeometry(id, scene,
  41812. /**
  41813. * Defines the zise of the box (width, height and depth are the same)
  41814. */
  41815. size, canBeRegenerated, mesh,
  41816. /**
  41817. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41818. */
  41819. side) {
  41820. if (mesh === void 0) { mesh = null; }
  41821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41822. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41823. _this.size = size;
  41824. _this.side = side;
  41825. return _this;
  41826. }
  41827. /** @hidden */
  41828. BoxGeometry.prototype._regenerateVertexData = function () {
  41829. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41830. };
  41831. BoxGeometry.prototype.copy = function (id) {
  41832. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41833. };
  41834. BoxGeometry.prototype.serialize = function () {
  41835. var serializationObject = _super.prototype.serialize.call(this);
  41836. serializationObject.size = this.size;
  41837. return serializationObject;
  41838. };
  41839. BoxGeometry.Parse = function (parsedBox, scene) {
  41840. if (scene.getGeometryByID(parsedBox.id)) {
  41841. return null; // null since geometry could be something else than a box...
  41842. }
  41843. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41844. if (BABYLON.Tags) {
  41845. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41846. }
  41847. scene.pushGeometry(box, true);
  41848. return box;
  41849. };
  41850. return BoxGeometry;
  41851. }(_PrimitiveGeometry));
  41852. BABYLON.BoxGeometry = BoxGeometry;
  41853. /**
  41854. * Creates a sphere geometry
  41855. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41856. */
  41857. var SphereGeometry = /** @class */ (function (_super) {
  41858. __extends(SphereGeometry, _super);
  41859. /**
  41860. * Create a new sphere geometry
  41861. * @param id defines the unique ID of the geometry
  41862. * @param scene defines the hosting scene
  41863. * @param segments defines the number of segments to use to create the sphere
  41864. * @param diameter defines the diameter of the sphere
  41865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41866. * @param mesh defines the hosting mesh (can be null)
  41867. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41868. */
  41869. function SphereGeometry(id, scene,
  41870. /**
  41871. * Defines the number of segments to use to create the sphere
  41872. */
  41873. segments,
  41874. /**
  41875. * Defines the diameter of the sphere
  41876. */
  41877. diameter, canBeRegenerated, mesh,
  41878. /**
  41879. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41880. */
  41881. side) {
  41882. if (mesh === void 0) { mesh = null; }
  41883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41885. _this.segments = segments;
  41886. _this.diameter = diameter;
  41887. _this.side = side;
  41888. return _this;
  41889. }
  41890. /** @hidden */
  41891. SphereGeometry.prototype._regenerateVertexData = function () {
  41892. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41893. };
  41894. SphereGeometry.prototype.copy = function (id) {
  41895. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41896. };
  41897. SphereGeometry.prototype.serialize = function () {
  41898. var serializationObject = _super.prototype.serialize.call(this);
  41899. serializationObject.segments = this.segments;
  41900. serializationObject.diameter = this.diameter;
  41901. return serializationObject;
  41902. };
  41903. SphereGeometry.Parse = function (parsedSphere, scene) {
  41904. if (scene.getGeometryByID(parsedSphere.id)) {
  41905. return null; // null since geometry could be something else than a sphere...
  41906. }
  41907. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41908. if (BABYLON.Tags) {
  41909. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41910. }
  41911. scene.pushGeometry(sphere, true);
  41912. return sphere;
  41913. };
  41914. return SphereGeometry;
  41915. }(_PrimitiveGeometry));
  41916. BABYLON.SphereGeometry = SphereGeometry;
  41917. /**
  41918. * Creates a disc geometry
  41919. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41920. */
  41921. var DiscGeometry = /** @class */ (function (_super) {
  41922. __extends(DiscGeometry, _super);
  41923. /**
  41924. * Creates a new disc geometry
  41925. * @param id defines the unique ID of the geometry
  41926. * @param scene defines the hosting scene
  41927. * @param radius defines the radius of the disc
  41928. * @param tessellation defines the tesselation factor to apply to the disc
  41929. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41930. * @param mesh defines the hosting mesh (can be null)
  41931. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41932. */
  41933. function DiscGeometry(id, scene,
  41934. /**
  41935. * Defines the radius of the disc
  41936. */
  41937. radius,
  41938. /**
  41939. * Defines the tesselation factor to apply to the disc
  41940. */
  41941. tessellation, canBeRegenerated, mesh,
  41942. /**
  41943. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41944. */
  41945. side) {
  41946. if (mesh === void 0) { mesh = null; }
  41947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41948. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41949. _this.radius = radius;
  41950. _this.tessellation = tessellation;
  41951. _this.side = side;
  41952. return _this;
  41953. }
  41954. /** @hidden */
  41955. DiscGeometry.prototype._regenerateVertexData = function () {
  41956. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41957. };
  41958. DiscGeometry.prototype.copy = function (id) {
  41959. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41960. };
  41961. return DiscGeometry;
  41962. }(_PrimitiveGeometry));
  41963. BABYLON.DiscGeometry = DiscGeometry;
  41964. /**
  41965. * Creates a new cylinder geometry
  41966. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41967. */
  41968. var CylinderGeometry = /** @class */ (function (_super) {
  41969. __extends(CylinderGeometry, _super);
  41970. /**
  41971. * Creates a new cylinder geometry
  41972. * @param id defines the unique ID of the geometry
  41973. * @param scene defines the hosting scene
  41974. * @param height defines the height of the cylinder
  41975. * @param diameterTop defines the diameter of the cylinder's top cap
  41976. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41977. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41978. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41979. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41980. * @param mesh defines the hosting mesh (can be null)
  41981. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41982. */
  41983. function CylinderGeometry(id, scene,
  41984. /**
  41985. * Defines the height of the cylinder
  41986. */
  41987. height,
  41988. /**
  41989. * Defines the diameter of the cylinder's top cap
  41990. */
  41991. diameterTop,
  41992. /**
  41993. * Defines the diameter of the cylinder's bottom cap
  41994. */
  41995. diameterBottom,
  41996. /**
  41997. * Defines the tessellation factor to apply to the cylinder
  41998. */
  41999. tessellation,
  42000. /**
  42001. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42002. */
  42003. subdivisions, canBeRegenerated, mesh,
  42004. /**
  42005. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42006. */
  42007. side) {
  42008. if (subdivisions === void 0) { subdivisions = 1; }
  42009. if (mesh === void 0) { mesh = null; }
  42010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42011. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42012. _this.height = height;
  42013. _this.diameterTop = diameterTop;
  42014. _this.diameterBottom = diameterBottom;
  42015. _this.tessellation = tessellation;
  42016. _this.subdivisions = subdivisions;
  42017. _this.side = side;
  42018. return _this;
  42019. }
  42020. /** @hidden */
  42021. CylinderGeometry.prototype._regenerateVertexData = function () {
  42022. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42023. };
  42024. CylinderGeometry.prototype.copy = function (id) {
  42025. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42026. };
  42027. CylinderGeometry.prototype.serialize = function () {
  42028. var serializationObject = _super.prototype.serialize.call(this);
  42029. serializationObject.height = this.height;
  42030. serializationObject.diameterTop = this.diameterTop;
  42031. serializationObject.diameterBottom = this.diameterBottom;
  42032. serializationObject.tessellation = this.tessellation;
  42033. return serializationObject;
  42034. };
  42035. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42036. if (scene.getGeometryByID(parsedCylinder.id)) {
  42037. return null; // null since geometry could be something else than a cylinder...
  42038. }
  42039. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42040. if (BABYLON.Tags) {
  42041. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42042. }
  42043. scene.pushGeometry(cylinder, true);
  42044. return cylinder;
  42045. };
  42046. return CylinderGeometry;
  42047. }(_PrimitiveGeometry));
  42048. BABYLON.CylinderGeometry = CylinderGeometry;
  42049. /**
  42050. * Creates a new torus geometry
  42051. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42052. */
  42053. var TorusGeometry = /** @class */ (function (_super) {
  42054. __extends(TorusGeometry, _super);
  42055. /**
  42056. * Creates a new torus geometry
  42057. * @param id defines the unique ID of the geometry
  42058. * @param scene defines the hosting scene
  42059. * @param diameter defines the diameter of the torus
  42060. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42061. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42062. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42063. * @param mesh defines the hosting mesh (can be null)
  42064. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42065. */
  42066. function TorusGeometry(id, scene,
  42067. /**
  42068. * Defines the diameter of the torus
  42069. */
  42070. diameter,
  42071. /**
  42072. * Defines the thickness of the torus (ie. internal diameter)
  42073. */
  42074. thickness,
  42075. /**
  42076. * Defines the tesselation factor to apply to the torus
  42077. */
  42078. tessellation, canBeRegenerated, mesh,
  42079. /**
  42080. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42081. */
  42082. side) {
  42083. if (mesh === void 0) { mesh = null; }
  42084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42086. _this.diameter = diameter;
  42087. _this.thickness = thickness;
  42088. _this.tessellation = tessellation;
  42089. _this.side = side;
  42090. return _this;
  42091. }
  42092. /** @hidden */
  42093. TorusGeometry.prototype._regenerateVertexData = function () {
  42094. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42095. };
  42096. TorusGeometry.prototype.copy = function (id) {
  42097. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42098. };
  42099. TorusGeometry.prototype.serialize = function () {
  42100. var serializationObject = _super.prototype.serialize.call(this);
  42101. serializationObject.diameter = this.diameter;
  42102. serializationObject.thickness = this.thickness;
  42103. serializationObject.tessellation = this.tessellation;
  42104. return serializationObject;
  42105. };
  42106. TorusGeometry.Parse = function (parsedTorus, scene) {
  42107. if (scene.getGeometryByID(parsedTorus.id)) {
  42108. return null; // null since geometry could be something else than a torus...
  42109. }
  42110. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42111. if (BABYLON.Tags) {
  42112. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42113. }
  42114. scene.pushGeometry(torus, true);
  42115. return torus;
  42116. };
  42117. return TorusGeometry;
  42118. }(_PrimitiveGeometry));
  42119. BABYLON.TorusGeometry = TorusGeometry;
  42120. /**
  42121. * Creates a new ground geometry
  42122. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42123. */
  42124. var GroundGeometry = /** @class */ (function (_super) {
  42125. __extends(GroundGeometry, _super);
  42126. /**
  42127. * Creates a new ground geometry
  42128. * @param id defines the unique ID of the geometry
  42129. * @param scene defines the hosting scene
  42130. * @param width defines the width of the ground
  42131. * @param height defines the height of the ground
  42132. * @param subdivisions defines the subdivisions to apply to the ground
  42133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42134. * @param mesh defines the hosting mesh (can be null)
  42135. */
  42136. function GroundGeometry(id, scene,
  42137. /**
  42138. * Defines the width of the ground
  42139. */
  42140. width,
  42141. /**
  42142. * Defines the height of the ground
  42143. */
  42144. height,
  42145. /**
  42146. * Defines the subdivisions to apply to the ground
  42147. */
  42148. subdivisions, canBeRegenerated, mesh) {
  42149. if (mesh === void 0) { mesh = null; }
  42150. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42151. _this.width = width;
  42152. _this.height = height;
  42153. _this.subdivisions = subdivisions;
  42154. return _this;
  42155. }
  42156. /** @hidden */
  42157. GroundGeometry.prototype._regenerateVertexData = function () {
  42158. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42159. };
  42160. GroundGeometry.prototype.copy = function (id) {
  42161. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42162. };
  42163. GroundGeometry.prototype.serialize = function () {
  42164. var serializationObject = _super.prototype.serialize.call(this);
  42165. serializationObject.width = this.width;
  42166. serializationObject.height = this.height;
  42167. serializationObject.subdivisions = this.subdivisions;
  42168. return serializationObject;
  42169. };
  42170. GroundGeometry.Parse = function (parsedGround, scene) {
  42171. if (scene.getGeometryByID(parsedGround.id)) {
  42172. return null; // null since geometry could be something else than a ground...
  42173. }
  42174. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42175. if (BABYLON.Tags) {
  42176. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42177. }
  42178. scene.pushGeometry(ground, true);
  42179. return ground;
  42180. };
  42181. return GroundGeometry;
  42182. }(_PrimitiveGeometry));
  42183. BABYLON.GroundGeometry = GroundGeometry;
  42184. /**
  42185. * Creates a tiled ground geometry
  42186. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42187. */
  42188. var TiledGroundGeometry = /** @class */ (function (_super) {
  42189. __extends(TiledGroundGeometry, _super);
  42190. /**
  42191. * Creates a tiled ground geometry
  42192. * @param id defines the unique ID of the geometry
  42193. * @param scene defines the hosting scene
  42194. * @param xmin defines the minimum value on X axis
  42195. * @param zmin defines the minimum value on Z axis
  42196. * @param xmax defines the maximum value on X axis
  42197. * @param zmax defines the maximum value on Z axis
  42198. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42199. * @param precision defines the precision to use when computing the tiles
  42200. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42201. * @param mesh defines the hosting mesh (can be null)
  42202. */
  42203. function TiledGroundGeometry(id, scene,
  42204. /**
  42205. * Defines the minimum value on X axis
  42206. */
  42207. xmin,
  42208. /**
  42209. * Defines the minimum value on Z axis
  42210. */
  42211. zmin,
  42212. /**
  42213. * Defines the maximum value on X axis
  42214. */
  42215. xmax,
  42216. /**
  42217. * Defines the maximum value on Z axis
  42218. */
  42219. zmax,
  42220. /**
  42221. * Defines the subdivisions to apply to the ground
  42222. */
  42223. subdivisions,
  42224. /**
  42225. * Defines the precision to use when computing the tiles
  42226. */
  42227. precision, canBeRegenerated, mesh) {
  42228. if (mesh === void 0) { mesh = null; }
  42229. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42230. _this.xmin = xmin;
  42231. _this.zmin = zmin;
  42232. _this.xmax = xmax;
  42233. _this.zmax = zmax;
  42234. _this.subdivisions = subdivisions;
  42235. _this.precision = precision;
  42236. return _this;
  42237. }
  42238. /** @hidden */
  42239. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42240. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42241. };
  42242. TiledGroundGeometry.prototype.copy = function (id) {
  42243. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42244. };
  42245. return TiledGroundGeometry;
  42246. }(_PrimitiveGeometry));
  42247. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42248. /**
  42249. * Creates a plane geometry
  42250. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42251. */
  42252. var PlaneGeometry = /** @class */ (function (_super) {
  42253. __extends(PlaneGeometry, _super);
  42254. /**
  42255. * Creates a plane geometry
  42256. * @param id defines the unique ID of the geometry
  42257. * @param scene defines the hosting scene
  42258. * @param size defines the size of the plane (width === height)
  42259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42260. * @param mesh defines the hosting mesh (can be null)
  42261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42262. */
  42263. function PlaneGeometry(id, scene,
  42264. /**
  42265. * Defines the size of the plane (width === height)
  42266. */
  42267. size, canBeRegenerated, mesh,
  42268. /**
  42269. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42270. */
  42271. side) {
  42272. if (mesh === void 0) { mesh = null; }
  42273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42275. _this.size = size;
  42276. _this.side = side;
  42277. return _this;
  42278. }
  42279. /** @hidden */
  42280. PlaneGeometry.prototype._regenerateVertexData = function () {
  42281. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42282. };
  42283. PlaneGeometry.prototype.copy = function (id) {
  42284. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42285. };
  42286. PlaneGeometry.prototype.serialize = function () {
  42287. var serializationObject = _super.prototype.serialize.call(this);
  42288. serializationObject.size = this.size;
  42289. return serializationObject;
  42290. };
  42291. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42292. if (scene.getGeometryByID(parsedPlane.id)) {
  42293. return null; // null since geometry could be something else than a ground...
  42294. }
  42295. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42296. if (BABYLON.Tags) {
  42297. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42298. }
  42299. scene.pushGeometry(plane, true);
  42300. return plane;
  42301. };
  42302. return PlaneGeometry;
  42303. }(_PrimitiveGeometry));
  42304. BABYLON.PlaneGeometry = PlaneGeometry;
  42305. /**
  42306. * Creates a torus knot geometry
  42307. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42308. */
  42309. var TorusKnotGeometry = /** @class */ (function (_super) {
  42310. __extends(TorusKnotGeometry, _super);
  42311. /**
  42312. * Creates a torus knot geometry
  42313. * @param id defines the unique ID of the geometry
  42314. * @param scene defines the hosting scene
  42315. * @param radius defines the radius of the torus knot
  42316. * @param tube defines the thickness of the torus knot tube
  42317. * @param radialSegments defines the number of radial segments
  42318. * @param tubularSegments defines the number of tubular segments
  42319. * @param p defines the first number of windings
  42320. * @param q defines the second number of windings
  42321. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42322. * @param mesh defines the hosting mesh (can be null)
  42323. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42324. */
  42325. function TorusKnotGeometry(id, scene,
  42326. /**
  42327. * Defines the radius of the torus knot
  42328. */
  42329. radius,
  42330. /**
  42331. * Defines the thickness of the torus knot tube
  42332. */
  42333. tube,
  42334. /**
  42335. * Defines the number of radial segments
  42336. */
  42337. radialSegments,
  42338. /**
  42339. * Defines the number of tubular segments
  42340. */
  42341. tubularSegments,
  42342. /**
  42343. * Defines the first number of windings
  42344. */
  42345. p,
  42346. /**
  42347. * Defines the second number of windings
  42348. */
  42349. q, canBeRegenerated, mesh,
  42350. /**
  42351. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42352. */
  42353. side) {
  42354. if (mesh === void 0) { mesh = null; }
  42355. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42356. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42357. _this.radius = radius;
  42358. _this.tube = tube;
  42359. _this.radialSegments = radialSegments;
  42360. _this.tubularSegments = tubularSegments;
  42361. _this.p = p;
  42362. _this.q = q;
  42363. _this.side = side;
  42364. return _this;
  42365. }
  42366. /** @hidden */
  42367. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42368. 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 });
  42369. };
  42370. TorusKnotGeometry.prototype.copy = function (id) {
  42371. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42372. };
  42373. TorusKnotGeometry.prototype.serialize = function () {
  42374. var serializationObject = _super.prototype.serialize.call(this);
  42375. serializationObject.radius = this.radius;
  42376. serializationObject.tube = this.tube;
  42377. serializationObject.radialSegments = this.radialSegments;
  42378. serializationObject.tubularSegments = this.tubularSegments;
  42379. serializationObject.p = this.p;
  42380. serializationObject.q = this.q;
  42381. return serializationObject;
  42382. };
  42383. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42384. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42385. return null; // null since geometry could be something else than a ground...
  42386. }
  42387. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42388. if (BABYLON.Tags) {
  42389. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42390. }
  42391. scene.pushGeometry(torusKnot, true);
  42392. return torusKnot;
  42393. };
  42394. return TorusKnotGeometry;
  42395. }(_PrimitiveGeometry));
  42396. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42397. //}
  42398. })(BABYLON || (BABYLON = {}));
  42399. //# sourceMappingURL=babylon.geometry.js.map
  42400. var BABYLON;
  42401. (function (BABYLON) {
  42402. /**
  42403. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42404. */
  42405. var PerformanceMonitor = /** @class */ (function () {
  42406. /**
  42407. * constructor
  42408. * @param frameSampleSize The number of samples required to saturate the sliding window
  42409. */
  42410. function PerformanceMonitor(frameSampleSize) {
  42411. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42412. this._enabled = true;
  42413. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42414. }
  42415. /**
  42416. * Samples current frame
  42417. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42418. */
  42419. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42420. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42421. if (!this._enabled) {
  42422. return;
  42423. }
  42424. if (this._lastFrameTimeMs != null) {
  42425. var dt = timeMs - this._lastFrameTimeMs;
  42426. this._rollingFrameTime.add(dt);
  42427. }
  42428. this._lastFrameTimeMs = timeMs;
  42429. };
  42430. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42431. /**
  42432. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42433. */
  42434. get: function () {
  42435. return this._rollingFrameTime.average;
  42436. },
  42437. enumerable: true,
  42438. configurable: true
  42439. });
  42440. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42441. /**
  42442. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42443. */
  42444. get: function () {
  42445. return this._rollingFrameTime.variance;
  42446. },
  42447. enumerable: true,
  42448. configurable: true
  42449. });
  42450. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42451. /**
  42452. * Returns the frame time of the most recent frame
  42453. */
  42454. get: function () {
  42455. return this._rollingFrameTime.history(0);
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42461. /**
  42462. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42463. */
  42464. get: function () {
  42465. return 1000.0 / this._rollingFrameTime.average;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42471. /**
  42472. * Returns the average framerate in frames per second using the most recent frame time
  42473. */
  42474. get: function () {
  42475. var history = this._rollingFrameTime.history(0);
  42476. if (history === 0) {
  42477. return 0;
  42478. }
  42479. return 1000.0 / history;
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42485. /**
  42486. * Returns true if enough samples have been taken to completely fill the sliding window
  42487. */
  42488. get: function () {
  42489. return this._rollingFrameTime.isSaturated();
  42490. },
  42491. enumerable: true,
  42492. configurable: true
  42493. });
  42494. /**
  42495. * Enables contributions to the sliding window sample set
  42496. */
  42497. PerformanceMonitor.prototype.enable = function () {
  42498. this._enabled = true;
  42499. };
  42500. /**
  42501. * Disables contributions to the sliding window sample set
  42502. * Samples will not be interpolated over the disabled period
  42503. */
  42504. PerformanceMonitor.prototype.disable = function () {
  42505. this._enabled = false;
  42506. //clear last sample to avoid interpolating over the disabled period when next enabled
  42507. this._lastFrameTimeMs = null;
  42508. };
  42509. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42510. /**
  42511. * Returns true if sampling is enabled
  42512. */
  42513. get: function () {
  42514. return this._enabled;
  42515. },
  42516. enumerable: true,
  42517. configurable: true
  42518. });
  42519. /**
  42520. * Resets performance monitor
  42521. */
  42522. PerformanceMonitor.prototype.reset = function () {
  42523. //clear last sample to avoid interpolating over the disabled period when next enabled
  42524. this._lastFrameTimeMs = null;
  42525. //wipe record
  42526. this._rollingFrameTime.reset();
  42527. };
  42528. return PerformanceMonitor;
  42529. }());
  42530. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42531. /**
  42532. * RollingAverage
  42533. *
  42534. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42535. */
  42536. var RollingAverage = /** @class */ (function () {
  42537. /**
  42538. * constructor
  42539. * @param length The number of samples required to saturate the sliding window
  42540. */
  42541. function RollingAverage(length) {
  42542. this._samples = new Array(length);
  42543. this.reset();
  42544. }
  42545. /**
  42546. * Adds a sample to the sample set
  42547. * @param v The sample value
  42548. */
  42549. RollingAverage.prototype.add = function (v) {
  42550. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42551. var delta;
  42552. //we need to check if we've already wrapped round
  42553. if (this.isSaturated()) {
  42554. //remove bottom of stack from mean
  42555. var bottomValue = this._samples[this._pos];
  42556. delta = bottomValue - this.average;
  42557. this.average -= delta / (this._sampleCount - 1);
  42558. this._m2 -= delta * (bottomValue - this.average);
  42559. }
  42560. else {
  42561. this._sampleCount++;
  42562. }
  42563. //add new value to mean
  42564. delta = v - this.average;
  42565. this.average += delta / (this._sampleCount);
  42566. this._m2 += delta * (v - this.average);
  42567. //set the new variance
  42568. this.variance = this._m2 / (this._sampleCount - 1);
  42569. this._samples[this._pos] = v;
  42570. this._pos++;
  42571. this._pos %= this._samples.length; //positive wrap around
  42572. };
  42573. /**
  42574. * Returns previously added values or null if outside of history or outside the sliding window domain
  42575. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42576. * @return Value previously recorded with add() or null if outside of range
  42577. */
  42578. RollingAverage.prototype.history = function (i) {
  42579. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42580. return 0;
  42581. }
  42582. var i0 = this._wrapPosition(this._pos - 1.0);
  42583. return this._samples[this._wrapPosition(i0 - i)];
  42584. };
  42585. /**
  42586. * Returns true if enough samples have been taken to completely fill the sliding window
  42587. * @return true if sample-set saturated
  42588. */
  42589. RollingAverage.prototype.isSaturated = function () {
  42590. return this._sampleCount >= this._samples.length;
  42591. };
  42592. /**
  42593. * Resets the rolling average (equivalent to 0 samples taken so far)
  42594. */
  42595. RollingAverage.prototype.reset = function () {
  42596. this.average = 0;
  42597. this.variance = 0;
  42598. this._sampleCount = 0;
  42599. this._pos = 0;
  42600. this._m2 = 0;
  42601. };
  42602. /**
  42603. * Wraps a value around the sample range boundaries
  42604. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42605. * @return Wrapped position in sample range
  42606. */
  42607. RollingAverage.prototype._wrapPosition = function (i) {
  42608. var max = this._samples.length;
  42609. return ((i % max) + max) % max;
  42610. };
  42611. return RollingAverage;
  42612. }());
  42613. BABYLON.RollingAverage = RollingAverage;
  42614. })(BABYLON || (BABYLON = {}));
  42615. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42616. var BABYLON;
  42617. (function (BABYLON) {
  42618. /**
  42619. * "Static Class" containing the most commonly used helper while dealing with material for
  42620. * rendering purpose.
  42621. *
  42622. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42623. *
  42624. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42625. */
  42626. var MaterialHelper = /** @class */ (function () {
  42627. function MaterialHelper() {
  42628. }
  42629. /**
  42630. * Bind the current view position to an effect.
  42631. * @param effect The effect to be bound
  42632. * @param scene The scene the eyes position is used from
  42633. */
  42634. MaterialHelper.BindEyePosition = function (effect, scene) {
  42635. if (scene._forcedViewPosition) {
  42636. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42637. return;
  42638. }
  42639. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42640. };
  42641. /**
  42642. * Helps preparing the defines values about the UVs in used in the effect.
  42643. * UVs are shared as much as we can accross channels in the shaders.
  42644. * @param texture The texture we are preparing the UVs for
  42645. * @param defines The defines to update
  42646. * @param key The channel key "diffuse", "specular"... used in the shader
  42647. */
  42648. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42649. defines._needUVs = true;
  42650. defines[key] = true;
  42651. if (texture.getTextureMatrix().isIdentity(true)) {
  42652. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42653. if (texture.coordinatesIndex === 0) {
  42654. defines["MAINUV1"] = true;
  42655. }
  42656. else {
  42657. defines["MAINUV2"] = true;
  42658. }
  42659. }
  42660. else {
  42661. defines[key + "DIRECTUV"] = 0;
  42662. }
  42663. };
  42664. /**
  42665. * Binds a texture matrix value to its corrsponding uniform
  42666. * @param texture The texture to bind the matrix for
  42667. * @param uniformBuffer The uniform buffer receivin the data
  42668. * @param key The channel key "diffuse", "specular"... used in the shader
  42669. */
  42670. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42671. var matrix = texture.getTextureMatrix();
  42672. if (!matrix.isIdentity(true)) {
  42673. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42674. }
  42675. };
  42676. /**
  42677. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42678. * @param mesh defines the current mesh
  42679. * @param scene defines the current scene
  42680. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42681. * @param pointsCloud defines if point cloud rendering has to be turned on
  42682. * @param fogEnabled defines if fog has to be turned on
  42683. * @param alphaTest defines if alpha testing has to be turned on
  42684. * @param defines defines the current list of defines
  42685. */
  42686. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42687. if (defines._areMiscDirty) {
  42688. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42689. defines["POINTSIZE"] = pointsCloud;
  42690. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42691. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42692. defines["ALPHATEST"] = alphaTest;
  42693. }
  42694. };
  42695. /**
  42696. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42697. * @param scene defines the current scene
  42698. * @param engine defines the current engine
  42699. * @param defines specifies the list of active defines
  42700. * @param useInstances defines if instances have to be turned on
  42701. * @param useClipPlane defines if clip plane have to be turned on
  42702. */
  42703. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42704. if (useClipPlane === void 0) { useClipPlane = null; }
  42705. var changed = false;
  42706. var useClipPlane1 = false;
  42707. var useClipPlane2 = false;
  42708. var useClipPlane3 = false;
  42709. var useClipPlane4 = false;
  42710. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42711. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42712. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42713. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42714. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42715. defines["CLIPPLANE"] = useClipPlane1;
  42716. changed = true;
  42717. }
  42718. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42719. defines["CLIPPLANE2"] = useClipPlane2;
  42720. changed = true;
  42721. }
  42722. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42723. defines["CLIPPLANE3"] = useClipPlane3;
  42724. changed = true;
  42725. }
  42726. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42727. defines["CLIPPLANE4"] = useClipPlane4;
  42728. changed = true;
  42729. }
  42730. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42731. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42732. changed = true;
  42733. }
  42734. if (defines["INSTANCES"] !== useInstances) {
  42735. defines["INSTANCES"] = useInstances;
  42736. changed = true;
  42737. }
  42738. if (changed) {
  42739. defines.markAsUnprocessed();
  42740. }
  42741. };
  42742. /**
  42743. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42744. * @param mesh The mesh containing the geometry data we will draw
  42745. * @param defines The defines to update
  42746. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42747. * @param useBones Precise whether bones should be used or not (override mesh info)
  42748. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42749. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42750. * @returns false if defines are considered not dirty and have not been checked
  42751. */
  42752. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42753. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42754. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42755. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42756. return false;
  42757. }
  42758. defines._normals = defines._needNormals;
  42759. defines._uvs = defines._needUVs;
  42760. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42761. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42762. defines["TANGENT"] = true;
  42763. }
  42764. if (defines._needUVs) {
  42765. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42766. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42767. }
  42768. else {
  42769. defines["UV1"] = false;
  42770. defines["UV2"] = false;
  42771. }
  42772. if (useVertexColor) {
  42773. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42774. defines["VERTEXCOLOR"] = hasVertexColors;
  42775. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42776. }
  42777. if (useBones) {
  42778. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42779. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42780. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42781. }
  42782. else {
  42783. defines["NUM_BONE_INFLUENCERS"] = 0;
  42784. defines["BonesPerMesh"] = 0;
  42785. }
  42786. }
  42787. if (useMorphTargets) {
  42788. var manager = mesh.morphTargetManager;
  42789. if (manager) {
  42790. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42791. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42792. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42793. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42794. }
  42795. else {
  42796. defines["MORPHTARGETS_TANGENT"] = false;
  42797. defines["MORPHTARGETS_NORMAL"] = false;
  42798. defines["MORPHTARGETS"] = false;
  42799. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42800. }
  42801. }
  42802. return true;
  42803. };
  42804. /**
  42805. * Prepares the defines related to the light information passed in parameter
  42806. * @param scene The scene we are intending to draw
  42807. * @param mesh The mesh the effect is compiling for
  42808. * @param defines The defines to update
  42809. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42810. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42811. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42812. * @returns true if normals will be required for the rest of the effect
  42813. */
  42814. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42815. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42816. if (disableLighting === void 0) { disableLighting = false; }
  42817. if (!defines._areLightsDirty) {
  42818. return defines._needNormals;
  42819. }
  42820. var lightIndex = 0;
  42821. var needNormals = false;
  42822. var needRebuild = false;
  42823. var lightmapMode = false;
  42824. var shadowEnabled = false;
  42825. var specularEnabled = false;
  42826. if (scene.lightsEnabled && !disableLighting) {
  42827. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42828. var light = _a[_i];
  42829. needNormals = true;
  42830. if (defines["LIGHT" + lightIndex] === undefined) {
  42831. needRebuild = true;
  42832. }
  42833. defines["LIGHT" + lightIndex] = true;
  42834. defines["SPOTLIGHT" + lightIndex] = false;
  42835. defines["HEMILIGHT" + lightIndex] = false;
  42836. defines["POINTLIGHT" + lightIndex] = false;
  42837. defines["DIRLIGHT" + lightIndex] = false;
  42838. light.prepareLightSpecificDefines(defines, lightIndex);
  42839. // FallOff.
  42840. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42841. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42842. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42843. switch (light.falloffType) {
  42844. case BABYLON.Light.FALLOFF_GLTF:
  42845. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42846. break;
  42847. case BABYLON.Light.FALLOFF_PHYSICAL:
  42848. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42849. break;
  42850. case BABYLON.Light.FALLOFF_STANDARD:
  42851. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42852. break;
  42853. }
  42854. // Specular
  42855. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42856. specularEnabled = true;
  42857. }
  42858. // Shadows
  42859. defines["SHADOW" + lightIndex] = false;
  42860. defines["SHADOWPCF" + lightIndex] = false;
  42861. defines["SHADOWPCSS" + lightIndex] = false;
  42862. defines["SHADOWPOISSON" + lightIndex] = false;
  42863. defines["SHADOWESM" + lightIndex] = false;
  42864. defines["SHADOWCUBE" + lightIndex] = false;
  42865. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42866. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42867. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42868. var shadowGenerator = light.getShadowGenerator();
  42869. if (shadowGenerator) {
  42870. var shadowMap = shadowGenerator.getShadowMap();
  42871. if (shadowMap) {
  42872. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42873. shadowEnabled = true;
  42874. shadowGenerator.prepareDefines(defines, lightIndex);
  42875. }
  42876. }
  42877. }
  42878. }
  42879. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42880. lightmapMode = true;
  42881. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42882. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42883. }
  42884. else {
  42885. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42886. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42887. }
  42888. lightIndex++;
  42889. if (lightIndex === maxSimultaneousLights) {
  42890. break;
  42891. }
  42892. }
  42893. }
  42894. defines["SPECULARTERM"] = specularEnabled;
  42895. defines["SHADOWS"] = shadowEnabled;
  42896. // Resetting all other lights if any
  42897. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42898. if (defines["LIGHT" + index] !== undefined) {
  42899. defines["LIGHT" + index] = false;
  42900. defines["HEMILIGHT" + lightIndex] = false;
  42901. defines["POINTLIGHT" + lightIndex] = false;
  42902. defines["DIRLIGHT" + lightIndex] = false;
  42903. defines["SPOTLIGHT" + lightIndex] = false;
  42904. defines["SHADOW" + lightIndex] = false;
  42905. }
  42906. }
  42907. var caps = scene.getEngine().getCaps();
  42908. if (defines["SHADOWFLOAT"] === undefined) {
  42909. needRebuild = true;
  42910. }
  42911. defines["SHADOWFLOAT"] = shadowEnabled &&
  42912. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42913. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42914. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42915. if (needRebuild) {
  42916. defines.rebuild();
  42917. }
  42918. return needNormals;
  42919. };
  42920. /**
  42921. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42922. * that won t be acctive due to defines being turned off.
  42923. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42924. * @param samplersList The samplers list
  42925. * @param defines The defines helping in the list generation
  42926. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42927. */
  42928. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42929. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42930. var uniformsList;
  42931. var uniformBuffersList = null;
  42932. if (uniformsListOrOptions.uniformsNames) {
  42933. var options = uniformsListOrOptions;
  42934. uniformsList = options.uniformsNames;
  42935. uniformBuffersList = options.uniformBuffersNames;
  42936. samplersList = options.samplers;
  42937. defines = options.defines;
  42938. maxSimultaneousLights = options.maxSimultaneousLights;
  42939. }
  42940. else {
  42941. uniformsList = uniformsListOrOptions;
  42942. if (!samplersList) {
  42943. samplersList = [];
  42944. }
  42945. }
  42946. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42947. if (!defines["LIGHT" + lightIndex]) {
  42948. break;
  42949. }
  42950. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42951. if (uniformBuffersList) {
  42952. uniformBuffersList.push("Light" + lightIndex);
  42953. }
  42954. samplersList.push("shadowSampler" + lightIndex);
  42955. samplersList.push("depthSampler" + lightIndex);
  42956. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42957. samplersList.push("projectionLightSampler" + lightIndex);
  42958. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42959. }
  42960. }
  42961. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42962. uniformsList.push("morphTargetInfluences");
  42963. }
  42964. };
  42965. /**
  42966. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42967. * @param defines The defines to update while falling back
  42968. * @param fallbacks The authorized effect fallbacks
  42969. * @param maxSimultaneousLights The maximum number of lights allowed
  42970. * @param rank the current rank of the Effect
  42971. * @returns The newly affected rank
  42972. */
  42973. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42974. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42975. if (rank === void 0) { rank = 0; }
  42976. var lightFallbackRank = 0;
  42977. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42978. if (!defines["LIGHT" + lightIndex]) {
  42979. break;
  42980. }
  42981. if (lightIndex > 0) {
  42982. lightFallbackRank = rank + lightIndex;
  42983. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42984. }
  42985. if (!defines["SHADOWS"]) {
  42986. if (defines["SHADOW" + lightIndex]) {
  42987. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42988. }
  42989. if (defines["SHADOWPCF" + lightIndex]) {
  42990. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42991. }
  42992. if (defines["SHADOWPCSS" + lightIndex]) {
  42993. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42994. }
  42995. if (defines["SHADOWPOISSON" + lightIndex]) {
  42996. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42997. }
  42998. if (defines["SHADOWESM" + lightIndex]) {
  42999. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43000. }
  43001. }
  43002. }
  43003. return lightFallbackRank++;
  43004. };
  43005. /**
  43006. * Prepares the list of attributes required for morph targets according to the effect defines.
  43007. * @param attribs The current list of supported attribs
  43008. * @param mesh The mesh to prepare the morph targets attributes for
  43009. * @param defines The current Defines of the effect
  43010. */
  43011. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43012. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43013. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43014. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43015. var manager = mesh.morphTargetManager;
  43016. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43017. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43018. for (var index = 0; index < influencers; index++) {
  43019. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43020. if (normal) {
  43021. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43022. }
  43023. if (tangent) {
  43024. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43025. }
  43026. if (attribs.length > maxAttributesCount) {
  43027. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43028. }
  43029. }
  43030. }
  43031. };
  43032. /**
  43033. * Prepares the list of attributes required for bones according to the effect defines.
  43034. * @param attribs The current list of supported attribs
  43035. * @param mesh The mesh to prepare the bones attributes for
  43036. * @param defines The current Defines of the effect
  43037. * @param fallbacks The current efffect fallback strategy
  43038. */
  43039. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43040. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43041. fallbacks.addCPUSkinningFallback(0, mesh);
  43042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43044. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43047. }
  43048. }
  43049. };
  43050. /**
  43051. * Prepares the list of attributes required for instances according to the effect defines.
  43052. * @param attribs The current list of supported attribs
  43053. * @param defines The current Defines of the effect
  43054. */
  43055. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43056. if (defines["INSTANCES"]) {
  43057. attribs.push("world0");
  43058. attribs.push("world1");
  43059. attribs.push("world2");
  43060. attribs.push("world3");
  43061. }
  43062. };
  43063. /**
  43064. * Binds the light shadow information to the effect for the given mesh.
  43065. * @param light The light containing the generator
  43066. * @param scene The scene the lights belongs to
  43067. * @param mesh The mesh we are binding the information to render
  43068. * @param lightIndex The light index in the effect used to render the mesh
  43069. * @param effect The effect we are binding the data to
  43070. */
  43071. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43072. if (light.shadowEnabled && mesh.receiveShadows) {
  43073. var shadowGenerator = light.getShadowGenerator();
  43074. if (shadowGenerator) {
  43075. shadowGenerator.bindShadowLight(lightIndex, effect);
  43076. }
  43077. }
  43078. };
  43079. /**
  43080. * Binds the light information to the effect.
  43081. * @param light The light containing the generator
  43082. * @param effect The effect we are binding the data to
  43083. * @param lightIndex The light index in the effect used to render
  43084. */
  43085. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43086. light.transferToEffect(effect, lightIndex + "");
  43087. };
  43088. /**
  43089. * Binds the lights information from the scene to the effect for the given mesh.
  43090. * @param scene The scene the lights belongs to
  43091. * @param mesh The mesh we are binding the information to render
  43092. * @param effect The effect we are binding the data to
  43093. * @param defines The generated defines for the effect
  43094. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43095. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43096. */
  43097. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43098. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43099. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43100. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43101. for (var i = 0; i < len; i++) {
  43102. var light = mesh._lightSources[i];
  43103. var iAsString = i.toString();
  43104. var scaledIntensity = light.getScaledIntensity();
  43105. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43106. MaterialHelper.BindLightProperties(light, effect, i);
  43107. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43108. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43109. if (defines["SPECULARTERM"]) {
  43110. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43111. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43112. }
  43113. // Shadows
  43114. if (scene.shadowsEnabled) {
  43115. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43116. }
  43117. light._uniformBuffer.update();
  43118. }
  43119. };
  43120. /**
  43121. * Binds the fog information from the scene to the effect for the given mesh.
  43122. * @param scene The scene the lights belongs to
  43123. * @param mesh The mesh we are binding the information to render
  43124. * @param effect The effect we are binding the data to
  43125. * @param linearSpace Defines if the fog effect is applied in linear space
  43126. */
  43127. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43128. if (linearSpace === void 0) { linearSpace = false; }
  43129. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43130. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43131. // Convert fog color to linear space if used in a linear space computed shader.
  43132. if (linearSpace) {
  43133. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43134. effect.setColor3("vFogColor", this._tempFogColor);
  43135. }
  43136. else {
  43137. effect.setColor3("vFogColor", scene.fogColor);
  43138. }
  43139. }
  43140. };
  43141. /**
  43142. * Binds the bones information from the mesh to the effect.
  43143. * @param mesh The mesh we are binding the information to render
  43144. * @param effect The effect we are binding the data to
  43145. */
  43146. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43147. if (!effect || !mesh) {
  43148. return;
  43149. }
  43150. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43151. mesh.computeBonesUsingShaders = false;
  43152. }
  43153. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43154. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43155. if (matrices) {
  43156. effect.setMatrices("mBones", matrices);
  43157. }
  43158. }
  43159. };
  43160. /**
  43161. * Binds the morph targets information from the mesh to the effect.
  43162. * @param abstractMesh The mesh we are binding the information to render
  43163. * @param effect The effect we are binding the data to
  43164. */
  43165. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43166. var manager = abstractMesh.morphTargetManager;
  43167. if (!abstractMesh || !manager) {
  43168. return;
  43169. }
  43170. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43171. };
  43172. /**
  43173. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43174. * @param defines The generated defines used in the effect
  43175. * @param effect The effect we are binding the data to
  43176. * @param scene The scene we are willing to render with logarithmic scale for
  43177. */
  43178. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43179. if (defines["LOGARITHMICDEPTH"]) {
  43180. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43181. }
  43182. };
  43183. /**
  43184. * Binds the clip plane information from the scene to the effect.
  43185. * @param scene The scene the clip plane information are extracted from
  43186. * @param effect The effect we are binding the data to
  43187. */
  43188. MaterialHelper.BindClipPlane = function (effect, scene) {
  43189. if (scene.clipPlane) {
  43190. var clipPlane = scene.clipPlane;
  43191. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43192. }
  43193. if (scene.clipPlane2) {
  43194. var clipPlane = scene.clipPlane2;
  43195. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43196. }
  43197. if (scene.clipPlane3) {
  43198. var clipPlane = scene.clipPlane3;
  43199. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43200. }
  43201. if (scene.clipPlane4) {
  43202. var clipPlane = scene.clipPlane4;
  43203. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43204. }
  43205. };
  43206. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43207. return MaterialHelper;
  43208. }());
  43209. BABYLON.MaterialHelper = MaterialHelper;
  43210. })(BABYLON || (BABYLON = {}));
  43211. //# sourceMappingURL=babylon.materialHelper.js.map
  43212. var BABYLON;
  43213. (function (BABYLON) {
  43214. /**
  43215. * Base class of materials working in push mode in babylon JS
  43216. * @hidden
  43217. */
  43218. var PushMaterial = /** @class */ (function (_super) {
  43219. __extends(PushMaterial, _super);
  43220. function PushMaterial(name, scene) {
  43221. var _this = _super.call(this, name, scene) || this;
  43222. _this._normalMatrix = new BABYLON.Matrix();
  43223. /**
  43224. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43225. * This means that the material can keep using a previous shader while a new one is being compiled.
  43226. * This is mostly used when shader parallel compilation is supported (true by default)
  43227. */
  43228. _this.allowShaderHotSwapping = true;
  43229. _this._storeEffectOnSubMeshes = true;
  43230. return _this;
  43231. }
  43232. PushMaterial.prototype.getEffect = function () {
  43233. return this._activeEffect;
  43234. };
  43235. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43236. if (!mesh) {
  43237. return false;
  43238. }
  43239. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43240. return true;
  43241. }
  43242. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43243. };
  43244. /**
  43245. * Binds the given world matrix to the active effect
  43246. *
  43247. * @param world the matrix to bind
  43248. */
  43249. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43250. this._activeEffect.setMatrix("world", world);
  43251. };
  43252. /**
  43253. * Binds the given normal matrix to the active effect
  43254. *
  43255. * @param normalMatrix the matrix to bind
  43256. */
  43257. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43258. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43259. };
  43260. PushMaterial.prototype.bind = function (world, mesh) {
  43261. if (!mesh) {
  43262. return;
  43263. }
  43264. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43265. };
  43266. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43267. if (effect === void 0) { effect = null; }
  43268. _super.prototype._afterBind.call(this, mesh);
  43269. this.getScene()._cachedEffect = effect;
  43270. };
  43271. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43272. if (visibility === void 0) { visibility = 1; }
  43273. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43274. };
  43275. return PushMaterial;
  43276. }(BABYLON.Material));
  43277. BABYLON.PushMaterial = PushMaterial;
  43278. })(BABYLON || (BABYLON = {}));
  43279. //# sourceMappingURL=babylon.pushMaterial.js.map
  43280. var BABYLON;
  43281. (function (BABYLON) {
  43282. /** @hidden */
  43283. var StandardMaterialDefines = /** @class */ (function (_super) {
  43284. __extends(StandardMaterialDefines, _super);
  43285. function StandardMaterialDefines() {
  43286. var _this = _super.call(this) || this;
  43287. _this.MAINUV1 = false;
  43288. _this.MAINUV2 = false;
  43289. _this.DIFFUSE = false;
  43290. _this.DIFFUSEDIRECTUV = 0;
  43291. _this.AMBIENT = false;
  43292. _this.AMBIENTDIRECTUV = 0;
  43293. _this.OPACITY = false;
  43294. _this.OPACITYDIRECTUV = 0;
  43295. _this.OPACITYRGB = false;
  43296. _this.REFLECTION = false;
  43297. _this.EMISSIVE = false;
  43298. _this.EMISSIVEDIRECTUV = 0;
  43299. _this.SPECULAR = false;
  43300. _this.SPECULARDIRECTUV = 0;
  43301. _this.BUMP = false;
  43302. _this.BUMPDIRECTUV = 0;
  43303. _this.PARALLAX = false;
  43304. _this.PARALLAXOCCLUSION = false;
  43305. _this.SPECULAROVERALPHA = false;
  43306. _this.CLIPPLANE = false;
  43307. _this.CLIPPLANE2 = false;
  43308. _this.CLIPPLANE3 = false;
  43309. _this.CLIPPLANE4 = false;
  43310. _this.ALPHATEST = false;
  43311. _this.DEPTHPREPASS = false;
  43312. _this.ALPHAFROMDIFFUSE = false;
  43313. _this.POINTSIZE = false;
  43314. _this.FOG = false;
  43315. _this.SPECULARTERM = false;
  43316. _this.DIFFUSEFRESNEL = false;
  43317. _this.OPACITYFRESNEL = false;
  43318. _this.REFLECTIONFRESNEL = false;
  43319. _this.REFRACTIONFRESNEL = false;
  43320. _this.EMISSIVEFRESNEL = false;
  43321. _this.FRESNEL = false;
  43322. _this.NORMAL = false;
  43323. _this.UV1 = false;
  43324. _this.UV2 = false;
  43325. _this.VERTEXCOLOR = false;
  43326. _this.VERTEXALPHA = false;
  43327. _this.NUM_BONE_INFLUENCERS = 0;
  43328. _this.BonesPerMesh = 0;
  43329. _this.INSTANCES = false;
  43330. _this.GLOSSINESS = false;
  43331. _this.ROUGHNESS = false;
  43332. _this.EMISSIVEASILLUMINATION = false;
  43333. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43334. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43335. _this.LIGHTMAP = false;
  43336. _this.LIGHTMAPDIRECTUV = 0;
  43337. _this.OBJECTSPACE_NORMALMAP = false;
  43338. _this.USELIGHTMAPASSHADOWMAP = false;
  43339. _this.REFLECTIONMAP_3D = false;
  43340. _this.REFLECTIONMAP_SPHERICAL = false;
  43341. _this.REFLECTIONMAP_PLANAR = false;
  43342. _this.REFLECTIONMAP_CUBIC = false;
  43343. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43344. _this.REFLECTIONMAP_PROJECTION = false;
  43345. _this.REFLECTIONMAP_SKYBOX = false;
  43346. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43347. _this.REFLECTIONMAP_EXPLICIT = false;
  43348. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43349. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43350. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43351. _this.INVERTCUBICMAP = false;
  43352. _this.LOGARITHMICDEPTH = false;
  43353. _this.REFRACTION = false;
  43354. _this.REFRACTIONMAP_3D = false;
  43355. _this.REFLECTIONOVERALPHA = false;
  43356. _this.TWOSIDEDLIGHTING = false;
  43357. _this.SHADOWFLOAT = false;
  43358. _this.MORPHTARGETS = false;
  43359. _this.MORPHTARGETS_NORMAL = false;
  43360. _this.MORPHTARGETS_TANGENT = false;
  43361. _this.NUM_MORPH_INFLUENCERS = 0;
  43362. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43363. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43364. _this.IMAGEPROCESSING = false;
  43365. _this.VIGNETTE = false;
  43366. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43367. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43368. _this.TONEMAPPING = false;
  43369. _this.TONEMAPPING_ACES = false;
  43370. _this.CONTRAST = false;
  43371. _this.COLORCURVES = false;
  43372. _this.COLORGRADING = false;
  43373. _this.COLORGRADING3D = false;
  43374. _this.SAMPLER3DGREENDEPTH = false;
  43375. _this.SAMPLER3DBGRMAP = false;
  43376. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43377. /**
  43378. * If the reflection texture on this material is in linear color space
  43379. * @hidden
  43380. */
  43381. _this.IS_REFLECTION_LINEAR = false;
  43382. /**
  43383. * If the refraction texture on this material is in linear color space
  43384. * @hidden
  43385. */
  43386. _this.IS_REFRACTION_LINEAR = false;
  43387. _this.EXPOSURE = false;
  43388. _this.rebuild();
  43389. return _this;
  43390. }
  43391. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43392. var modes = [
  43393. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43394. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43395. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43396. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43397. ];
  43398. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43399. var mode = modes_1[_i];
  43400. this[mode] = (mode === modeToEnable);
  43401. }
  43402. };
  43403. return StandardMaterialDefines;
  43404. }(BABYLON.MaterialDefines));
  43405. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43406. /**
  43407. * This is the default material used in Babylon. It is the best trade off between quality
  43408. * and performances.
  43409. * @see http://doc.babylonjs.com/babylon101/materials
  43410. */
  43411. var StandardMaterial = /** @class */ (function (_super) {
  43412. __extends(StandardMaterial, _super);
  43413. /**
  43414. * Instantiates a new standard material.
  43415. * This is the default material used in Babylon. It is the best trade off between quality
  43416. * and performances.
  43417. * @see http://doc.babylonjs.com/babylon101/materials
  43418. * @param name Define the name of the material in the scene
  43419. * @param scene Define the scene the material belong to
  43420. */
  43421. function StandardMaterial(name, scene) {
  43422. var _this = _super.call(this, name, scene) || this;
  43423. /**
  43424. * The color of the material lit by the environmental background lighting.
  43425. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43426. */
  43427. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43428. /**
  43429. * The basic color of the material as viewed under a light.
  43430. */
  43431. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43432. /**
  43433. * Define how the color and intensity of the highlight given by the light in the material.
  43434. */
  43435. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43436. /**
  43437. * Define the color of the material as if self lit.
  43438. * This will be mixed in the final result even in the absence of light.
  43439. */
  43440. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43441. /**
  43442. * Defines how sharp are the highlights in the material.
  43443. * The bigger the value the sharper giving a more glossy feeling to the result.
  43444. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43445. */
  43446. _this.specularPower = 64;
  43447. _this._useAlphaFromDiffuseTexture = false;
  43448. _this._useEmissiveAsIllumination = false;
  43449. _this._linkEmissiveWithDiffuse = false;
  43450. _this._useSpecularOverAlpha = false;
  43451. _this._useReflectionOverAlpha = false;
  43452. _this._disableLighting = false;
  43453. _this._useObjectSpaceNormalMap = false;
  43454. _this._useParallax = false;
  43455. _this._useParallaxOcclusion = false;
  43456. /**
  43457. * 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.
  43458. */
  43459. _this.parallaxScaleBias = 0.05;
  43460. _this._roughness = 0;
  43461. /**
  43462. * In case of refraction, define the value of the indice of refraction.
  43463. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43464. */
  43465. _this.indexOfRefraction = 0.98;
  43466. /**
  43467. * Invert the refraction texture alongside the y axis.
  43468. * It can be usefull with procedural textures or probe for instance.
  43469. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43470. */
  43471. _this.invertRefractionY = true;
  43472. /**
  43473. * Defines the alpha limits in alpha test mode.
  43474. */
  43475. _this.alphaCutOff = 0.4;
  43476. _this._useLightmapAsShadowmap = false;
  43477. _this._useReflectionFresnelFromSpecular = false;
  43478. _this._useGlossinessFromSpecularMapAlpha = false;
  43479. _this._maxSimultaneousLights = 4;
  43480. _this._invertNormalMapX = false;
  43481. _this._invertNormalMapY = false;
  43482. _this._twoSidedLighting = false;
  43483. _this._renderTargets = new BABYLON.SmartArray(16);
  43484. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43485. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43486. // Setup the default processing configuration to the scene.
  43487. _this._attachImageProcessingConfiguration(null);
  43488. _this.getRenderTargetTextures = function () {
  43489. _this._renderTargets.reset();
  43490. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43491. _this._renderTargets.push(_this._reflectionTexture);
  43492. }
  43493. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43494. _this._renderTargets.push(_this._refractionTexture);
  43495. }
  43496. return _this._renderTargets;
  43497. };
  43498. return _this;
  43499. }
  43500. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43501. /**
  43502. * Gets the image processing configuration used either in this material.
  43503. */
  43504. get: function () {
  43505. return this._imageProcessingConfiguration;
  43506. },
  43507. /**
  43508. * Sets the Default image processing configuration used either in the this material.
  43509. *
  43510. * If sets to null, the scene one is in use.
  43511. */
  43512. set: function (value) {
  43513. this._attachImageProcessingConfiguration(value);
  43514. // Ensure the effect will be rebuilt.
  43515. this._markAllSubMeshesAsTexturesDirty();
  43516. },
  43517. enumerable: true,
  43518. configurable: true
  43519. });
  43520. /**
  43521. * Attaches a new image processing configuration to the Standard Material.
  43522. * @param configuration
  43523. */
  43524. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43525. var _this = this;
  43526. if (configuration === this._imageProcessingConfiguration) {
  43527. return;
  43528. }
  43529. // Detaches observer.
  43530. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43531. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43532. }
  43533. // Pick the scene configuration if needed.
  43534. if (!configuration) {
  43535. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43536. }
  43537. else {
  43538. this._imageProcessingConfiguration = configuration;
  43539. }
  43540. // Attaches observer.
  43541. if (this._imageProcessingConfiguration) {
  43542. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43543. _this._markAllSubMeshesAsImageProcessingDirty();
  43544. });
  43545. }
  43546. };
  43547. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43548. /**
  43549. * Gets wether the color curves effect is enabled.
  43550. */
  43551. get: function () {
  43552. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43553. },
  43554. /**
  43555. * Sets wether the color curves effect is enabled.
  43556. */
  43557. set: function (value) {
  43558. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43559. },
  43560. enumerable: true,
  43561. configurable: true
  43562. });
  43563. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43564. /**
  43565. * Gets wether the color grading effect is enabled.
  43566. */
  43567. get: function () {
  43568. return this.imageProcessingConfiguration.colorGradingEnabled;
  43569. },
  43570. /**
  43571. * Gets wether the color grading effect is enabled.
  43572. */
  43573. set: function (value) {
  43574. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43575. },
  43576. enumerable: true,
  43577. configurable: true
  43578. });
  43579. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43580. /**
  43581. * Gets wether tonemapping is enabled or not.
  43582. */
  43583. get: function () {
  43584. return this._imageProcessingConfiguration.toneMappingEnabled;
  43585. },
  43586. /**
  43587. * Sets wether tonemapping is enabled or not
  43588. */
  43589. set: function (value) {
  43590. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43591. },
  43592. enumerable: true,
  43593. configurable: true
  43594. });
  43595. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43596. /**
  43597. * The camera exposure used on this material.
  43598. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43599. * This corresponds to a photographic exposure.
  43600. */
  43601. get: function () {
  43602. return this._imageProcessingConfiguration.exposure;
  43603. },
  43604. /**
  43605. * The camera exposure used on this material.
  43606. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43607. * This corresponds to a photographic exposure.
  43608. */
  43609. set: function (value) {
  43610. this._imageProcessingConfiguration.exposure = value;
  43611. },
  43612. enumerable: true,
  43613. configurable: true
  43614. });
  43615. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43616. /**
  43617. * Gets The camera contrast used on this material.
  43618. */
  43619. get: function () {
  43620. return this._imageProcessingConfiguration.contrast;
  43621. },
  43622. /**
  43623. * Sets The camera contrast used on this material.
  43624. */
  43625. set: function (value) {
  43626. this._imageProcessingConfiguration.contrast = value;
  43627. },
  43628. enumerable: true,
  43629. configurable: true
  43630. });
  43631. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43632. /**
  43633. * Gets the Color Grading 2D Lookup Texture.
  43634. */
  43635. get: function () {
  43636. return this._imageProcessingConfiguration.colorGradingTexture;
  43637. },
  43638. /**
  43639. * Sets the Color Grading 2D Lookup Texture.
  43640. */
  43641. set: function (value) {
  43642. this._imageProcessingConfiguration.colorGradingTexture = value;
  43643. },
  43644. enumerable: true,
  43645. configurable: true
  43646. });
  43647. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43648. /**
  43649. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43650. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43651. * 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;
  43652. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43653. */
  43654. get: function () {
  43655. return this._imageProcessingConfiguration.colorCurves;
  43656. },
  43657. /**
  43658. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43659. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43660. * 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;
  43661. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43662. */
  43663. set: function (value) {
  43664. this._imageProcessingConfiguration.colorCurves = value;
  43665. },
  43666. enumerable: true,
  43667. configurable: true
  43668. });
  43669. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43670. /**
  43671. * Gets a boolean indicating that current material needs to register RTT
  43672. */
  43673. get: function () {
  43674. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43675. return true;
  43676. }
  43677. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43678. return true;
  43679. }
  43680. return false;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. /**
  43686. * Gets the current class name of the material e.g. "StandardMaterial"
  43687. * Mainly use in serialization.
  43688. * @returns the class name
  43689. */
  43690. StandardMaterial.prototype.getClassName = function () {
  43691. return "StandardMaterial";
  43692. };
  43693. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43694. /**
  43695. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43696. * You can try switching to logarithmic depth.
  43697. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43698. */
  43699. get: function () {
  43700. return this._useLogarithmicDepth;
  43701. },
  43702. set: function (value) {
  43703. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43704. this._markAllSubMeshesAsMiscDirty();
  43705. },
  43706. enumerable: true,
  43707. configurable: true
  43708. });
  43709. /**
  43710. * Specifies if the material will require alpha blending
  43711. * @returns a boolean specifying if alpha blending is needed
  43712. */
  43713. StandardMaterial.prototype.needAlphaBlending = function () {
  43714. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43715. };
  43716. /**
  43717. * Specifies if this material should be rendered in alpha test mode
  43718. * @returns a boolean specifying if an alpha test is needed.
  43719. */
  43720. StandardMaterial.prototype.needAlphaTesting = function () {
  43721. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43722. };
  43723. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43724. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43725. };
  43726. /**
  43727. * Get the texture used for alpha test purpose.
  43728. * @returns the diffuse texture in case of the standard material.
  43729. */
  43730. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43731. return this._diffuseTexture;
  43732. };
  43733. /**
  43734. * Get if the submesh is ready to be used and all its information available.
  43735. * Child classes can use it to update shaders
  43736. * @param mesh defines the mesh to check
  43737. * @param subMesh defines which submesh to check
  43738. * @param useInstances specifies that instances should be used
  43739. * @returns a boolean indicating that the submesh is ready or not
  43740. */
  43741. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43742. if (useInstances === void 0) { useInstances = false; }
  43743. if (subMesh.effect && this.isFrozen) {
  43744. if (this._wasPreviouslyReady) {
  43745. return true;
  43746. }
  43747. }
  43748. if (!subMesh._materialDefines) {
  43749. subMesh._materialDefines = new StandardMaterialDefines();
  43750. }
  43751. var scene = this.getScene();
  43752. var defines = subMesh._materialDefines;
  43753. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43754. if (defines._renderId === scene.getRenderId()) {
  43755. return true;
  43756. }
  43757. }
  43758. var engine = scene.getEngine();
  43759. // Lights
  43760. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43761. // Textures
  43762. if (defines._areTexturesDirty) {
  43763. defines._needUVs = false;
  43764. defines.MAINUV1 = false;
  43765. defines.MAINUV2 = false;
  43766. if (scene.texturesEnabled) {
  43767. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43768. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43769. return false;
  43770. }
  43771. else {
  43772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43773. }
  43774. }
  43775. else {
  43776. defines.DIFFUSE = false;
  43777. }
  43778. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43779. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43780. return false;
  43781. }
  43782. else {
  43783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43784. }
  43785. }
  43786. else {
  43787. defines.AMBIENT = false;
  43788. }
  43789. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43790. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43791. return false;
  43792. }
  43793. else {
  43794. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43795. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43796. }
  43797. }
  43798. else {
  43799. defines.OPACITY = false;
  43800. }
  43801. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43802. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43803. return false;
  43804. }
  43805. else {
  43806. defines._needNormals = true;
  43807. defines.REFLECTION = true;
  43808. defines.ROUGHNESS = (this._roughness > 0);
  43809. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43810. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43811. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43812. switch (this._reflectionTexture.coordinatesMode) {
  43813. case BABYLON.Texture.EXPLICIT_MODE:
  43814. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43815. break;
  43816. case BABYLON.Texture.PLANAR_MODE:
  43817. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43818. break;
  43819. case BABYLON.Texture.PROJECTION_MODE:
  43820. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43821. break;
  43822. case BABYLON.Texture.SKYBOX_MODE:
  43823. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43824. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43825. break;
  43826. case BABYLON.Texture.SPHERICAL_MODE:
  43827. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43828. break;
  43829. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43830. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43831. break;
  43832. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43833. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43834. break;
  43835. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43836. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43837. break;
  43838. case BABYLON.Texture.CUBIC_MODE:
  43839. case BABYLON.Texture.INVCUBIC_MODE:
  43840. default:
  43841. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43842. break;
  43843. }
  43844. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43845. }
  43846. }
  43847. else {
  43848. defines.REFLECTION = false;
  43849. }
  43850. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43851. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43852. return false;
  43853. }
  43854. else {
  43855. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43856. }
  43857. }
  43858. else {
  43859. defines.EMISSIVE = false;
  43860. }
  43861. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43862. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43863. return false;
  43864. }
  43865. else {
  43866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43867. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43868. }
  43869. }
  43870. else {
  43871. defines.LIGHTMAP = false;
  43872. }
  43873. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43874. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43875. return false;
  43876. }
  43877. else {
  43878. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43879. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43880. }
  43881. }
  43882. else {
  43883. defines.SPECULAR = false;
  43884. }
  43885. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43886. // Bump texure can not be not blocking.
  43887. if (!this._bumpTexture.isReady()) {
  43888. return false;
  43889. }
  43890. else {
  43891. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43892. defines.PARALLAX = this._useParallax;
  43893. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43894. }
  43895. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43896. }
  43897. else {
  43898. defines.BUMP = false;
  43899. }
  43900. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43901. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43902. return false;
  43903. }
  43904. else {
  43905. defines._needUVs = true;
  43906. defines.REFRACTION = true;
  43907. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43908. }
  43909. }
  43910. else {
  43911. defines.REFRACTION = false;
  43912. }
  43913. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43914. }
  43915. else {
  43916. defines.DIFFUSE = false;
  43917. defines.AMBIENT = false;
  43918. defines.OPACITY = false;
  43919. defines.REFLECTION = false;
  43920. defines.EMISSIVE = false;
  43921. defines.LIGHTMAP = false;
  43922. defines.BUMP = false;
  43923. defines.REFRACTION = false;
  43924. }
  43925. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43926. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43927. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43928. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43929. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43930. }
  43931. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43932. if (!this._imageProcessingConfiguration.isReady()) {
  43933. return false;
  43934. }
  43935. this._imageProcessingConfiguration.prepareDefines(defines);
  43936. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43937. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43938. }
  43939. if (defines._areFresnelDirty) {
  43940. if (StandardMaterial.FresnelEnabled) {
  43941. // Fresnel
  43942. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43943. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43944. this._reflectionFresnelParameters) {
  43945. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43946. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43947. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43948. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43949. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43950. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43951. defines._needNormals = true;
  43952. defines.FRESNEL = true;
  43953. }
  43954. }
  43955. else {
  43956. defines.FRESNEL = false;
  43957. }
  43958. }
  43959. // Misc.
  43960. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43961. // Attribs
  43962. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43963. // Values that need to be evaluated on every frame
  43964. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43965. // Get correct effect
  43966. if (defines.isDirty) {
  43967. defines.markAsProcessed();
  43968. // Fallbacks
  43969. var fallbacks = new BABYLON.EffectFallbacks();
  43970. if (defines.REFLECTION) {
  43971. fallbacks.addFallback(0, "REFLECTION");
  43972. }
  43973. if (defines.SPECULAR) {
  43974. fallbacks.addFallback(0, "SPECULAR");
  43975. }
  43976. if (defines.BUMP) {
  43977. fallbacks.addFallback(0, "BUMP");
  43978. }
  43979. if (defines.PARALLAX) {
  43980. fallbacks.addFallback(1, "PARALLAX");
  43981. }
  43982. if (defines.PARALLAXOCCLUSION) {
  43983. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43984. }
  43985. if (defines.SPECULAROVERALPHA) {
  43986. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43987. }
  43988. if (defines.FOG) {
  43989. fallbacks.addFallback(1, "FOG");
  43990. }
  43991. if (defines.POINTSIZE) {
  43992. fallbacks.addFallback(0, "POINTSIZE");
  43993. }
  43994. if (defines.LOGARITHMICDEPTH) {
  43995. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43996. }
  43997. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43998. if (defines.SPECULARTERM) {
  43999. fallbacks.addFallback(0, "SPECULARTERM");
  44000. }
  44001. if (defines.DIFFUSEFRESNEL) {
  44002. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44003. }
  44004. if (defines.OPACITYFRESNEL) {
  44005. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44006. }
  44007. if (defines.REFLECTIONFRESNEL) {
  44008. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44009. }
  44010. if (defines.EMISSIVEFRESNEL) {
  44011. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44012. }
  44013. if (defines.FRESNEL) {
  44014. fallbacks.addFallback(4, "FRESNEL");
  44015. }
  44016. //Attributes
  44017. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44018. if (defines.NORMAL) {
  44019. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44020. }
  44021. if (defines.UV1) {
  44022. attribs.push(BABYLON.VertexBuffer.UVKind);
  44023. }
  44024. if (defines.UV2) {
  44025. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44026. }
  44027. if (defines.VERTEXCOLOR) {
  44028. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44029. }
  44030. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44031. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44032. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44033. var shaderName = "default";
  44034. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44035. "vFogInfos", "vFogColor", "pointSize",
  44036. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44037. "mBones",
  44038. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44039. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44040. "vReflectionPosition", "vReflectionSize",
  44041. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  44042. ];
  44043. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44044. var uniformBuffers = ["Material", "Scene"];
  44045. if (BABYLON.ImageProcessingConfiguration) {
  44046. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44047. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44048. }
  44049. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44050. uniformsNames: uniforms,
  44051. uniformBuffersNames: uniformBuffers,
  44052. samplers: samplers,
  44053. defines: defines,
  44054. maxSimultaneousLights: this._maxSimultaneousLights
  44055. });
  44056. if (this.customShaderNameResolve) {
  44057. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44058. }
  44059. var join = defines.toString();
  44060. var previousEffect = subMesh.effect;
  44061. var effect = scene.getEngine().createEffect(shaderName, {
  44062. attributes: attribs,
  44063. uniformsNames: uniforms,
  44064. uniformBuffersNames: uniformBuffers,
  44065. samplers: samplers,
  44066. defines: join,
  44067. fallbacks: fallbacks,
  44068. onCompiled: this.onCompiled,
  44069. onError: this.onError,
  44070. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44071. }, engine);
  44072. if (effect) {
  44073. // Use previous effect while new one is compiling
  44074. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44075. effect = previousEffect;
  44076. defines.markAsUnprocessed();
  44077. }
  44078. else {
  44079. scene.resetCachedMaterial();
  44080. subMesh.setEffect(effect, defines);
  44081. this.buildUniformLayout();
  44082. }
  44083. }
  44084. }
  44085. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44086. return false;
  44087. }
  44088. defines._renderId = scene.getRenderId();
  44089. this._wasPreviouslyReady = true;
  44090. return true;
  44091. };
  44092. /**
  44093. * Builds the material UBO layouts.
  44094. * Used internally during the effect preparation.
  44095. */
  44096. StandardMaterial.prototype.buildUniformLayout = function () {
  44097. // Order is important !
  44098. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44099. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44100. this._uniformBuffer.addUniform("opacityParts", 4);
  44101. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44102. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44103. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44104. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44105. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44106. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44107. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44108. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44109. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44110. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44111. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44112. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44113. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44114. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44115. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44116. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44117. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44118. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44119. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44120. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44121. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44122. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44123. this._uniformBuffer.addUniform("specularMatrix", 16);
  44124. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44125. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44126. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44127. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44128. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44129. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44130. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44131. this._uniformBuffer.addUniform("pointSize", 1);
  44132. this._uniformBuffer.create();
  44133. };
  44134. /**
  44135. * Unbinds the material from the mesh
  44136. */
  44137. StandardMaterial.prototype.unbind = function () {
  44138. if (this._activeEffect) {
  44139. var needFlag = false;
  44140. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44141. this._activeEffect.setTexture("reflection2DSampler", null);
  44142. needFlag = true;
  44143. }
  44144. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44145. this._activeEffect.setTexture("refraction2DSampler", null);
  44146. needFlag = true;
  44147. }
  44148. if (needFlag) {
  44149. this._markAllSubMeshesAsTexturesDirty();
  44150. }
  44151. }
  44152. _super.prototype.unbind.call(this);
  44153. };
  44154. /**
  44155. * Binds the submesh to this material by preparing the effect and shader to draw
  44156. * @param world defines the world transformation matrix
  44157. * @param mesh defines the mesh containing the submesh
  44158. * @param subMesh defines the submesh to bind the material to
  44159. */
  44160. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44161. var scene = this.getScene();
  44162. var defines = subMesh._materialDefines;
  44163. if (!defines) {
  44164. return;
  44165. }
  44166. var effect = subMesh.effect;
  44167. if (!effect) {
  44168. return;
  44169. }
  44170. this._activeEffect = effect;
  44171. // Matrices
  44172. this.bindOnlyWorldMatrix(world);
  44173. // Normal Matrix
  44174. if (defines.OBJECTSPACE_NORMALMAP) {
  44175. world.toNormalMatrix(this._normalMatrix);
  44176. this.bindOnlyNormalMatrix(this._normalMatrix);
  44177. }
  44178. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44179. // Bones
  44180. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44181. if (mustRebind) {
  44182. this._uniformBuffer.bindToEffect(effect, "Material");
  44183. this.bindViewProjection(effect);
  44184. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44185. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44186. // Fresnel
  44187. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44188. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44189. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44190. }
  44191. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44192. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44193. }
  44194. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44195. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44196. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44197. }
  44198. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44199. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44200. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44201. }
  44202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44203. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44204. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44205. }
  44206. }
  44207. // Textures
  44208. if (scene.texturesEnabled) {
  44209. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44210. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44211. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44212. if (this._diffuseTexture.hasAlpha) {
  44213. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44214. }
  44215. }
  44216. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44217. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44218. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44219. }
  44220. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44221. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44222. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44223. }
  44224. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44225. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44226. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44227. if (this._reflectionTexture.boundingBoxSize) {
  44228. var cubeTexture = this._reflectionTexture;
  44229. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44230. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44231. }
  44232. }
  44233. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44234. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44235. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44236. }
  44237. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44238. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44239. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44240. }
  44241. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44242. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44243. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44244. }
  44245. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44246. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44247. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44248. if (scene._mirroredCameraPosition) {
  44249. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44250. }
  44251. else {
  44252. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44253. }
  44254. }
  44255. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44256. var depth = 1.0;
  44257. if (!this._refractionTexture.isCube) {
  44258. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44259. if (this._refractionTexture.depth) {
  44260. depth = this._refractionTexture.depth;
  44261. }
  44262. }
  44263. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44264. }
  44265. }
  44266. // Point size
  44267. if (this.pointsCloud) {
  44268. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44269. }
  44270. if (defines.SPECULARTERM) {
  44271. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44272. }
  44273. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44274. // Diffuse
  44275. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44276. }
  44277. // Textures
  44278. if (scene.texturesEnabled) {
  44279. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44280. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44281. }
  44282. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44283. effect.setTexture("ambientSampler", this._ambientTexture);
  44284. }
  44285. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44286. effect.setTexture("opacitySampler", this._opacityTexture);
  44287. }
  44288. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44289. if (this._reflectionTexture.isCube) {
  44290. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44291. }
  44292. else {
  44293. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44294. }
  44295. }
  44296. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44297. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44298. }
  44299. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44300. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44301. }
  44302. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44303. effect.setTexture("specularSampler", this._specularTexture);
  44304. }
  44305. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44306. effect.setTexture("bumpSampler", this._bumpTexture);
  44307. }
  44308. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44309. var depth = 1.0;
  44310. if (this._refractionTexture.isCube) {
  44311. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44312. }
  44313. else {
  44314. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44315. }
  44316. }
  44317. }
  44318. // Clip plane
  44319. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44320. // Colors
  44321. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44322. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44323. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44324. }
  44325. if (mustRebind || !this.isFrozen) {
  44326. // Lights
  44327. if (scene.lightsEnabled && !this._disableLighting) {
  44328. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44329. }
  44330. // View
  44331. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44332. this.bindView(effect);
  44333. }
  44334. // Fog
  44335. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44336. // Morph targets
  44337. if (defines.NUM_MORPH_INFLUENCERS) {
  44338. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44339. }
  44340. // Log. depth
  44341. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44342. // image processing
  44343. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44344. this._imageProcessingConfiguration.bind(this._activeEffect);
  44345. }
  44346. }
  44347. this._uniformBuffer.update();
  44348. this._afterBind(mesh, this._activeEffect);
  44349. };
  44350. /**
  44351. * Get the list of animatables in the material.
  44352. * @returns the list of animatables object used in the material
  44353. */
  44354. StandardMaterial.prototype.getAnimatables = function () {
  44355. var results = [];
  44356. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44357. results.push(this._diffuseTexture);
  44358. }
  44359. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44360. results.push(this._ambientTexture);
  44361. }
  44362. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44363. results.push(this._opacityTexture);
  44364. }
  44365. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44366. results.push(this._reflectionTexture);
  44367. }
  44368. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44369. results.push(this._emissiveTexture);
  44370. }
  44371. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44372. results.push(this._specularTexture);
  44373. }
  44374. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44375. results.push(this._bumpTexture);
  44376. }
  44377. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44378. results.push(this._lightmapTexture);
  44379. }
  44380. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44381. results.push(this._refractionTexture);
  44382. }
  44383. return results;
  44384. };
  44385. /**
  44386. * Gets the active textures from the material
  44387. * @returns an array of textures
  44388. */
  44389. StandardMaterial.prototype.getActiveTextures = function () {
  44390. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44391. if (this._diffuseTexture) {
  44392. activeTextures.push(this._diffuseTexture);
  44393. }
  44394. if (this._ambientTexture) {
  44395. activeTextures.push(this._ambientTexture);
  44396. }
  44397. if (this._opacityTexture) {
  44398. activeTextures.push(this._opacityTexture);
  44399. }
  44400. if (this._reflectionTexture) {
  44401. activeTextures.push(this._reflectionTexture);
  44402. }
  44403. if (this._emissiveTexture) {
  44404. activeTextures.push(this._emissiveTexture);
  44405. }
  44406. if (this._specularTexture) {
  44407. activeTextures.push(this._specularTexture);
  44408. }
  44409. if (this._bumpTexture) {
  44410. activeTextures.push(this._bumpTexture);
  44411. }
  44412. if (this._lightmapTexture) {
  44413. activeTextures.push(this._lightmapTexture);
  44414. }
  44415. if (this._refractionTexture) {
  44416. activeTextures.push(this._refractionTexture);
  44417. }
  44418. return activeTextures;
  44419. };
  44420. /**
  44421. * Specifies if the material uses a texture
  44422. * @param texture defines the texture to check against the material
  44423. * @returns a boolean specifying if the material uses the texture
  44424. */
  44425. StandardMaterial.prototype.hasTexture = function (texture) {
  44426. if (_super.prototype.hasTexture.call(this, texture)) {
  44427. return true;
  44428. }
  44429. if (this._diffuseTexture === texture) {
  44430. return true;
  44431. }
  44432. if (this._ambientTexture === texture) {
  44433. return true;
  44434. }
  44435. if (this._opacityTexture === texture) {
  44436. return true;
  44437. }
  44438. if (this._reflectionTexture === texture) {
  44439. return true;
  44440. }
  44441. if (this._emissiveTexture === texture) {
  44442. return true;
  44443. }
  44444. if (this._specularTexture === texture) {
  44445. return true;
  44446. }
  44447. if (this._bumpTexture === texture) {
  44448. return true;
  44449. }
  44450. if (this._lightmapTexture === texture) {
  44451. return true;
  44452. }
  44453. if (this._refractionTexture === texture) {
  44454. return true;
  44455. }
  44456. return false;
  44457. };
  44458. /**
  44459. * Disposes the material
  44460. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44461. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44462. */
  44463. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44464. if (forceDisposeTextures) {
  44465. if (this._diffuseTexture) {
  44466. this._diffuseTexture.dispose();
  44467. }
  44468. if (this._ambientTexture) {
  44469. this._ambientTexture.dispose();
  44470. }
  44471. if (this._opacityTexture) {
  44472. this._opacityTexture.dispose();
  44473. }
  44474. if (this._reflectionTexture) {
  44475. this._reflectionTexture.dispose();
  44476. }
  44477. if (this._emissiveTexture) {
  44478. this._emissiveTexture.dispose();
  44479. }
  44480. if (this._specularTexture) {
  44481. this._specularTexture.dispose();
  44482. }
  44483. if (this._bumpTexture) {
  44484. this._bumpTexture.dispose();
  44485. }
  44486. if (this._lightmapTexture) {
  44487. this._lightmapTexture.dispose();
  44488. }
  44489. if (this._refractionTexture) {
  44490. this._refractionTexture.dispose();
  44491. }
  44492. }
  44493. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44494. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44495. }
  44496. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44497. };
  44498. /**
  44499. * Makes a duplicate of the material, and gives it a new name
  44500. * @param name defines the new name for the duplicated material
  44501. * @returns the cloned material
  44502. */
  44503. StandardMaterial.prototype.clone = function (name) {
  44504. var _this = this;
  44505. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44506. result.name = name;
  44507. result.id = name;
  44508. return result;
  44509. };
  44510. /**
  44511. * Serializes this material in a JSON representation
  44512. * @returns the serialized material object
  44513. */
  44514. StandardMaterial.prototype.serialize = function () {
  44515. return BABYLON.SerializationHelper.Serialize(this);
  44516. };
  44517. /**
  44518. * Creates a standard material from parsed material data
  44519. * @param source defines the JSON represnetation of the material
  44520. * @param scene defines the hosting scene
  44521. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44522. * @returns a new material
  44523. */
  44524. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44525. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44526. };
  44527. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44528. /**
  44529. * Are diffuse textures enabled in the application.
  44530. */
  44531. get: function () {
  44532. return StandardMaterial._DiffuseTextureEnabled;
  44533. },
  44534. set: function (value) {
  44535. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44536. return;
  44537. }
  44538. StandardMaterial._DiffuseTextureEnabled = value;
  44539. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44540. },
  44541. enumerable: true,
  44542. configurable: true
  44543. });
  44544. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44545. /**
  44546. * Are ambient textures enabled in the application.
  44547. */
  44548. get: function () {
  44549. return StandardMaterial._AmbientTextureEnabled;
  44550. },
  44551. set: function (value) {
  44552. if (StandardMaterial._AmbientTextureEnabled === value) {
  44553. return;
  44554. }
  44555. StandardMaterial._AmbientTextureEnabled = value;
  44556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44557. },
  44558. enumerable: true,
  44559. configurable: true
  44560. });
  44561. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44562. /**
  44563. * Are opacity textures enabled in the application.
  44564. */
  44565. get: function () {
  44566. return StandardMaterial._OpacityTextureEnabled;
  44567. },
  44568. set: function (value) {
  44569. if (StandardMaterial._OpacityTextureEnabled === value) {
  44570. return;
  44571. }
  44572. StandardMaterial._OpacityTextureEnabled = value;
  44573. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44574. },
  44575. enumerable: true,
  44576. configurable: true
  44577. });
  44578. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44579. /**
  44580. * Are reflection textures enabled in the application.
  44581. */
  44582. get: function () {
  44583. return StandardMaterial._ReflectionTextureEnabled;
  44584. },
  44585. set: function (value) {
  44586. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44587. return;
  44588. }
  44589. StandardMaterial._ReflectionTextureEnabled = value;
  44590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44591. },
  44592. enumerable: true,
  44593. configurable: true
  44594. });
  44595. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44596. /**
  44597. * Are emissive textures enabled in the application.
  44598. */
  44599. get: function () {
  44600. return StandardMaterial._EmissiveTextureEnabled;
  44601. },
  44602. set: function (value) {
  44603. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44604. return;
  44605. }
  44606. StandardMaterial._EmissiveTextureEnabled = value;
  44607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44608. },
  44609. enumerable: true,
  44610. configurable: true
  44611. });
  44612. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44613. /**
  44614. * Are specular textures enabled in the application.
  44615. */
  44616. get: function () {
  44617. return StandardMaterial._SpecularTextureEnabled;
  44618. },
  44619. set: function (value) {
  44620. if (StandardMaterial._SpecularTextureEnabled === value) {
  44621. return;
  44622. }
  44623. StandardMaterial._SpecularTextureEnabled = value;
  44624. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44625. },
  44626. enumerable: true,
  44627. configurable: true
  44628. });
  44629. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44630. /**
  44631. * Are bump textures enabled in the application.
  44632. */
  44633. get: function () {
  44634. return StandardMaterial._BumpTextureEnabled;
  44635. },
  44636. set: function (value) {
  44637. if (StandardMaterial._BumpTextureEnabled === value) {
  44638. return;
  44639. }
  44640. StandardMaterial._BumpTextureEnabled = value;
  44641. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44642. },
  44643. enumerable: true,
  44644. configurable: true
  44645. });
  44646. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44647. /**
  44648. * Are lightmap textures enabled in the application.
  44649. */
  44650. get: function () {
  44651. return StandardMaterial._LightmapTextureEnabled;
  44652. },
  44653. set: function (value) {
  44654. if (StandardMaterial._LightmapTextureEnabled === value) {
  44655. return;
  44656. }
  44657. StandardMaterial._LightmapTextureEnabled = value;
  44658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44659. },
  44660. enumerable: true,
  44661. configurable: true
  44662. });
  44663. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44664. /**
  44665. * Are refraction textures enabled in the application.
  44666. */
  44667. get: function () {
  44668. return StandardMaterial._RefractionTextureEnabled;
  44669. },
  44670. set: function (value) {
  44671. if (StandardMaterial._RefractionTextureEnabled === value) {
  44672. return;
  44673. }
  44674. StandardMaterial._RefractionTextureEnabled = value;
  44675. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44676. },
  44677. enumerable: true,
  44678. configurable: true
  44679. });
  44680. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44681. /**
  44682. * Are color grading textures enabled in the application.
  44683. */
  44684. get: function () {
  44685. return StandardMaterial._ColorGradingTextureEnabled;
  44686. },
  44687. set: function (value) {
  44688. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44689. return;
  44690. }
  44691. StandardMaterial._ColorGradingTextureEnabled = value;
  44692. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44693. },
  44694. enumerable: true,
  44695. configurable: true
  44696. });
  44697. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44698. /**
  44699. * Are fresnels enabled in the application.
  44700. */
  44701. get: function () {
  44702. return StandardMaterial._FresnelEnabled;
  44703. },
  44704. set: function (value) {
  44705. if (StandardMaterial._FresnelEnabled === value) {
  44706. return;
  44707. }
  44708. StandardMaterial._FresnelEnabled = value;
  44709. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44710. },
  44711. enumerable: true,
  44712. configurable: true
  44713. });
  44714. // Flags used to enable or disable a type of texture for all Standard Materials
  44715. StandardMaterial._DiffuseTextureEnabled = true;
  44716. StandardMaterial._AmbientTextureEnabled = true;
  44717. StandardMaterial._OpacityTextureEnabled = true;
  44718. StandardMaterial._ReflectionTextureEnabled = true;
  44719. StandardMaterial._EmissiveTextureEnabled = true;
  44720. StandardMaterial._SpecularTextureEnabled = true;
  44721. StandardMaterial._BumpTextureEnabled = true;
  44722. StandardMaterial._LightmapTextureEnabled = true;
  44723. StandardMaterial._RefractionTextureEnabled = true;
  44724. StandardMaterial._ColorGradingTextureEnabled = true;
  44725. StandardMaterial._FresnelEnabled = true;
  44726. __decorate([
  44727. BABYLON.serializeAsTexture("diffuseTexture")
  44728. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44729. __decorate([
  44730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44731. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44732. __decorate([
  44733. BABYLON.serializeAsTexture("ambientTexture")
  44734. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44735. __decorate([
  44736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44737. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44738. __decorate([
  44739. BABYLON.serializeAsTexture("opacityTexture")
  44740. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44741. __decorate([
  44742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44743. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44744. __decorate([
  44745. BABYLON.serializeAsTexture("reflectionTexture")
  44746. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44747. __decorate([
  44748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44749. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44750. __decorate([
  44751. BABYLON.serializeAsTexture("emissiveTexture")
  44752. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44753. __decorate([
  44754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44755. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44756. __decorate([
  44757. BABYLON.serializeAsTexture("specularTexture")
  44758. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44759. __decorate([
  44760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44761. ], StandardMaterial.prototype, "specularTexture", void 0);
  44762. __decorate([
  44763. BABYLON.serializeAsTexture("bumpTexture")
  44764. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44765. __decorate([
  44766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44767. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44768. __decorate([
  44769. BABYLON.serializeAsTexture("lightmapTexture")
  44770. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44771. __decorate([
  44772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44773. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44774. __decorate([
  44775. BABYLON.serializeAsTexture("refractionTexture")
  44776. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44777. __decorate([
  44778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44779. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44780. __decorate([
  44781. BABYLON.serializeAsColor3("ambient")
  44782. ], StandardMaterial.prototype, "ambientColor", void 0);
  44783. __decorate([
  44784. BABYLON.serializeAsColor3("diffuse")
  44785. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44786. __decorate([
  44787. BABYLON.serializeAsColor3("specular")
  44788. ], StandardMaterial.prototype, "specularColor", void 0);
  44789. __decorate([
  44790. BABYLON.serializeAsColor3("emissive")
  44791. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44792. __decorate([
  44793. BABYLON.serialize()
  44794. ], StandardMaterial.prototype, "specularPower", void 0);
  44795. __decorate([
  44796. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44797. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44798. __decorate([
  44799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44800. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44801. __decorate([
  44802. BABYLON.serialize("useEmissiveAsIllumination")
  44803. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44804. __decorate([
  44805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44806. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44807. __decorate([
  44808. BABYLON.serialize("linkEmissiveWithDiffuse")
  44809. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44810. __decorate([
  44811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44812. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44813. __decorate([
  44814. BABYLON.serialize("useSpecularOverAlpha")
  44815. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44816. __decorate([
  44817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44818. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44819. __decorate([
  44820. BABYLON.serialize("useReflectionOverAlpha")
  44821. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44822. __decorate([
  44823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44824. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44825. __decorate([
  44826. BABYLON.serialize("disableLighting")
  44827. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44828. __decorate([
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44830. ], StandardMaterial.prototype, "disableLighting", void 0);
  44831. __decorate([
  44832. BABYLON.serialize("useObjectSpaceNormalMap")
  44833. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44834. __decorate([
  44835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44836. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44837. __decorate([
  44838. BABYLON.serialize("useParallax")
  44839. ], StandardMaterial.prototype, "_useParallax", void 0);
  44840. __decorate([
  44841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44842. ], StandardMaterial.prototype, "useParallax", void 0);
  44843. __decorate([
  44844. BABYLON.serialize("useParallaxOcclusion")
  44845. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44846. __decorate([
  44847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44848. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44849. __decorate([
  44850. BABYLON.serialize()
  44851. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44852. __decorate([
  44853. BABYLON.serialize("roughness")
  44854. ], StandardMaterial.prototype, "_roughness", void 0);
  44855. __decorate([
  44856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44857. ], StandardMaterial.prototype, "roughness", void 0);
  44858. __decorate([
  44859. BABYLON.serialize()
  44860. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44861. __decorate([
  44862. BABYLON.serialize()
  44863. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44864. __decorate([
  44865. BABYLON.serialize()
  44866. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44867. __decorate([
  44868. BABYLON.serialize("useLightmapAsShadowmap")
  44869. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44870. __decorate([
  44871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44872. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44873. __decorate([
  44874. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44875. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44876. __decorate([
  44877. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44878. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44879. __decorate([
  44880. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44881. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44882. __decorate([
  44883. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44884. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44885. __decorate([
  44886. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44887. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44888. __decorate([
  44889. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44890. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44891. __decorate([
  44892. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44893. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44894. __decorate([
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44896. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44897. __decorate([
  44898. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44899. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44900. __decorate([
  44901. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44902. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44903. __decorate([
  44904. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44905. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44906. __decorate([
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44908. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44909. __decorate([
  44910. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44911. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44912. __decorate([
  44913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44914. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44915. __decorate([
  44916. BABYLON.serialize("maxSimultaneousLights")
  44917. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44918. __decorate([
  44919. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44920. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44921. __decorate([
  44922. BABYLON.serialize("invertNormalMapX")
  44923. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44924. __decorate([
  44925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44926. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44927. __decorate([
  44928. BABYLON.serialize("invertNormalMapY")
  44929. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44930. __decorate([
  44931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44932. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44933. __decorate([
  44934. BABYLON.serialize("twoSidedLighting")
  44935. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44936. __decorate([
  44937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44938. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44939. __decorate([
  44940. BABYLON.serialize()
  44941. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44942. return StandardMaterial;
  44943. }(BABYLON.PushMaterial));
  44944. BABYLON.StandardMaterial = StandardMaterial;
  44945. })(BABYLON || (BABYLON = {}));
  44946. //# sourceMappingURL=babylon.standardMaterial.js.map
  44947. var BABYLON;
  44948. (function (BABYLON) {
  44949. /**
  44950. * Class representing spherical polynomial coefficients to the 3rd degree
  44951. */
  44952. var SphericalPolynomial = /** @class */ (function () {
  44953. function SphericalPolynomial() {
  44954. /**
  44955. * The x coefficients of the spherical polynomial
  44956. */
  44957. this.x = BABYLON.Vector3.Zero();
  44958. /**
  44959. * The y coefficients of the spherical polynomial
  44960. */
  44961. this.y = BABYLON.Vector3.Zero();
  44962. /**
  44963. * The z coefficients of the spherical polynomial
  44964. */
  44965. this.z = BABYLON.Vector3.Zero();
  44966. /**
  44967. * The xx coefficients of the spherical polynomial
  44968. */
  44969. this.xx = BABYLON.Vector3.Zero();
  44970. /**
  44971. * The yy coefficients of the spherical polynomial
  44972. */
  44973. this.yy = BABYLON.Vector3.Zero();
  44974. /**
  44975. * The zz coefficients of the spherical polynomial
  44976. */
  44977. this.zz = BABYLON.Vector3.Zero();
  44978. /**
  44979. * The xy coefficients of the spherical polynomial
  44980. */
  44981. this.xy = BABYLON.Vector3.Zero();
  44982. /**
  44983. * The yz coefficients of the spherical polynomial
  44984. */
  44985. this.yz = BABYLON.Vector3.Zero();
  44986. /**
  44987. * The zx coefficients of the spherical polynomial
  44988. */
  44989. this.zx = BABYLON.Vector3.Zero();
  44990. }
  44991. /**
  44992. * Adds an ambient color to the spherical polynomial
  44993. * @param color the color to add
  44994. */
  44995. SphericalPolynomial.prototype.addAmbient = function (color) {
  44996. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44997. this.xx = this.xx.add(colorVector);
  44998. this.yy = this.yy.add(colorVector);
  44999. this.zz = this.zz.add(colorVector);
  45000. };
  45001. /**
  45002. * Scales the spherical polynomial by the given amount
  45003. * @param scale the amount to scale
  45004. */
  45005. SphericalPolynomial.prototype.scale = function (scale) {
  45006. this.x = this.x.scale(scale);
  45007. this.y = this.y.scale(scale);
  45008. this.z = this.z.scale(scale);
  45009. this.xx = this.xx.scale(scale);
  45010. this.yy = this.yy.scale(scale);
  45011. this.zz = this.zz.scale(scale);
  45012. this.yz = this.yz.scale(scale);
  45013. this.zx = this.zx.scale(scale);
  45014. this.xy = this.xy.scale(scale);
  45015. };
  45016. /**
  45017. * Gets the spherical polynomial from harmonics
  45018. * @param harmonics the spherical harmonics
  45019. * @returns the spherical polynomial
  45020. */
  45021. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45022. var result = new SphericalPolynomial();
  45023. result.x = harmonics.l11.scale(1.02333);
  45024. result.y = harmonics.l1_1.scale(1.02333);
  45025. result.z = harmonics.l10.scale(1.02333);
  45026. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45027. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45028. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45029. result.yz = harmonics.l2_1.scale(0.858086);
  45030. result.zx = harmonics.l21.scale(0.858086);
  45031. result.xy = harmonics.l2_2.scale(0.858086);
  45032. result.scale(1.0 / Math.PI);
  45033. return result;
  45034. };
  45035. /**
  45036. * Constructs a spherical polynomial from an array.
  45037. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45038. * @returns the spherical polynomial
  45039. */
  45040. SphericalPolynomial.FromArray = function (data) {
  45041. var sp = new SphericalPolynomial();
  45042. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45043. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45044. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45045. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45046. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45047. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45048. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45049. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45050. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45051. return sp;
  45052. };
  45053. return SphericalPolynomial;
  45054. }());
  45055. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45056. /**
  45057. * Class representing spherical harmonics coefficients to the 3rd degree
  45058. */
  45059. var SphericalHarmonics = /** @class */ (function () {
  45060. function SphericalHarmonics() {
  45061. /**
  45062. * The l0,0 coefficients of the spherical harmonics
  45063. */
  45064. this.l00 = BABYLON.Vector3.Zero();
  45065. /**
  45066. * The l1,-1 coefficients of the spherical harmonics
  45067. */
  45068. this.l1_1 = BABYLON.Vector3.Zero();
  45069. /**
  45070. * The l1,0 coefficients of the spherical harmonics
  45071. */
  45072. this.l10 = BABYLON.Vector3.Zero();
  45073. /**
  45074. * The l1,1 coefficients of the spherical harmonics
  45075. */
  45076. this.l11 = BABYLON.Vector3.Zero();
  45077. /**
  45078. * The l2,-2 coefficients of the spherical harmonics
  45079. */
  45080. this.l2_2 = BABYLON.Vector3.Zero();
  45081. /**
  45082. * The l2,-1 coefficients of the spherical harmonics
  45083. */
  45084. this.l2_1 = BABYLON.Vector3.Zero();
  45085. /**
  45086. * The l2,0 coefficients of the spherical harmonics
  45087. */
  45088. this.l20 = BABYLON.Vector3.Zero();
  45089. /**
  45090. * The l2,1 coefficients of the spherical harmonics
  45091. */
  45092. this.l21 = BABYLON.Vector3.Zero();
  45093. /**
  45094. * The l2,2 coefficients of the spherical harmonics
  45095. */
  45096. this.lL22 = BABYLON.Vector3.Zero();
  45097. }
  45098. /**
  45099. * Adds a light to the spherical harmonics
  45100. * @param direction the direction of the light
  45101. * @param color the color of the light
  45102. * @param deltaSolidAngle the delta solid angle of the light
  45103. */
  45104. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45105. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45106. var c = colorVector.scale(deltaSolidAngle);
  45107. this.l00 = this.l00.add(c.scale(0.282095));
  45108. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45109. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45110. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45111. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45112. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45113. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45114. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45115. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45116. };
  45117. /**
  45118. * Scales the spherical harmonics by the given amount
  45119. * @param scale the amount to scale
  45120. */
  45121. SphericalHarmonics.prototype.scale = function (scale) {
  45122. this.l00 = this.l00.scale(scale);
  45123. this.l1_1 = this.l1_1.scale(scale);
  45124. this.l10 = this.l10.scale(scale);
  45125. this.l11 = this.l11.scale(scale);
  45126. this.l2_2 = this.l2_2.scale(scale);
  45127. this.l2_1 = this.l2_1.scale(scale);
  45128. this.l20 = this.l20.scale(scale);
  45129. this.l21 = this.l21.scale(scale);
  45130. this.lL22 = this.lL22.scale(scale);
  45131. };
  45132. /**
  45133. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45134. *
  45135. * ```
  45136. * E_lm = A_l * L_lm
  45137. * ```
  45138. *
  45139. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45140. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45141. * the scaling factors are given in equation 9.
  45142. */
  45143. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45144. // Constant (Band 0)
  45145. this.l00 = this.l00.scale(3.141593);
  45146. // Linear (Band 1)
  45147. this.l1_1 = this.l1_1.scale(2.094395);
  45148. this.l10 = this.l10.scale(2.094395);
  45149. this.l11 = this.l11.scale(2.094395);
  45150. // Quadratic (Band 2)
  45151. this.l2_2 = this.l2_2.scale(0.785398);
  45152. this.l2_1 = this.l2_1.scale(0.785398);
  45153. this.l20 = this.l20.scale(0.785398);
  45154. this.l21 = this.l21.scale(0.785398);
  45155. this.lL22 = this.lL22.scale(0.785398);
  45156. };
  45157. /**
  45158. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45159. *
  45160. * ```
  45161. * L = (1/pi) * E * rho
  45162. * ```
  45163. *
  45164. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45165. */
  45166. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45167. this.scale(1.0 / Math.PI);
  45168. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45169. // (The pixel shader must apply albedo after texture fetches, etc).
  45170. };
  45171. /**
  45172. * Gets the spherical harmonics from polynomial
  45173. * @param polynomial the spherical polynomial
  45174. * @returns the spherical harmonics
  45175. */
  45176. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45177. var result = new SphericalHarmonics();
  45178. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45179. result.l1_1 = polynomial.y.scale(0.977204);
  45180. result.l10 = polynomial.z.scale(0.977204);
  45181. result.l11 = polynomial.x.scale(0.977204);
  45182. result.l2_2 = polynomial.xy.scale(1.16538);
  45183. result.l2_1 = polynomial.yz.scale(1.16538);
  45184. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45185. result.l21 = polynomial.zx.scale(1.16538);
  45186. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45187. result.scale(Math.PI);
  45188. return result;
  45189. };
  45190. /**
  45191. * Constructs a spherical harmonics from an array.
  45192. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45193. * @returns the spherical harmonics
  45194. */
  45195. SphericalHarmonics.FromArray = function (data) {
  45196. var sh = new SphericalHarmonics();
  45197. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45198. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45199. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45200. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45201. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45202. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45203. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45204. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45205. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45206. return sh;
  45207. };
  45208. return SphericalHarmonics;
  45209. }());
  45210. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45211. })(BABYLON || (BABYLON = {}));
  45212. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45213. var BABYLON;
  45214. (function (BABYLON) {
  45215. var FileFaceOrientation = /** @class */ (function () {
  45216. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45217. this.name = name;
  45218. this.worldAxisForNormal = worldAxisForNormal;
  45219. this.worldAxisForFileX = worldAxisForFileX;
  45220. this.worldAxisForFileY = worldAxisForFileY;
  45221. }
  45222. return FileFaceOrientation;
  45223. }());
  45224. /**
  45225. * Helper class dealing with the extraction of spherical polynomial dataArray
  45226. * from a cube map.
  45227. */
  45228. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45229. function CubeMapToSphericalPolynomialTools() {
  45230. }
  45231. /**
  45232. * Converts a texture to the according Spherical Polynomial data.
  45233. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45234. *
  45235. * @param texture The texture to extract the information from.
  45236. * @return The Spherical Polynomial data.
  45237. */
  45238. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45239. if (!texture.isCube) {
  45240. // Only supports cube Textures currently.
  45241. return null;
  45242. }
  45243. var size = texture.getSize().width;
  45244. var right = texture.readPixels(0);
  45245. var left = texture.readPixels(1);
  45246. var up;
  45247. var down;
  45248. if (texture.isRenderTarget) {
  45249. up = texture.readPixels(3);
  45250. down = texture.readPixels(2);
  45251. }
  45252. else {
  45253. up = texture.readPixels(2);
  45254. down = texture.readPixels(3);
  45255. }
  45256. var front = texture.readPixels(4);
  45257. var back = texture.readPixels(5);
  45258. var gammaSpace = texture.gammaSpace;
  45259. // Always read as RGBA.
  45260. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45261. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45262. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45263. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45264. }
  45265. var cubeInfo = {
  45266. size: size,
  45267. right: right,
  45268. left: left,
  45269. up: up,
  45270. down: down,
  45271. front: front,
  45272. back: back,
  45273. format: format,
  45274. type: type,
  45275. gammaSpace: gammaSpace,
  45276. };
  45277. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45278. };
  45279. /**
  45280. * Converts a cubemap to the according Spherical Polynomial data.
  45281. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45282. *
  45283. * @param cubeInfo The Cube map to extract the information from.
  45284. * @return The Spherical Polynomial data.
  45285. */
  45286. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45287. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45288. var totalSolidAngle = 0.0;
  45289. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45290. var du = 2.0 / cubeInfo.size;
  45291. var dv = du;
  45292. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45293. var minUV = du * 0.5 - 1.0;
  45294. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45295. var fileFace = this.FileFaces[faceIndex];
  45296. var dataArray = cubeInfo[fileFace.name];
  45297. var v = minUV;
  45298. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45299. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45300. // Because SP is still linear, so summation is fine in that basis.
  45301. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45302. for (var y = 0; y < cubeInfo.size; y++) {
  45303. var u = minUV;
  45304. for (var x = 0; x < cubeInfo.size; x++) {
  45305. // World direction (not normalised)
  45306. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45307. worldDirection.normalize();
  45308. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45309. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45310. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45311. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45312. // Handle Integer types.
  45313. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45314. r /= 255;
  45315. g /= 255;
  45316. b /= 255;
  45317. }
  45318. // Handle Gamma space textures.
  45319. if (cubeInfo.gammaSpace) {
  45320. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45321. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45322. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45323. }
  45324. var color = new BABYLON.Color3(r, g, b);
  45325. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45326. totalSolidAngle += deltaSolidAngle;
  45327. u += du;
  45328. }
  45329. v += dv;
  45330. }
  45331. }
  45332. // Solid angle for entire sphere is 4*pi
  45333. var sphereSolidAngle = 4.0 * Math.PI;
  45334. // Adjust the solid angle to allow for how many faces we processed.
  45335. var facesProcessed = 6.0;
  45336. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45337. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45338. // This is needed because the numerical integration over the cube uses a
  45339. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45340. // and also to compensate for accumulative error due to float precision in the summation.
  45341. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45342. sphericalHarmonics.scale(correctionFactor);
  45343. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45344. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45345. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45346. };
  45347. CubeMapToSphericalPolynomialTools.FileFaces = [
  45348. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45349. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45350. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45351. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45352. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45353. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45354. ];
  45355. return CubeMapToSphericalPolynomialTools;
  45356. }());
  45357. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45358. })(BABYLON || (BABYLON = {}));
  45359. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45360. var BABYLON;
  45361. (function (BABYLON) {
  45362. /**
  45363. * Manages the defines for the PBR Material.
  45364. * @hiddenChildren
  45365. */
  45366. var PBRMaterialDefines = /** @class */ (function (_super) {
  45367. __extends(PBRMaterialDefines, _super);
  45368. /**
  45369. * Initializes the PBR Material defines.
  45370. */
  45371. function PBRMaterialDefines() {
  45372. var _this = _super.call(this) || this;
  45373. _this.PBR = true;
  45374. _this.MAINUV1 = false;
  45375. _this.MAINUV2 = false;
  45376. _this.UV1 = false;
  45377. _this.UV2 = false;
  45378. _this.ALBEDO = false;
  45379. _this.ALBEDODIRECTUV = 0;
  45380. _this.VERTEXCOLOR = false;
  45381. _this.AMBIENT = false;
  45382. _this.AMBIENTDIRECTUV = 0;
  45383. _this.AMBIENTINGRAYSCALE = false;
  45384. _this.OPACITY = false;
  45385. _this.VERTEXALPHA = false;
  45386. _this.OPACITYDIRECTUV = 0;
  45387. _this.OPACITYRGB = false;
  45388. _this.ALPHATEST = false;
  45389. _this.DEPTHPREPASS = false;
  45390. _this.ALPHABLEND = false;
  45391. _this.ALPHAFROMALBEDO = false;
  45392. _this.ALPHATESTVALUE = "0.5";
  45393. _this.SPECULAROVERALPHA = false;
  45394. _this.RADIANCEOVERALPHA = false;
  45395. _this.ALPHAFRESNEL = false;
  45396. _this.LINEARALPHAFRESNEL = false;
  45397. _this.PREMULTIPLYALPHA = false;
  45398. _this.EMISSIVE = false;
  45399. _this.EMISSIVEDIRECTUV = 0;
  45400. _this.REFLECTIVITY = false;
  45401. _this.REFLECTIVITYDIRECTUV = 0;
  45402. _this.SPECULARTERM = false;
  45403. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45404. _this.MICROSURFACEAUTOMATIC = false;
  45405. _this.LODBASEDMICROSFURACE = false;
  45406. _this.MICROSURFACEMAP = false;
  45407. _this.MICROSURFACEMAPDIRECTUV = 0;
  45408. _this.METALLICWORKFLOW = false;
  45409. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45410. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45411. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45412. _this.AOSTOREINMETALMAPRED = false;
  45413. _this.ENVIRONMENTBRDF = false;
  45414. _this.NORMAL = false;
  45415. _this.TANGENT = false;
  45416. _this.BUMP = false;
  45417. _this.BUMPDIRECTUV = 0;
  45418. _this.OBJECTSPACE_NORMALMAP = false;
  45419. _this.PARALLAX = false;
  45420. _this.PARALLAXOCCLUSION = false;
  45421. _this.NORMALXYSCALE = true;
  45422. _this.LIGHTMAP = false;
  45423. _this.LIGHTMAPDIRECTUV = 0;
  45424. _this.USELIGHTMAPASSHADOWMAP = false;
  45425. _this.GAMMALIGHTMAP = false;
  45426. _this.REFLECTION = false;
  45427. _this.REFLECTIONMAP_3D = false;
  45428. _this.REFLECTIONMAP_SPHERICAL = false;
  45429. _this.REFLECTIONMAP_PLANAR = false;
  45430. _this.REFLECTIONMAP_CUBIC = false;
  45431. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45432. _this.REFLECTIONMAP_PROJECTION = false;
  45433. _this.REFLECTIONMAP_SKYBOX = false;
  45434. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45435. _this.REFLECTIONMAP_EXPLICIT = false;
  45436. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45437. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45438. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45439. _this.INVERTCUBICMAP = false;
  45440. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45441. _this.USESPHERICALINVERTEX = false;
  45442. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45443. _this.LODINREFLECTIONALPHA = false;
  45444. _this.GAMMAREFLECTION = false;
  45445. _this.RGBDREFLECTION = false;
  45446. _this.RADIANCEOCCLUSION = false;
  45447. _this.HORIZONOCCLUSION = false;
  45448. _this.REFRACTION = false;
  45449. _this.REFRACTIONMAP_3D = false;
  45450. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45451. _this.LODINREFRACTIONALPHA = false;
  45452. _this.GAMMAREFRACTION = false;
  45453. _this.RGBDREFRACTION = false;
  45454. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45455. _this.INSTANCES = false;
  45456. _this.NUM_BONE_INFLUENCERS = 0;
  45457. _this.BonesPerMesh = 0;
  45458. _this.NONUNIFORMSCALING = false;
  45459. _this.MORPHTARGETS = false;
  45460. _this.MORPHTARGETS_NORMAL = false;
  45461. _this.MORPHTARGETS_TANGENT = false;
  45462. _this.NUM_MORPH_INFLUENCERS = 0;
  45463. _this.IMAGEPROCESSING = false;
  45464. _this.VIGNETTE = false;
  45465. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45466. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45467. _this.TONEMAPPING = false;
  45468. _this.TONEMAPPING_ACES = false;
  45469. _this.CONTRAST = false;
  45470. _this.COLORCURVES = false;
  45471. _this.COLORGRADING = false;
  45472. _this.COLORGRADING3D = false;
  45473. _this.SAMPLER3DGREENDEPTH = false;
  45474. _this.SAMPLER3DBGRMAP = false;
  45475. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45476. _this.EXPOSURE = false;
  45477. _this.USEPHYSICALLIGHTFALLOFF = false;
  45478. _this.USEGLTFLIGHTFALLOFF = false;
  45479. _this.TWOSIDEDLIGHTING = false;
  45480. _this.SHADOWFLOAT = false;
  45481. _this.CLIPPLANE = false;
  45482. _this.CLIPPLANE2 = false;
  45483. _this.CLIPPLANE3 = false;
  45484. _this.CLIPPLANE4 = false;
  45485. _this.POINTSIZE = false;
  45486. _this.FOG = false;
  45487. _this.LOGARITHMICDEPTH = false;
  45488. _this.FORCENORMALFORWARD = false;
  45489. _this.SPECULARAA = false;
  45490. _this.UNLIT = false;
  45491. _this.rebuild();
  45492. return _this;
  45493. }
  45494. /**
  45495. * Resets the PBR Material defines.
  45496. */
  45497. PBRMaterialDefines.prototype.reset = function () {
  45498. _super.prototype.reset.call(this);
  45499. this.ALPHATESTVALUE = "0.5";
  45500. this.PBR = true;
  45501. };
  45502. return PBRMaterialDefines;
  45503. }(BABYLON.MaterialDefines));
  45504. /**
  45505. * The Physically based material base class of BJS.
  45506. *
  45507. * This offers the main features of a standard PBR material.
  45508. * For more information, please refer to the documentation :
  45509. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45510. */
  45511. var PBRBaseMaterial = /** @class */ (function (_super) {
  45512. __extends(PBRBaseMaterial, _super);
  45513. /**
  45514. * Instantiates a new PBRMaterial instance.
  45515. *
  45516. * @param name The material name
  45517. * @param scene The scene the material will be use in.
  45518. */
  45519. function PBRBaseMaterial(name, scene) {
  45520. var _this = _super.call(this, name, scene) || this;
  45521. /**
  45522. * Intensity of the direct lights e.g. the four lights available in your scene.
  45523. * This impacts both the direct diffuse and specular highlights.
  45524. */
  45525. _this._directIntensity = 1.0;
  45526. /**
  45527. * Intensity of the emissive part of the material.
  45528. * This helps controlling the emissive effect without modifying the emissive color.
  45529. */
  45530. _this._emissiveIntensity = 1.0;
  45531. /**
  45532. * Intensity of the environment e.g. how much the environment will light the object
  45533. * either through harmonics for rough material or through the refelction for shiny ones.
  45534. */
  45535. _this._environmentIntensity = 1.0;
  45536. /**
  45537. * This is a special control allowing the reduction of the specular highlights coming from the
  45538. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45539. */
  45540. _this._specularIntensity = 1.0;
  45541. /**
  45542. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45543. */
  45544. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45545. /**
  45546. * Debug Control allowing disabling the bump map on this material.
  45547. */
  45548. _this._disableBumpMap = false;
  45549. /**
  45550. * AKA Occlusion Texture Intensity in other nomenclature.
  45551. */
  45552. _this._ambientTextureStrength = 1.0;
  45553. /**
  45554. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45555. * 1 means it completely occludes it
  45556. * 0 mean it has no impact
  45557. */
  45558. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45559. /**
  45560. * The color of a material in ambient lighting.
  45561. */
  45562. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45563. /**
  45564. * AKA Diffuse Color in other nomenclature.
  45565. */
  45566. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45567. /**
  45568. * AKA Specular Color in other nomenclature.
  45569. */
  45570. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45571. /**
  45572. * The color applied when light is reflected from a material.
  45573. */
  45574. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45575. /**
  45576. * The color applied when light is emitted from a material.
  45577. */
  45578. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45579. /**
  45580. * AKA Glossiness in other nomenclature.
  45581. */
  45582. _this._microSurface = 0.9;
  45583. /**
  45584. * source material index of refraction (IOR)' / 'destination material IOR.
  45585. */
  45586. _this._indexOfRefraction = 0.66;
  45587. /**
  45588. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45589. */
  45590. _this._invertRefractionY = false;
  45591. /**
  45592. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45593. * Materials half opaque for instance using refraction could benefit from this control.
  45594. */
  45595. _this._linkRefractionWithTransparency = false;
  45596. /**
  45597. * Specifies that the material will use the light map as a show map.
  45598. */
  45599. _this._useLightmapAsShadowmap = false;
  45600. /**
  45601. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45602. * makes the reflect vector face the model (under horizon).
  45603. */
  45604. _this._useHorizonOcclusion = true;
  45605. /**
  45606. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45607. * too much the area relying on ambient texture to define their ambient occlusion.
  45608. */
  45609. _this._useRadianceOcclusion = true;
  45610. /**
  45611. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45612. */
  45613. _this._useAlphaFromAlbedoTexture = false;
  45614. /**
  45615. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45616. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45617. */
  45618. _this._useSpecularOverAlpha = true;
  45619. /**
  45620. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45621. */
  45622. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45623. /**
  45624. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45625. */
  45626. _this._useRoughnessFromMetallicTextureAlpha = true;
  45627. /**
  45628. * Specifies if the metallic texture contains the roughness information in its green channel.
  45629. */
  45630. _this._useRoughnessFromMetallicTextureGreen = false;
  45631. /**
  45632. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45633. */
  45634. _this._useMetallnessFromMetallicTextureBlue = false;
  45635. /**
  45636. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45637. */
  45638. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45639. /**
  45640. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45641. */
  45642. _this._useAmbientInGrayScale = false;
  45643. /**
  45644. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45645. * The material will try to infer what glossiness each pixel should be.
  45646. */
  45647. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45648. /**
  45649. * Defines the falloff type used in this material.
  45650. * It by default is Physical.
  45651. */
  45652. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45653. /**
  45654. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45655. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45656. */
  45657. _this._useRadianceOverAlpha = true;
  45658. /**
  45659. * Allows using an object space normal map (instead of tangent space).
  45660. */
  45661. _this._useObjectSpaceNormalMap = false;
  45662. /**
  45663. * Allows using the bump map in parallax mode.
  45664. */
  45665. _this._useParallax = false;
  45666. /**
  45667. * Allows using the bump map in parallax occlusion mode.
  45668. */
  45669. _this._useParallaxOcclusion = false;
  45670. /**
  45671. * Controls the scale bias of the parallax mode.
  45672. */
  45673. _this._parallaxScaleBias = 0.05;
  45674. /**
  45675. * If sets to true, disables all the lights affecting the material.
  45676. */
  45677. _this._disableLighting = false;
  45678. /**
  45679. * Number of Simultaneous lights allowed on the material.
  45680. */
  45681. _this._maxSimultaneousLights = 4;
  45682. /**
  45683. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45684. */
  45685. _this._invertNormalMapX = false;
  45686. /**
  45687. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45688. */
  45689. _this._invertNormalMapY = false;
  45690. /**
  45691. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45692. */
  45693. _this._twoSidedLighting = false;
  45694. /**
  45695. * Defines the alpha limits in alpha test mode.
  45696. */
  45697. _this._alphaCutOff = 0.4;
  45698. /**
  45699. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45700. */
  45701. _this._forceAlphaTest = false;
  45702. /**
  45703. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45704. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45705. */
  45706. _this._useAlphaFresnel = false;
  45707. /**
  45708. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45709. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45710. */
  45711. _this._useLinearAlphaFresnel = false;
  45712. /**
  45713. * The transparency mode of the material.
  45714. */
  45715. _this._transparencyMode = null;
  45716. /**
  45717. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45718. * from cos thetav and roughness:
  45719. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45720. */
  45721. _this._environmentBRDFTexture = null;
  45722. /**
  45723. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45724. */
  45725. _this._forceIrradianceInFragment = false;
  45726. /**
  45727. * Force normal to face away from face.
  45728. */
  45729. _this._forceNormalForward = false;
  45730. /**
  45731. * Enables specular anti aliasing in the PBR shader.
  45732. * It will both interacts on the Geometry for analytical and IBL lighting.
  45733. * It also prefilter the roughness map based on the bump values.
  45734. */
  45735. _this._enableSpecularAntiAliasing = false;
  45736. /**
  45737. * Stores the available render targets.
  45738. */
  45739. _this._renderTargets = new BABYLON.SmartArray(16);
  45740. /**
  45741. * Sets the global ambient color for the material used in lighting calculations.
  45742. */
  45743. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45744. /**
  45745. * If set to true, no lighting calculations will be applied.
  45746. */
  45747. _this._unlit = false;
  45748. // Setup the default processing configuration to the scene.
  45749. _this._attachImageProcessingConfiguration(null);
  45750. _this.getRenderTargetTextures = function () {
  45751. _this._renderTargets.reset();
  45752. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45753. _this._renderTargets.push(_this._reflectionTexture);
  45754. }
  45755. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45756. _this._renderTargets.push(_this._refractionTexture);
  45757. }
  45758. return _this._renderTargets;
  45759. };
  45760. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45761. return _this;
  45762. }
  45763. /**
  45764. * Attaches a new image processing configuration to the PBR Material.
  45765. * @param configuration
  45766. */
  45767. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45768. var _this = this;
  45769. if (configuration === this._imageProcessingConfiguration) {
  45770. return;
  45771. }
  45772. // Detaches observer.
  45773. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45774. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45775. }
  45776. // Pick the scene configuration if needed.
  45777. if (!configuration) {
  45778. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45779. }
  45780. else {
  45781. this._imageProcessingConfiguration = configuration;
  45782. }
  45783. // Attaches observer.
  45784. if (this._imageProcessingConfiguration) {
  45785. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45786. _this._markAllSubMeshesAsImageProcessingDirty();
  45787. });
  45788. }
  45789. };
  45790. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45791. /**
  45792. * Gets a boolean indicating that current material needs to register RTT
  45793. */
  45794. get: function () {
  45795. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45796. return true;
  45797. }
  45798. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45799. return true;
  45800. }
  45801. return false;
  45802. },
  45803. enumerable: true,
  45804. configurable: true
  45805. });
  45806. /**
  45807. * Gets the name of the material class.
  45808. */
  45809. PBRBaseMaterial.prototype.getClassName = function () {
  45810. return "PBRBaseMaterial";
  45811. };
  45812. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45813. /**
  45814. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45815. */
  45816. get: function () {
  45817. return this._useLogarithmicDepth;
  45818. },
  45819. /**
  45820. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45821. */
  45822. set: function (value) {
  45823. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45824. },
  45825. enumerable: true,
  45826. configurable: true
  45827. });
  45828. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45829. /**
  45830. * Gets the current transparency mode.
  45831. */
  45832. get: function () {
  45833. return this._transparencyMode;
  45834. },
  45835. /**
  45836. * Sets the transparency mode of the material.
  45837. *
  45838. * | Value | Type | Description |
  45839. * | ----- | ----------------------------------- | ----------- |
  45840. * | 0 | OPAQUE | |
  45841. * | 1 | ALPHATEST | |
  45842. * | 2 | ALPHABLEND | |
  45843. * | 3 | ALPHATESTANDBLEND | |
  45844. *
  45845. */
  45846. set: function (value) {
  45847. if (this._transparencyMode === value) {
  45848. return;
  45849. }
  45850. this._transparencyMode = value;
  45851. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45852. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45853. },
  45854. enumerable: true,
  45855. configurable: true
  45856. });
  45857. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45858. /**
  45859. * Returns true if alpha blending should be disabled.
  45860. */
  45861. get: function () {
  45862. return (this._linkRefractionWithTransparency ||
  45863. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45864. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45865. },
  45866. enumerable: true,
  45867. configurable: true
  45868. });
  45869. /**
  45870. * Specifies whether or not this material should be rendered in alpha blend mode.
  45871. */
  45872. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45873. if (this._disableAlphaBlending) {
  45874. return false;
  45875. }
  45876. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45877. };
  45878. /**
  45879. * Specifies if the mesh will require alpha blending.
  45880. * @param mesh - BJS mesh.
  45881. */
  45882. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45883. if (this._disableAlphaBlending) {
  45884. return false;
  45885. }
  45886. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45887. };
  45888. /**
  45889. * Specifies whether or not this material should be rendered in alpha test mode.
  45890. */
  45891. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45892. if (this._forceAlphaTest) {
  45893. return true;
  45894. }
  45895. if (this._linkRefractionWithTransparency) {
  45896. return false;
  45897. }
  45898. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45899. };
  45900. /**
  45901. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45902. */
  45903. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45904. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45905. };
  45906. /**
  45907. * Gets the texture used for the alpha test.
  45908. */
  45909. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45910. return this._albedoTexture;
  45911. };
  45912. /**
  45913. * Specifies that the submesh is ready to be used.
  45914. * @param mesh - BJS mesh.
  45915. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45916. * @param useInstances - Specifies that instances should be used.
  45917. * @returns - boolean indicating that the submesh is ready or not.
  45918. */
  45919. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45920. if (subMesh.effect && this.isFrozen) {
  45921. if (this._wasPreviouslyReady) {
  45922. return true;
  45923. }
  45924. }
  45925. if (!subMesh._materialDefines) {
  45926. subMesh._materialDefines = new PBRMaterialDefines();
  45927. }
  45928. var defines = subMesh._materialDefines;
  45929. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45930. if (defines._renderId === this.getScene().getRenderId()) {
  45931. return true;
  45932. }
  45933. }
  45934. var scene = this.getScene();
  45935. var engine = scene.getEngine();
  45936. if (defines._areTexturesDirty) {
  45937. if (scene.texturesEnabled) {
  45938. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45939. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45940. return false;
  45941. }
  45942. }
  45943. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45944. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45945. return false;
  45946. }
  45947. }
  45948. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45949. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45950. return false;
  45951. }
  45952. }
  45953. var reflectionTexture = this._getReflectionTexture();
  45954. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45955. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45956. return false;
  45957. }
  45958. }
  45959. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45960. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45961. return false;
  45962. }
  45963. }
  45964. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45965. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45966. return false;
  45967. }
  45968. }
  45969. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45970. if (this._metallicTexture) {
  45971. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45972. return false;
  45973. }
  45974. }
  45975. else if (this._reflectivityTexture) {
  45976. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45977. return false;
  45978. }
  45979. }
  45980. if (this._microSurfaceTexture) {
  45981. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45982. return false;
  45983. }
  45984. }
  45985. }
  45986. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45987. // Bump texture cannot be not blocking.
  45988. if (!this._bumpTexture.isReady()) {
  45989. return false;
  45990. }
  45991. }
  45992. var refractionTexture = this._getRefractionTexture();
  45993. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45994. if (!refractionTexture.isReadyOrNotBlocking()) {
  45995. return false;
  45996. }
  45997. }
  45998. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45999. // This is blocking.
  46000. if (!this._environmentBRDFTexture.isReady()) {
  46001. return false;
  46002. }
  46003. }
  46004. }
  46005. }
  46006. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46007. if (!this._imageProcessingConfiguration.isReady()) {
  46008. return false;
  46009. }
  46010. }
  46011. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46012. mesh.createNormals(true);
  46013. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46014. }
  46015. var previousEffect = subMesh.effect;
  46016. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46017. if (effect) {
  46018. // Use previous effect while new one is compiling
  46019. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46020. effect = previousEffect;
  46021. defines.markAsUnprocessed();
  46022. }
  46023. else {
  46024. scene.resetCachedMaterial();
  46025. subMesh.setEffect(effect, defines);
  46026. this.buildUniformLayout();
  46027. }
  46028. }
  46029. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46030. return false;
  46031. }
  46032. defines._renderId = scene.getRenderId();
  46033. this._wasPreviouslyReady = true;
  46034. return true;
  46035. };
  46036. /**
  46037. * Specifies if the material uses metallic roughness workflow.
  46038. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46039. */
  46040. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46041. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46042. return true;
  46043. }
  46044. return false;
  46045. };
  46046. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46047. if (onCompiled === void 0) { onCompiled = null; }
  46048. if (onError === void 0) { onError = null; }
  46049. if (useInstances === void 0) { useInstances = null; }
  46050. if (useClipPlane === void 0) { useClipPlane = null; }
  46051. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46052. if (!defines.isDirty) {
  46053. return null;
  46054. }
  46055. defines.markAsProcessed();
  46056. var scene = this.getScene();
  46057. var engine = scene.getEngine();
  46058. // Fallbacks
  46059. var fallbacks = new BABYLON.EffectFallbacks();
  46060. var fallbackRank = 0;
  46061. if (defines.USESPHERICALINVERTEX) {
  46062. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46063. }
  46064. if (defines.FOG) {
  46065. fallbacks.addFallback(fallbackRank, "FOG");
  46066. }
  46067. if (defines.SPECULARAA) {
  46068. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46069. }
  46070. if (defines.POINTSIZE) {
  46071. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46072. }
  46073. if (defines.LOGARITHMICDEPTH) {
  46074. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46075. }
  46076. if (defines.PARALLAX) {
  46077. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46078. }
  46079. if (defines.PARALLAXOCCLUSION) {
  46080. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46081. }
  46082. if (defines.ENVIRONMENTBRDF) {
  46083. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46084. }
  46085. if (defines.TANGENT) {
  46086. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46087. }
  46088. if (defines.BUMP) {
  46089. fallbacks.addFallback(fallbackRank++, "BUMP");
  46090. }
  46091. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46092. if (defines.SPECULARTERM) {
  46093. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46094. }
  46095. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46096. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46097. }
  46098. if (defines.LIGHTMAP) {
  46099. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46100. }
  46101. if (defines.NORMAL) {
  46102. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46103. }
  46104. if (defines.AMBIENT) {
  46105. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46106. }
  46107. if (defines.EMISSIVE) {
  46108. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46109. }
  46110. if (defines.VERTEXCOLOR) {
  46111. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46112. }
  46113. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46114. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46115. }
  46116. if (defines.MORPHTARGETS) {
  46117. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46118. }
  46119. //Attributes
  46120. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46121. if (defines.NORMAL) {
  46122. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46123. }
  46124. if (defines.TANGENT) {
  46125. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46126. }
  46127. if (defines.UV1) {
  46128. attribs.push(BABYLON.VertexBuffer.UVKind);
  46129. }
  46130. if (defines.UV2) {
  46131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46132. }
  46133. if (defines.VERTEXCOLOR) {
  46134. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46135. }
  46136. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46137. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46138. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46139. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46140. "vFogInfos", "vFogColor", "pointSize",
  46141. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46142. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46143. "mBones",
  46144. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46145. "vLightingIntensity",
  46146. "logarithmicDepthConstant",
  46147. "vSphericalX", "vSphericalY", "vSphericalZ",
  46148. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46149. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46150. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46151. "vTangentSpaceParams"
  46152. ];
  46153. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46154. "bumpSampler", "lightmapSampler", "opacitySampler",
  46155. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46156. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46157. "microSurfaceSampler", "environmentBrdfSampler"];
  46158. var uniformBuffers = ["Material", "Scene"];
  46159. if (BABYLON.ImageProcessingConfiguration) {
  46160. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46161. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46162. }
  46163. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46164. uniformsNames: uniforms,
  46165. uniformBuffersNames: uniformBuffers,
  46166. samplers: samplers,
  46167. defines: defines,
  46168. maxSimultaneousLights: this._maxSimultaneousLights
  46169. });
  46170. var join = defines.toString();
  46171. return engine.createEffect("pbr", {
  46172. attributes: attribs,
  46173. uniformsNames: uniforms,
  46174. uniformBuffersNames: uniformBuffers,
  46175. samplers: samplers,
  46176. defines: join,
  46177. fallbacks: fallbacks,
  46178. onCompiled: onCompiled,
  46179. onError: onError,
  46180. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46181. }, engine);
  46182. };
  46183. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46184. if (useInstances === void 0) { useInstances = null; }
  46185. if (useClipPlane === void 0) { useClipPlane = null; }
  46186. var scene = this.getScene();
  46187. var engine = scene.getEngine();
  46188. // Lights
  46189. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46190. defines._needNormals = true;
  46191. // Textures
  46192. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46193. if (defines._areTexturesDirty) {
  46194. defines._needUVs = false;
  46195. if (scene.texturesEnabled) {
  46196. if (scene.getEngine().getCaps().textureLOD) {
  46197. defines.LODBASEDMICROSFURACE = true;
  46198. }
  46199. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46201. }
  46202. else {
  46203. defines.ALBEDO = false;
  46204. }
  46205. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46207. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46208. }
  46209. else {
  46210. defines.AMBIENT = false;
  46211. }
  46212. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46213. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46214. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46215. }
  46216. else {
  46217. defines.OPACITY = false;
  46218. }
  46219. var reflectionTexture = this._getReflectionTexture();
  46220. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46221. defines.REFLECTION = true;
  46222. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46223. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46224. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46225. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46226. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46227. defines.INVERTCUBICMAP = true;
  46228. }
  46229. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46230. switch (reflectionTexture.coordinatesMode) {
  46231. case BABYLON.Texture.EXPLICIT_MODE:
  46232. defines.REFLECTIONMAP_EXPLICIT = true;
  46233. break;
  46234. case BABYLON.Texture.PLANAR_MODE:
  46235. defines.REFLECTIONMAP_PLANAR = true;
  46236. break;
  46237. case BABYLON.Texture.PROJECTION_MODE:
  46238. defines.REFLECTIONMAP_PROJECTION = true;
  46239. break;
  46240. case BABYLON.Texture.SKYBOX_MODE:
  46241. defines.REFLECTIONMAP_SKYBOX = true;
  46242. break;
  46243. case BABYLON.Texture.SPHERICAL_MODE:
  46244. defines.REFLECTIONMAP_SPHERICAL = true;
  46245. break;
  46246. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46247. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46248. break;
  46249. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46250. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46251. break;
  46252. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46253. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46254. break;
  46255. case BABYLON.Texture.CUBIC_MODE:
  46256. case BABYLON.Texture.INVCUBIC_MODE:
  46257. default:
  46258. defines.REFLECTIONMAP_CUBIC = true;
  46259. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46260. break;
  46261. }
  46262. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46263. if (reflectionTexture.sphericalPolynomial) {
  46264. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46265. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46266. defines.USESPHERICALINVERTEX = false;
  46267. }
  46268. else {
  46269. defines.USESPHERICALINVERTEX = true;
  46270. }
  46271. }
  46272. }
  46273. else {
  46274. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46275. }
  46276. }
  46277. else {
  46278. defines.REFLECTION = false;
  46279. defines.REFLECTIONMAP_3D = false;
  46280. defines.REFLECTIONMAP_SPHERICAL = false;
  46281. defines.REFLECTIONMAP_PLANAR = false;
  46282. defines.REFLECTIONMAP_CUBIC = false;
  46283. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46284. defines.REFLECTIONMAP_PROJECTION = false;
  46285. defines.REFLECTIONMAP_SKYBOX = false;
  46286. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46287. defines.REFLECTIONMAP_EXPLICIT = false;
  46288. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46289. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46290. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46291. defines.INVERTCUBICMAP = false;
  46292. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46293. defines.USESPHERICALINVERTEX = false;
  46294. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46295. defines.LODINREFLECTIONALPHA = false;
  46296. defines.GAMMAREFLECTION = false;
  46297. defines.RGBDREFLECTION = false;
  46298. }
  46299. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46301. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46302. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46303. }
  46304. else {
  46305. defines.LIGHTMAP = false;
  46306. }
  46307. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46309. }
  46310. else {
  46311. defines.EMISSIVE = false;
  46312. }
  46313. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46314. if (this._metallicTexture) {
  46315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46316. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46317. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46318. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46319. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46320. }
  46321. else if (this._reflectivityTexture) {
  46322. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46323. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46324. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46325. }
  46326. else {
  46327. defines.REFLECTIVITY = false;
  46328. }
  46329. if (this._microSurfaceTexture) {
  46330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46331. }
  46332. else {
  46333. defines.MICROSURFACEMAP = false;
  46334. }
  46335. }
  46336. else {
  46337. defines.REFLECTIVITY = false;
  46338. defines.MICROSURFACEMAP = false;
  46339. }
  46340. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46342. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46343. defines.PARALLAX = true;
  46344. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46345. }
  46346. else {
  46347. defines.PARALLAX = false;
  46348. }
  46349. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46350. }
  46351. else {
  46352. defines.BUMP = false;
  46353. }
  46354. var refractionTexture = this._getRefractionTexture();
  46355. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46356. defines.REFRACTION = true;
  46357. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46358. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46359. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46360. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46361. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46362. if (this._linkRefractionWithTransparency) {
  46363. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46364. }
  46365. }
  46366. else {
  46367. defines.REFRACTION = false;
  46368. }
  46369. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46370. defines.ENVIRONMENTBRDF = true;
  46371. }
  46372. else {
  46373. defines.ENVIRONMENTBRDF = false;
  46374. }
  46375. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46376. defines.ALPHAFROMALBEDO = true;
  46377. }
  46378. else {
  46379. defines.ALPHAFROMALBEDO = false;
  46380. }
  46381. }
  46382. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46383. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46384. defines.USEPHYSICALLIGHTFALLOFF = false;
  46385. defines.USEGLTFLIGHTFALLOFF = false;
  46386. }
  46387. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46388. defines.USEPHYSICALLIGHTFALLOFF = false;
  46389. defines.USEGLTFLIGHTFALLOFF = true;
  46390. }
  46391. else {
  46392. defines.USEPHYSICALLIGHTFALLOFF = true;
  46393. defines.USEGLTFLIGHTFALLOFF = false;
  46394. }
  46395. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46396. if (!this.backFaceCulling && this._twoSidedLighting) {
  46397. defines.TWOSIDEDLIGHTING = true;
  46398. }
  46399. else {
  46400. defines.TWOSIDEDLIGHTING = false;
  46401. }
  46402. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46403. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46404. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46405. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46406. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46407. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46408. }
  46409. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46410. this._imageProcessingConfiguration.prepareDefines(defines);
  46411. }
  46412. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46413. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46414. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46415. // Misc.
  46416. if (defines._areMiscDirty) {
  46417. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46418. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46419. }
  46420. // Values that need to be evaluated on every frame
  46421. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46422. // Attribs
  46423. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46424. };
  46425. /**
  46426. * Force shader compilation
  46427. */
  46428. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46429. var _this = this;
  46430. var localOptions = __assign({ clipPlane: false }, options);
  46431. var defines = new PBRMaterialDefines();
  46432. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46433. if (effect.isReady()) {
  46434. if (onCompiled) {
  46435. onCompiled(this);
  46436. }
  46437. }
  46438. else {
  46439. effect.onCompileObservable.add(function () {
  46440. if (onCompiled) {
  46441. onCompiled(_this);
  46442. }
  46443. });
  46444. }
  46445. };
  46446. /**
  46447. * Initializes the uniform buffer layout for the shader.
  46448. */
  46449. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46450. // Order is important !
  46451. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46452. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46453. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46454. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46455. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46456. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46457. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46458. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46459. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46460. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46461. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46462. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46463. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46464. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46465. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46466. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46467. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46468. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46469. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46470. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46471. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46472. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46473. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46474. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46475. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46476. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46477. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46478. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46479. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46480. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46481. this._uniformBuffer.addUniform("pointSize", 1);
  46482. this._uniformBuffer.create();
  46483. };
  46484. /**
  46485. * Unbinds the textures.
  46486. */
  46487. PBRBaseMaterial.prototype.unbind = function () {
  46488. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46489. this._uniformBuffer.setTexture("reflectionSampler", null);
  46490. }
  46491. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46492. this._uniformBuffer.setTexture("refractionSampler", null);
  46493. }
  46494. _super.prototype.unbind.call(this);
  46495. };
  46496. /**
  46497. * Binds the submesh data.
  46498. * @param world - The world matrix.
  46499. * @param mesh - The BJS mesh.
  46500. * @param subMesh - A submesh of the BJS mesh.
  46501. */
  46502. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46503. var scene = this.getScene();
  46504. var defines = subMesh._materialDefines;
  46505. if (!defines) {
  46506. return;
  46507. }
  46508. var effect = subMesh.effect;
  46509. if (!effect) {
  46510. return;
  46511. }
  46512. this._activeEffect = effect;
  46513. // Matrices
  46514. this.bindOnlyWorldMatrix(world);
  46515. // Normal Matrix
  46516. if (defines.OBJECTSPACE_NORMALMAP) {
  46517. world.toNormalMatrix(this._normalMatrix);
  46518. this.bindOnlyNormalMatrix(this._normalMatrix);
  46519. }
  46520. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46521. // Bones
  46522. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46523. var reflectionTexture = null;
  46524. if (mustRebind) {
  46525. this._uniformBuffer.bindToEffect(effect, "Material");
  46526. this.bindViewProjection(effect);
  46527. reflectionTexture = this._getReflectionTexture();
  46528. var refractionTexture = this._getRefractionTexture();
  46529. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46530. // Texture uniforms
  46531. if (scene.texturesEnabled) {
  46532. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46533. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46534. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46535. }
  46536. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46537. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46538. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46539. }
  46540. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46541. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46542. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46543. }
  46544. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46545. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46546. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46547. if (reflectionTexture.boundingBoxSize) {
  46548. var cubeTexture = reflectionTexture;
  46549. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46550. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46551. }
  46552. var polynomials = reflectionTexture.sphericalPolynomial;
  46553. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46554. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46555. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46556. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46557. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46558. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46559. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46560. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46561. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46562. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46563. }
  46564. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46565. }
  46566. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46567. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46568. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46569. }
  46570. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46571. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46572. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46573. }
  46574. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46575. if (this._metallicTexture) {
  46576. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46577. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46578. }
  46579. else if (this._reflectivityTexture) {
  46580. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46581. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46582. }
  46583. if (this._microSurfaceTexture) {
  46584. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46585. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46586. }
  46587. }
  46588. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46589. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46590. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46591. if (scene._mirroredCameraPosition) {
  46592. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46593. }
  46594. else {
  46595. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46596. }
  46597. }
  46598. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46599. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46600. var depth = 1.0;
  46601. if (!refractionTexture.isCube) {
  46602. if (refractionTexture.depth) {
  46603. depth = refractionTexture.depth;
  46604. }
  46605. }
  46606. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46607. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46608. }
  46609. }
  46610. // Point size
  46611. if (this.pointsCloud) {
  46612. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46613. }
  46614. // Colors
  46615. if (defines.METALLICWORKFLOW) {
  46616. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46617. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46618. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46619. }
  46620. else {
  46621. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46622. }
  46623. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46624. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46625. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46626. // Misc
  46627. this._lightingInfos.x = this._directIntensity;
  46628. this._lightingInfos.y = this._emissiveIntensity;
  46629. this._lightingInfos.z = this._environmentIntensity;
  46630. this._lightingInfos.w = this._specularIntensity;
  46631. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46632. }
  46633. // Textures
  46634. if (scene.texturesEnabled) {
  46635. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46636. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46637. }
  46638. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46639. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46640. }
  46641. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46642. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46643. }
  46644. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46645. if (defines.LODBASEDMICROSFURACE) {
  46646. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46647. }
  46648. else {
  46649. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46650. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46651. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46652. }
  46653. }
  46654. if (defines.ENVIRONMENTBRDF) {
  46655. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46656. }
  46657. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46658. if (defines.LODBASEDMICROSFURACE) {
  46659. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46660. }
  46661. else {
  46662. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46663. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46664. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46665. }
  46666. }
  46667. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46668. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46669. }
  46670. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46671. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46672. }
  46673. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46674. if (this._metallicTexture) {
  46675. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46676. }
  46677. else if (this._reflectivityTexture) {
  46678. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46679. }
  46680. if (this._microSurfaceTexture) {
  46681. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46682. }
  46683. }
  46684. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46685. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46686. }
  46687. }
  46688. // Clip plane
  46689. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46690. // Colors
  46691. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46692. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46693. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46694. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46695. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46696. }
  46697. if (mustRebind || !this.isFrozen) {
  46698. // Lights
  46699. if (scene.lightsEnabled && !this._disableLighting) {
  46700. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46701. }
  46702. // View
  46703. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46704. this.bindView(effect);
  46705. }
  46706. // Fog
  46707. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46708. // Morph targets
  46709. if (defines.NUM_MORPH_INFLUENCERS) {
  46710. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46711. }
  46712. // image processing
  46713. this._imageProcessingConfiguration.bind(this._activeEffect);
  46714. // Log. depth
  46715. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46716. }
  46717. this._uniformBuffer.update();
  46718. this._afterBind(mesh, this._activeEffect);
  46719. };
  46720. /**
  46721. * Returns the animatable textures.
  46722. * @returns - Array of animatable textures.
  46723. */
  46724. PBRBaseMaterial.prototype.getAnimatables = function () {
  46725. var results = [];
  46726. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46727. results.push(this._albedoTexture);
  46728. }
  46729. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46730. results.push(this._ambientTexture);
  46731. }
  46732. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46733. results.push(this._opacityTexture);
  46734. }
  46735. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46736. results.push(this._reflectionTexture);
  46737. }
  46738. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46739. results.push(this._emissiveTexture);
  46740. }
  46741. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46742. results.push(this._metallicTexture);
  46743. }
  46744. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46745. results.push(this._reflectivityTexture);
  46746. }
  46747. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46748. results.push(this._bumpTexture);
  46749. }
  46750. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46751. results.push(this._lightmapTexture);
  46752. }
  46753. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46754. results.push(this._refractionTexture);
  46755. }
  46756. return results;
  46757. };
  46758. /**
  46759. * Returns the texture used for reflections.
  46760. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46761. */
  46762. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46763. if (this._reflectionTexture) {
  46764. return this._reflectionTexture;
  46765. }
  46766. return this.getScene().environmentTexture;
  46767. };
  46768. /**
  46769. * Returns the texture used for refraction or null if none is used.
  46770. * @returns - Refection texture if present. If no refraction texture and refraction
  46771. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46772. */
  46773. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46774. if (this._refractionTexture) {
  46775. return this._refractionTexture;
  46776. }
  46777. if (this._linkRefractionWithTransparency) {
  46778. return this.getScene().environmentTexture;
  46779. }
  46780. return null;
  46781. };
  46782. /**
  46783. * Disposes the resources of the material.
  46784. * @param forceDisposeEffect - Forces the disposal of effects.
  46785. * @param forceDisposeTextures - Forces the disposal of all textures.
  46786. */
  46787. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46788. if (forceDisposeTextures) {
  46789. if (this._albedoTexture) {
  46790. this._albedoTexture.dispose();
  46791. }
  46792. if (this._ambientTexture) {
  46793. this._ambientTexture.dispose();
  46794. }
  46795. if (this._opacityTexture) {
  46796. this._opacityTexture.dispose();
  46797. }
  46798. if (this._reflectionTexture) {
  46799. this._reflectionTexture.dispose();
  46800. }
  46801. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46802. this._environmentBRDFTexture.dispose();
  46803. }
  46804. if (this._emissiveTexture) {
  46805. this._emissiveTexture.dispose();
  46806. }
  46807. if (this._metallicTexture) {
  46808. this._metallicTexture.dispose();
  46809. }
  46810. if (this._reflectivityTexture) {
  46811. this._reflectivityTexture.dispose();
  46812. }
  46813. if (this._bumpTexture) {
  46814. this._bumpTexture.dispose();
  46815. }
  46816. if (this._lightmapTexture) {
  46817. this._lightmapTexture.dispose();
  46818. }
  46819. if (this._refractionTexture) {
  46820. this._refractionTexture.dispose();
  46821. }
  46822. }
  46823. this._renderTargets.dispose();
  46824. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46825. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46826. }
  46827. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46828. };
  46829. /**
  46830. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46831. */
  46832. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46833. /**
  46834. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46835. * to enhance interoperability with other engines.
  46836. */
  46837. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46838. /**
  46839. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46840. * to enhance interoperability with other materials.
  46841. */
  46842. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46843. /**
  46844. * Stores the reflectivity values based on metallic roughness workflow.
  46845. */
  46846. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46847. __decorate([
  46848. BABYLON.serializeAsImageProcessingConfiguration()
  46849. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46850. __decorate([
  46851. BABYLON.serialize()
  46852. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46853. __decorate([
  46854. BABYLON.serialize()
  46855. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46856. return PBRBaseMaterial;
  46857. }(BABYLON.PushMaterial));
  46858. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46859. })(BABYLON || (BABYLON = {}));
  46860. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46861. var BABYLON;
  46862. (function (BABYLON) {
  46863. /**
  46864. * The Physically based simple base material of BJS.
  46865. *
  46866. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46867. * It is used as the base class for both the specGloss and metalRough conventions.
  46868. */
  46869. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46870. __extends(PBRBaseSimpleMaterial, _super);
  46871. /**
  46872. * Instantiates a new PBRMaterial instance.
  46873. *
  46874. * @param name The material name
  46875. * @param scene The scene the material will be use in.
  46876. */
  46877. function PBRBaseSimpleMaterial(name, scene) {
  46878. var _this = _super.call(this, name, scene) || this;
  46879. /**
  46880. * Number of Simultaneous lights allowed on the material.
  46881. */
  46882. _this.maxSimultaneousLights = 4;
  46883. /**
  46884. * If sets to true, disables all the lights affecting the material.
  46885. */
  46886. _this.disableLighting = false;
  46887. /**
  46888. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46889. */
  46890. _this.invertNormalMapX = false;
  46891. /**
  46892. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46893. */
  46894. _this.invertNormalMapY = false;
  46895. /**
  46896. * Emissivie color used to self-illuminate the model.
  46897. */
  46898. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46899. /**
  46900. * Occlusion Channel Strenght.
  46901. */
  46902. _this.occlusionStrength = 1.0;
  46903. /**
  46904. * If true, the light map contains occlusion information instead of lighting info.
  46905. */
  46906. _this.useLightmapAsShadowmap = false;
  46907. _this._useAlphaFromAlbedoTexture = true;
  46908. _this._useAmbientInGrayScale = true;
  46909. return _this;
  46910. }
  46911. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46912. /**
  46913. * Gets the current double sided mode.
  46914. */
  46915. get: function () {
  46916. return this._twoSidedLighting;
  46917. },
  46918. /**
  46919. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46920. */
  46921. set: function (value) {
  46922. if (this._twoSidedLighting === value) {
  46923. return;
  46924. }
  46925. this._twoSidedLighting = value;
  46926. this.backFaceCulling = !value;
  46927. this._markAllSubMeshesAsTexturesDirty();
  46928. },
  46929. enumerable: true,
  46930. configurable: true
  46931. });
  46932. /**
  46933. * Return the active textures of the material.
  46934. */
  46935. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46936. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46937. if (this.environmentTexture) {
  46938. activeTextures.push(this.environmentTexture);
  46939. }
  46940. if (this.normalTexture) {
  46941. activeTextures.push(this.normalTexture);
  46942. }
  46943. if (this.emissiveTexture) {
  46944. activeTextures.push(this.emissiveTexture);
  46945. }
  46946. if (this.occlusionTexture) {
  46947. activeTextures.push(this.occlusionTexture);
  46948. }
  46949. if (this.lightmapTexture) {
  46950. activeTextures.push(this.lightmapTexture);
  46951. }
  46952. return activeTextures;
  46953. };
  46954. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46955. if (_super.prototype.hasTexture.call(this, texture)) {
  46956. return true;
  46957. }
  46958. if (this.lightmapTexture === texture) {
  46959. return true;
  46960. }
  46961. return false;
  46962. };
  46963. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46964. return "PBRBaseSimpleMaterial";
  46965. };
  46966. __decorate([
  46967. BABYLON.serialize(),
  46968. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46969. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46970. __decorate([
  46971. BABYLON.serialize(),
  46972. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46973. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46974. __decorate([
  46975. BABYLON.serializeAsTexture(),
  46976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46977. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46978. __decorate([
  46979. BABYLON.serialize(),
  46980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46981. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46982. __decorate([
  46983. BABYLON.serialize(),
  46984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46985. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46986. __decorate([
  46987. BABYLON.serializeAsTexture(),
  46988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46989. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46990. __decorate([
  46991. BABYLON.serializeAsColor3("emissive"),
  46992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46993. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46994. __decorate([
  46995. BABYLON.serializeAsTexture(),
  46996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46997. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46998. __decorate([
  46999. BABYLON.serialize(),
  47000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47001. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47002. __decorate([
  47003. BABYLON.serializeAsTexture(),
  47004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47005. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47006. __decorate([
  47007. BABYLON.serialize(),
  47008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47009. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47010. __decorate([
  47011. BABYLON.serialize()
  47012. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47013. __decorate([
  47014. BABYLON.serializeAsTexture(),
  47015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47016. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47017. __decorate([
  47018. BABYLON.serialize(),
  47019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47020. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47021. return PBRBaseSimpleMaterial;
  47022. }(BABYLON.PBRBaseMaterial));
  47023. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47024. })(BABYLON || (BABYLON = {}));
  47025. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  47026. var BABYLON;
  47027. (function (BABYLON) {
  47028. /**
  47029. * The Physically based material of BJS.
  47030. *
  47031. * This offers the main features of a standard PBR material.
  47032. * For more information, please refer to the documentation :
  47033. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47034. */
  47035. var PBRMaterial = /** @class */ (function (_super) {
  47036. __extends(PBRMaterial, _super);
  47037. /**
  47038. * Instantiates a new PBRMaterial instance.
  47039. *
  47040. * @param name The material name
  47041. * @param scene The scene the material will be use in.
  47042. */
  47043. function PBRMaterial(name, scene) {
  47044. var _this = _super.call(this, name, scene) || this;
  47045. /**
  47046. * Intensity of the direct lights e.g. the four lights available in your scene.
  47047. * This impacts both the direct diffuse and specular highlights.
  47048. */
  47049. _this.directIntensity = 1.0;
  47050. /**
  47051. * Intensity of the emissive part of the material.
  47052. * This helps controlling the emissive effect without modifying the emissive color.
  47053. */
  47054. _this.emissiveIntensity = 1.0;
  47055. /**
  47056. * Intensity of the environment e.g. how much the environment will light the object
  47057. * either through harmonics for rough material or through the refelction for shiny ones.
  47058. */
  47059. _this.environmentIntensity = 1.0;
  47060. /**
  47061. * This is a special control allowing the reduction of the specular highlights coming from the
  47062. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47063. */
  47064. _this.specularIntensity = 1.0;
  47065. /**
  47066. * Debug Control allowing disabling the bump map on this material.
  47067. */
  47068. _this.disableBumpMap = false;
  47069. /**
  47070. * AKA Occlusion Texture Intensity in other nomenclature.
  47071. */
  47072. _this.ambientTextureStrength = 1.0;
  47073. /**
  47074. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47075. * 1 means it completely occludes it
  47076. * 0 mean it has no impact
  47077. */
  47078. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47079. /**
  47080. * The color of a material in ambient lighting.
  47081. */
  47082. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47083. /**
  47084. * AKA Diffuse Color in other nomenclature.
  47085. */
  47086. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47087. /**
  47088. * AKA Specular Color in other nomenclature.
  47089. */
  47090. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47091. /**
  47092. * The color reflected from the material.
  47093. */
  47094. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47095. /**
  47096. * The color emitted from the material.
  47097. */
  47098. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47099. /**
  47100. * AKA Glossiness in other nomenclature.
  47101. */
  47102. _this.microSurface = 1.0;
  47103. /**
  47104. * source material index of refraction (IOR)' / 'destination material IOR.
  47105. */
  47106. _this.indexOfRefraction = 0.66;
  47107. /**
  47108. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47109. */
  47110. _this.invertRefractionY = false;
  47111. /**
  47112. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47113. * Materials half opaque for instance using refraction could benefit from this control.
  47114. */
  47115. _this.linkRefractionWithTransparency = false;
  47116. /**
  47117. * If true, the light map contains occlusion information instead of lighting info.
  47118. */
  47119. _this.useLightmapAsShadowmap = false;
  47120. /**
  47121. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47122. */
  47123. _this.useAlphaFromAlbedoTexture = false;
  47124. /**
  47125. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47126. */
  47127. _this.forceAlphaTest = false;
  47128. /**
  47129. * Defines the alpha limits in alpha test mode.
  47130. */
  47131. _this.alphaCutOff = 0.4;
  47132. /**
  47133. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47134. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47135. */
  47136. _this.useSpecularOverAlpha = true;
  47137. /**
  47138. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47139. */
  47140. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47141. /**
  47142. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47143. */
  47144. _this.useRoughnessFromMetallicTextureAlpha = true;
  47145. /**
  47146. * Specifies if the metallic texture contains the roughness information in its green channel.
  47147. */
  47148. _this.useRoughnessFromMetallicTextureGreen = false;
  47149. /**
  47150. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47151. */
  47152. _this.useMetallnessFromMetallicTextureBlue = false;
  47153. /**
  47154. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47155. */
  47156. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47157. /**
  47158. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47159. */
  47160. _this.useAmbientInGrayScale = false;
  47161. /**
  47162. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47163. * The material will try to infer what glossiness each pixel should be.
  47164. */
  47165. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47166. /**
  47167. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47168. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47169. */
  47170. _this.useRadianceOverAlpha = true;
  47171. /**
  47172. * Allows using an object space normal map (instead of tangent space).
  47173. */
  47174. _this.useObjectSpaceNormalMap = false;
  47175. /**
  47176. * Allows using the bump map in parallax mode.
  47177. */
  47178. _this.useParallax = false;
  47179. /**
  47180. * Allows using the bump map in parallax occlusion mode.
  47181. */
  47182. _this.useParallaxOcclusion = false;
  47183. /**
  47184. * Controls the scale bias of the parallax mode.
  47185. */
  47186. _this.parallaxScaleBias = 0.05;
  47187. /**
  47188. * If sets to true, disables all the lights affecting the material.
  47189. */
  47190. _this.disableLighting = false;
  47191. /**
  47192. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47193. */
  47194. _this.forceIrradianceInFragment = false;
  47195. /**
  47196. * Number of Simultaneous lights allowed on the material.
  47197. */
  47198. _this.maxSimultaneousLights = 4;
  47199. /**
  47200. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47201. */
  47202. _this.invertNormalMapX = false;
  47203. /**
  47204. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47205. */
  47206. _this.invertNormalMapY = false;
  47207. /**
  47208. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47209. */
  47210. _this.twoSidedLighting = false;
  47211. /**
  47212. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47213. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47214. */
  47215. _this.useAlphaFresnel = false;
  47216. /**
  47217. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47218. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47219. */
  47220. _this.useLinearAlphaFresnel = false;
  47221. /**
  47222. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47223. * And/Or occlude the blended part.
  47224. */
  47225. _this.environmentBRDFTexture = null;
  47226. /**
  47227. * Force normal to face away from face.
  47228. */
  47229. _this.forceNormalForward = false;
  47230. /**
  47231. * Enables specular anti aliasing in the PBR shader.
  47232. * It will both interacts on the Geometry for analytical and IBL lighting.
  47233. * It also prefilter the roughness map based on the bump values.
  47234. */
  47235. _this.enableSpecularAntiAliasing = false;
  47236. /**
  47237. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47238. * makes the reflect vector face the model (under horizon).
  47239. */
  47240. _this.useHorizonOcclusion = true;
  47241. /**
  47242. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47243. * too much the area relying on ambient texture to define their ambient occlusion.
  47244. */
  47245. _this.useRadianceOcclusion = true;
  47246. /**
  47247. * If set to true, no lighting calculations will be applied.
  47248. */
  47249. _this.unlit = false;
  47250. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47251. return _this;
  47252. }
  47253. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47254. /**
  47255. * BJS is using an harcoded light falloff based on a manually sets up range.
  47256. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47257. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47258. */
  47259. get: function () {
  47260. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47261. },
  47262. /**
  47263. * BJS is using an harcoded light falloff based on a manually sets up range.
  47264. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47265. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47266. */
  47267. set: function (value) {
  47268. if (value !== this.usePhysicalLightFalloff) {
  47269. // Ensure the effect will be rebuilt.
  47270. this._markAllSubMeshesAsTexturesDirty();
  47271. if (value) {
  47272. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47273. }
  47274. else {
  47275. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47276. }
  47277. }
  47278. },
  47279. enumerable: true,
  47280. configurable: true
  47281. });
  47282. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47283. /**
  47284. * In order to support the falloff compatibility with gltf, a special mode has been added
  47285. * to reproduce the gltf light falloff.
  47286. */
  47287. get: function () {
  47288. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47289. },
  47290. /**
  47291. * In order to support the falloff compatibility with gltf, a special mode has been added
  47292. * to reproduce the gltf light falloff.
  47293. */
  47294. set: function (value) {
  47295. if (value !== this.useGLTFLightFalloff) {
  47296. // Ensure the effect will be rebuilt.
  47297. this._markAllSubMeshesAsTexturesDirty();
  47298. if (value) {
  47299. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47300. }
  47301. else {
  47302. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47303. }
  47304. }
  47305. },
  47306. enumerable: true,
  47307. configurable: true
  47308. });
  47309. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47310. /**
  47311. * Gets the image processing configuration used either in this material.
  47312. */
  47313. get: function () {
  47314. return this._imageProcessingConfiguration;
  47315. },
  47316. /**
  47317. * Sets the Default image processing configuration used either in the this material.
  47318. *
  47319. * If sets to null, the scene one is in use.
  47320. */
  47321. set: function (value) {
  47322. this._attachImageProcessingConfiguration(value);
  47323. // Ensure the effect will be rebuilt.
  47324. this._markAllSubMeshesAsTexturesDirty();
  47325. },
  47326. enumerable: true,
  47327. configurable: true
  47328. });
  47329. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47330. /**
  47331. * Gets wether the color curves effect is enabled.
  47332. */
  47333. get: function () {
  47334. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47335. },
  47336. /**
  47337. * Sets wether the color curves effect is enabled.
  47338. */
  47339. set: function (value) {
  47340. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47341. },
  47342. enumerable: true,
  47343. configurable: true
  47344. });
  47345. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47346. /**
  47347. * Gets wether the color grading effect is enabled.
  47348. */
  47349. get: function () {
  47350. return this.imageProcessingConfiguration.colorGradingEnabled;
  47351. },
  47352. /**
  47353. * Gets wether the color grading effect is enabled.
  47354. */
  47355. set: function (value) {
  47356. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47357. },
  47358. enumerable: true,
  47359. configurable: true
  47360. });
  47361. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47362. /**
  47363. * Gets wether tonemapping is enabled or not.
  47364. */
  47365. get: function () {
  47366. return this._imageProcessingConfiguration.toneMappingEnabled;
  47367. },
  47368. /**
  47369. * Sets wether tonemapping is enabled or not
  47370. */
  47371. set: function (value) {
  47372. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47373. },
  47374. enumerable: true,
  47375. configurable: true
  47376. });
  47377. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47378. /**
  47379. * The camera exposure used on this material.
  47380. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47381. * This corresponds to a photographic exposure.
  47382. */
  47383. get: function () {
  47384. return this._imageProcessingConfiguration.exposure;
  47385. },
  47386. /**
  47387. * The camera exposure used on this material.
  47388. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47389. * This corresponds to a photographic exposure.
  47390. */
  47391. set: function (value) {
  47392. this._imageProcessingConfiguration.exposure = value;
  47393. },
  47394. enumerable: true,
  47395. configurable: true
  47396. });
  47397. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47398. /**
  47399. * Gets The camera contrast used on this material.
  47400. */
  47401. get: function () {
  47402. return this._imageProcessingConfiguration.contrast;
  47403. },
  47404. /**
  47405. * Sets The camera contrast used on this material.
  47406. */
  47407. set: function (value) {
  47408. this._imageProcessingConfiguration.contrast = value;
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47414. /**
  47415. * Gets the Color Grading 2D Lookup Texture.
  47416. */
  47417. get: function () {
  47418. return this._imageProcessingConfiguration.colorGradingTexture;
  47419. },
  47420. /**
  47421. * Sets the Color Grading 2D Lookup Texture.
  47422. */
  47423. set: function (value) {
  47424. this._imageProcessingConfiguration.colorGradingTexture = value;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47430. /**
  47431. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47432. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47433. * 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;
  47434. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47435. */
  47436. get: function () {
  47437. return this._imageProcessingConfiguration.colorCurves;
  47438. },
  47439. /**
  47440. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47441. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47442. * 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;
  47443. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47444. */
  47445. set: function (value) {
  47446. this._imageProcessingConfiguration.colorCurves = value;
  47447. },
  47448. enumerable: true,
  47449. configurable: true
  47450. });
  47451. /**
  47452. * Returns the name of this material class.
  47453. */
  47454. PBRMaterial.prototype.getClassName = function () {
  47455. return "PBRMaterial";
  47456. };
  47457. /**
  47458. * Returns an array of the actively used textures.
  47459. * @returns - Array of BaseTextures
  47460. */
  47461. PBRMaterial.prototype.getActiveTextures = function () {
  47462. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47463. if (this._albedoTexture) {
  47464. activeTextures.push(this._albedoTexture);
  47465. }
  47466. if (this._ambientTexture) {
  47467. activeTextures.push(this._ambientTexture);
  47468. }
  47469. if (this._opacityTexture) {
  47470. activeTextures.push(this._opacityTexture);
  47471. }
  47472. if (this._reflectionTexture) {
  47473. activeTextures.push(this._reflectionTexture);
  47474. }
  47475. if (this._emissiveTexture) {
  47476. activeTextures.push(this._emissiveTexture);
  47477. }
  47478. if (this._reflectivityTexture) {
  47479. activeTextures.push(this._reflectivityTexture);
  47480. }
  47481. if (this._metallicTexture) {
  47482. activeTextures.push(this._metallicTexture);
  47483. }
  47484. if (this._microSurfaceTexture) {
  47485. activeTextures.push(this._microSurfaceTexture);
  47486. }
  47487. if (this._bumpTexture) {
  47488. activeTextures.push(this._bumpTexture);
  47489. }
  47490. if (this._lightmapTexture) {
  47491. activeTextures.push(this._lightmapTexture);
  47492. }
  47493. if (this._refractionTexture) {
  47494. activeTextures.push(this._refractionTexture);
  47495. }
  47496. return activeTextures;
  47497. };
  47498. /**
  47499. * Checks to see if a texture is used in the material.
  47500. * @param texture - Base texture to use.
  47501. * @returns - Boolean specifying if a texture is used in the material.
  47502. */
  47503. PBRMaterial.prototype.hasTexture = function (texture) {
  47504. if (_super.prototype.hasTexture.call(this, texture)) {
  47505. return true;
  47506. }
  47507. if (this._albedoTexture === texture) {
  47508. return true;
  47509. }
  47510. if (this._ambientTexture === texture) {
  47511. return true;
  47512. }
  47513. if (this._opacityTexture === texture) {
  47514. return true;
  47515. }
  47516. if (this._reflectionTexture === texture) {
  47517. return true;
  47518. }
  47519. if (this._reflectivityTexture === texture) {
  47520. return true;
  47521. }
  47522. if (this._metallicTexture === texture) {
  47523. return true;
  47524. }
  47525. if (this._microSurfaceTexture === texture) {
  47526. return true;
  47527. }
  47528. if (this._bumpTexture === texture) {
  47529. return true;
  47530. }
  47531. if (this._lightmapTexture === texture) {
  47532. return true;
  47533. }
  47534. if (this._refractionTexture === texture) {
  47535. return true;
  47536. }
  47537. return false;
  47538. };
  47539. /**
  47540. * Makes a duplicate of the current material.
  47541. * @param name - name to use for the new material.
  47542. */
  47543. PBRMaterial.prototype.clone = function (name) {
  47544. var _this = this;
  47545. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47546. clone.id = name;
  47547. clone.name = name;
  47548. return clone;
  47549. };
  47550. /**
  47551. * Serializes this PBR Material.
  47552. * @returns - An object with the serialized material.
  47553. */
  47554. PBRMaterial.prototype.serialize = function () {
  47555. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47556. serializationObject.customType = "BABYLON.PBRMaterial";
  47557. return serializationObject;
  47558. };
  47559. // Statics
  47560. /**
  47561. * Parses a PBR Material from a serialized object.
  47562. * @param source - Serialized object.
  47563. * @param scene - BJS scene instance.
  47564. * @param rootUrl - url for the scene object
  47565. * @returns - PBRMaterial
  47566. */
  47567. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47568. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47569. };
  47570. /**
  47571. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47572. */
  47573. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47574. /**
  47575. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47576. */
  47577. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47578. /**
  47579. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47580. */
  47581. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47582. /**
  47583. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47584. * They are also discarded below the alpha cutoff threshold to improve performances.
  47585. */
  47586. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47587. /**
  47588. * Defines the default value of how much AO map is occluding the analytical lights
  47589. * (point spot...).
  47590. */
  47591. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47592. __decorate([
  47593. BABYLON.serialize(),
  47594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47595. ], PBRMaterial.prototype, "directIntensity", void 0);
  47596. __decorate([
  47597. BABYLON.serialize(),
  47598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47599. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47600. __decorate([
  47601. BABYLON.serialize(),
  47602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47603. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47604. __decorate([
  47605. BABYLON.serialize(),
  47606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47607. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47608. __decorate([
  47609. BABYLON.serialize(),
  47610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47611. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47612. __decorate([
  47613. BABYLON.serializeAsTexture(),
  47614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47615. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47616. __decorate([
  47617. BABYLON.serializeAsTexture(),
  47618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47619. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47620. __decorate([
  47621. BABYLON.serialize(),
  47622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47623. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47624. __decorate([
  47625. BABYLON.serialize(),
  47626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47627. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47628. __decorate([
  47629. BABYLON.serializeAsTexture(),
  47630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47631. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47632. __decorate([
  47633. BABYLON.serializeAsTexture(),
  47634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47635. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47636. __decorate([
  47637. BABYLON.serializeAsTexture(),
  47638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47639. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47640. __decorate([
  47641. BABYLON.serializeAsTexture(),
  47642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47643. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47644. __decorate([
  47645. BABYLON.serializeAsTexture(),
  47646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47647. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47648. __decorate([
  47649. BABYLON.serialize(),
  47650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47651. ], PBRMaterial.prototype, "metallic", void 0);
  47652. __decorate([
  47653. BABYLON.serialize(),
  47654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47655. ], PBRMaterial.prototype, "roughness", void 0);
  47656. __decorate([
  47657. BABYLON.serializeAsTexture(),
  47658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47659. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47660. __decorate([
  47661. BABYLON.serializeAsTexture(),
  47662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47663. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47664. __decorate([
  47665. BABYLON.serializeAsTexture(),
  47666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47667. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47668. __decorate([
  47669. BABYLON.serializeAsTexture(),
  47670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47671. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47672. __decorate([
  47673. BABYLON.serializeAsColor3("ambient"),
  47674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47675. ], PBRMaterial.prototype, "ambientColor", void 0);
  47676. __decorate([
  47677. BABYLON.serializeAsColor3("albedo"),
  47678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47679. ], PBRMaterial.prototype, "albedoColor", void 0);
  47680. __decorate([
  47681. BABYLON.serializeAsColor3("reflectivity"),
  47682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47683. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47684. __decorate([
  47685. BABYLON.serializeAsColor3("reflection"),
  47686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47687. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47688. __decorate([
  47689. BABYLON.serializeAsColor3("emissive"),
  47690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47691. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47692. __decorate([
  47693. BABYLON.serialize(),
  47694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47695. ], PBRMaterial.prototype, "microSurface", void 0);
  47696. __decorate([
  47697. BABYLON.serialize(),
  47698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47699. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47700. __decorate([
  47701. BABYLON.serialize(),
  47702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47703. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47704. __decorate([
  47705. BABYLON.serialize(),
  47706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47707. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47708. __decorate([
  47709. BABYLON.serialize(),
  47710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47711. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47712. __decorate([
  47713. BABYLON.serialize(),
  47714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47715. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47716. __decorate([
  47717. BABYLON.serialize(),
  47718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47719. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47720. __decorate([
  47721. BABYLON.serialize(),
  47722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47723. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47724. __decorate([
  47725. BABYLON.serialize(),
  47726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47727. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47728. __decorate([
  47729. BABYLON.serialize(),
  47730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47731. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47732. __decorate([
  47733. BABYLON.serialize(),
  47734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47735. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47736. __decorate([
  47737. BABYLON.serialize(),
  47738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47739. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47740. __decorate([
  47741. BABYLON.serialize(),
  47742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47743. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47744. __decorate([
  47745. BABYLON.serialize(),
  47746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47747. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47748. __decorate([
  47749. BABYLON.serialize(),
  47750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47751. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47752. __decorate([
  47753. BABYLON.serialize(),
  47754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47755. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47756. __decorate([
  47757. BABYLON.serialize()
  47758. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47759. __decorate([
  47760. BABYLON.serialize()
  47761. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47762. __decorate([
  47763. BABYLON.serialize(),
  47764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47765. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47766. __decorate([
  47767. BABYLON.serialize(),
  47768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47769. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47770. __decorate([
  47771. BABYLON.serialize(),
  47772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47773. ], PBRMaterial.prototype, "useParallax", void 0);
  47774. __decorate([
  47775. BABYLON.serialize(),
  47776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47777. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47778. __decorate([
  47779. BABYLON.serialize(),
  47780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47781. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47782. __decorate([
  47783. BABYLON.serialize(),
  47784. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47785. ], PBRMaterial.prototype, "disableLighting", void 0);
  47786. __decorate([
  47787. BABYLON.serialize(),
  47788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47789. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47790. __decorate([
  47791. BABYLON.serialize(),
  47792. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47793. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47794. __decorate([
  47795. BABYLON.serialize(),
  47796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47797. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47798. __decorate([
  47799. BABYLON.serialize(),
  47800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47801. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47802. __decorate([
  47803. BABYLON.serialize(),
  47804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47805. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47806. __decorate([
  47807. BABYLON.serialize(),
  47808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47809. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47810. __decorate([
  47811. BABYLON.serialize(),
  47812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47813. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47814. __decorate([
  47815. BABYLON.serializeAsTexture(),
  47816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47817. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47818. __decorate([
  47819. BABYLON.serialize(),
  47820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47821. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47822. __decorate([
  47823. BABYLON.serialize(),
  47824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47825. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47826. __decorate([
  47827. BABYLON.serialize(),
  47828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47829. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47830. __decorate([
  47831. BABYLON.serialize(),
  47832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47833. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47834. __decorate([
  47835. BABYLON.serialize(),
  47836. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47837. ], PBRMaterial.prototype, "unlit", void 0);
  47838. return PBRMaterial;
  47839. }(BABYLON.PBRBaseMaterial));
  47840. BABYLON.PBRMaterial = PBRMaterial;
  47841. })(BABYLON || (BABYLON = {}));
  47842. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47843. var BABYLON;
  47844. (function (BABYLON) {
  47845. /**
  47846. * The PBR material of BJS following the metal roughness convention.
  47847. *
  47848. * This fits to the PBR convention in the GLTF definition:
  47849. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47850. */
  47851. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47852. __extends(PBRMetallicRoughnessMaterial, _super);
  47853. /**
  47854. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47855. *
  47856. * @param name The material name
  47857. * @param scene The scene the material will be use in.
  47858. */
  47859. function PBRMetallicRoughnessMaterial(name, scene) {
  47860. var _this = _super.call(this, name, scene) || this;
  47861. _this._useRoughnessFromMetallicTextureAlpha = false;
  47862. _this._useRoughnessFromMetallicTextureGreen = true;
  47863. _this._useMetallnessFromMetallicTextureBlue = true;
  47864. _this.metallic = 1.0;
  47865. _this.roughness = 1.0;
  47866. return _this;
  47867. }
  47868. /**
  47869. * Return the currrent class name of the material.
  47870. */
  47871. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47872. return "PBRMetallicRoughnessMaterial";
  47873. };
  47874. /**
  47875. * Return the active textures of the material.
  47876. */
  47877. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47878. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47879. if (this.baseTexture) {
  47880. activeTextures.push(this.baseTexture);
  47881. }
  47882. if (this.metallicRoughnessTexture) {
  47883. activeTextures.push(this.metallicRoughnessTexture);
  47884. }
  47885. return activeTextures;
  47886. };
  47887. /**
  47888. * Checks to see if a texture is used in the material.
  47889. * @param texture - Base texture to use.
  47890. * @returns - Boolean specifying if a texture is used in the material.
  47891. */
  47892. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47893. if (_super.prototype.hasTexture.call(this, texture)) {
  47894. return true;
  47895. }
  47896. if (this.baseTexture === texture) {
  47897. return true;
  47898. }
  47899. if (this.metallicRoughnessTexture === texture) {
  47900. return true;
  47901. }
  47902. return false;
  47903. };
  47904. /**
  47905. * Makes a duplicate of the current material.
  47906. * @param name - name to use for the new material.
  47907. */
  47908. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47909. var _this = this;
  47910. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47911. clone.id = name;
  47912. clone.name = name;
  47913. return clone;
  47914. };
  47915. /**
  47916. * Serialize the material to a parsable JSON object.
  47917. */
  47918. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47919. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47920. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47921. return serializationObject;
  47922. };
  47923. /**
  47924. * Parses a JSON object correponding to the serialize function.
  47925. */
  47926. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47927. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47928. };
  47929. __decorate([
  47930. BABYLON.serializeAsColor3(),
  47931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47932. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47933. __decorate([
  47934. BABYLON.serializeAsTexture(),
  47935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47936. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47937. __decorate([
  47938. BABYLON.serialize(),
  47939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47940. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47941. __decorate([
  47942. BABYLON.serialize(),
  47943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47944. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47945. __decorate([
  47946. BABYLON.serializeAsTexture(),
  47947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47948. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47949. return PBRMetallicRoughnessMaterial;
  47950. }(BABYLON.PBRBaseSimpleMaterial));
  47951. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47952. })(BABYLON || (BABYLON = {}));
  47953. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47954. var BABYLON;
  47955. (function (BABYLON) {
  47956. /**
  47957. * The PBR material of BJS following the specular glossiness convention.
  47958. *
  47959. * This fits to the PBR convention in the GLTF definition:
  47960. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47961. */
  47962. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47963. __extends(PBRSpecularGlossinessMaterial, _super);
  47964. /**
  47965. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47966. *
  47967. * @param name The material name
  47968. * @param scene The scene the material will be use in.
  47969. */
  47970. function PBRSpecularGlossinessMaterial(name, scene) {
  47971. var _this = _super.call(this, name, scene) || this;
  47972. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47973. return _this;
  47974. }
  47975. /**
  47976. * Return the currrent class name of the material.
  47977. */
  47978. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47979. return "PBRSpecularGlossinessMaterial";
  47980. };
  47981. /**
  47982. * Return the active textures of the material.
  47983. */
  47984. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47985. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47986. if (this.diffuseTexture) {
  47987. activeTextures.push(this.diffuseTexture);
  47988. }
  47989. if (this.specularGlossinessTexture) {
  47990. activeTextures.push(this.specularGlossinessTexture);
  47991. }
  47992. return activeTextures;
  47993. };
  47994. /**
  47995. * Checks to see if a texture is used in the material.
  47996. * @param texture - Base texture to use.
  47997. * @returns - Boolean specifying if a texture is used in the material.
  47998. */
  47999. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48000. if (_super.prototype.hasTexture.call(this, texture)) {
  48001. return true;
  48002. }
  48003. if (this.diffuseTexture === texture) {
  48004. return true;
  48005. }
  48006. if (this.specularGlossinessTexture === texture) {
  48007. return true;
  48008. }
  48009. return false;
  48010. };
  48011. /**
  48012. * Makes a duplicate of the current material.
  48013. * @param name - name to use for the new material.
  48014. */
  48015. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48016. var _this = this;
  48017. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48018. clone.id = name;
  48019. clone.name = name;
  48020. return clone;
  48021. };
  48022. /**
  48023. * Serialize the material to a parsable JSON object.
  48024. */
  48025. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48026. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48027. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48028. return serializationObject;
  48029. };
  48030. /**
  48031. * Parses a JSON object correponding to the serialize function.
  48032. */
  48033. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48034. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48035. };
  48036. __decorate([
  48037. BABYLON.serializeAsColor3("diffuse"),
  48038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48039. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48040. __decorate([
  48041. BABYLON.serializeAsTexture(),
  48042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48043. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48044. __decorate([
  48045. BABYLON.serializeAsColor3("specular"),
  48046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48047. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48048. __decorate([
  48049. BABYLON.serialize(),
  48050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48051. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48052. __decorate([
  48053. BABYLON.serializeAsTexture(),
  48054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48055. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48056. return PBRSpecularGlossinessMaterial;
  48057. }(BABYLON.PBRBaseSimpleMaterial));
  48058. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48059. })(BABYLON || (BABYLON = {}));
  48060. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48061. var BABYLON;
  48062. (function (BABYLON) {
  48063. /**
  48064. * @ignore
  48065. * This is a list of all the different input types that are available in the application.
  48066. * Fo instance: ArcRotateCameraGamepadInput...
  48067. */
  48068. BABYLON.CameraInputTypes = {};
  48069. /**
  48070. * This represents the input manager used within a camera.
  48071. * It helps dealing with all the different kind of input attached to a camera.
  48072. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48073. */
  48074. var CameraInputsManager = /** @class */ (function () {
  48075. /**
  48076. * Instantiate a new Camera Input Manager.
  48077. * @param camera Defines the camera the input manager blongs to
  48078. */
  48079. function CameraInputsManager(camera) {
  48080. this.attached = {};
  48081. this.camera = camera;
  48082. this.checkInputs = function () { };
  48083. }
  48084. /**
  48085. * Add an input method to a camera
  48086. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48087. * @param input camera input method
  48088. */
  48089. CameraInputsManager.prototype.add = function (input) {
  48090. var type = input.getSimpleName();
  48091. if (this.attached[type]) {
  48092. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48093. return;
  48094. }
  48095. this.attached[type] = input;
  48096. input.camera = this.camera;
  48097. //for checkInputs, we are dynamically creating a function
  48098. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48099. if (input.checkInputs) {
  48100. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48101. }
  48102. if (this.attachedElement) {
  48103. input.attachControl(this.attachedElement);
  48104. }
  48105. };
  48106. /**
  48107. * Remove a specific input method from a camera
  48108. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48109. * @param inputToRemove camera input method
  48110. */
  48111. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48112. for (var cam in this.attached) {
  48113. var input = this.attached[cam];
  48114. if (input === inputToRemove) {
  48115. input.detachControl(this.attachedElement);
  48116. input.camera = null;
  48117. delete this.attached[cam];
  48118. this.rebuildInputCheck();
  48119. }
  48120. }
  48121. };
  48122. /**
  48123. * Remove a specific input type from a camera
  48124. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48125. * @param inputType the type of the input to remove
  48126. */
  48127. CameraInputsManager.prototype.removeByType = function (inputType) {
  48128. for (var cam in this.attached) {
  48129. var input = this.attached[cam];
  48130. if (input.getClassName() === inputType) {
  48131. input.detachControl(this.attachedElement);
  48132. input.camera = null;
  48133. delete this.attached[cam];
  48134. this.rebuildInputCheck();
  48135. }
  48136. }
  48137. };
  48138. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48139. var current = this.checkInputs;
  48140. return function () {
  48141. current();
  48142. fn();
  48143. };
  48144. };
  48145. /**
  48146. * Attach the input controls to the currently attached dom element to listen the events from.
  48147. * @param input Defines the input to attach
  48148. */
  48149. CameraInputsManager.prototype.attachInput = function (input) {
  48150. if (this.attachedElement) {
  48151. input.attachControl(this.attachedElement, this.noPreventDefault);
  48152. }
  48153. };
  48154. /**
  48155. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48156. * @param element Defines the dom element to collect the events from
  48157. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48158. */
  48159. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48160. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48161. if (this.attachedElement) {
  48162. return;
  48163. }
  48164. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48165. this.attachedElement = element;
  48166. this.noPreventDefault = noPreventDefault;
  48167. for (var cam in this.attached) {
  48168. this.attached[cam].attachControl(element, noPreventDefault);
  48169. }
  48170. };
  48171. /**
  48172. * Detach the current manager inputs controls from a specific dom element.
  48173. * @param element Defines the dom element to collect the events from
  48174. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48175. */
  48176. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48177. if (disconnect === void 0) { disconnect = false; }
  48178. if (this.attachedElement !== element) {
  48179. return;
  48180. }
  48181. for (var cam in this.attached) {
  48182. this.attached[cam].detachControl(element);
  48183. if (disconnect) {
  48184. this.attached[cam].camera = null;
  48185. }
  48186. }
  48187. this.attachedElement = null;
  48188. };
  48189. /**
  48190. * Rebuild the dynamic inputCheck function from the current list of
  48191. * defined inputs in the manager.
  48192. */
  48193. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48194. this.checkInputs = function () { };
  48195. for (var cam in this.attached) {
  48196. var input = this.attached[cam];
  48197. if (input.checkInputs) {
  48198. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48199. }
  48200. }
  48201. };
  48202. /**
  48203. * Remove all attached input methods from a camera
  48204. */
  48205. CameraInputsManager.prototype.clear = function () {
  48206. if (this.attachedElement) {
  48207. this.detachElement(this.attachedElement, true);
  48208. }
  48209. this.attached = {};
  48210. this.attachedElement = null;
  48211. this.checkInputs = function () { };
  48212. };
  48213. /**
  48214. * Serialize the current input manager attached to a camera.
  48215. * This ensures than once parsed,
  48216. * the input associated to the camera will be identical to the current ones
  48217. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48218. */
  48219. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48220. var inputs = {};
  48221. for (var cam in this.attached) {
  48222. var input = this.attached[cam];
  48223. var res = BABYLON.SerializationHelper.Serialize(input);
  48224. inputs[input.getClassName()] = res;
  48225. }
  48226. serializedCamera.inputsmgr = inputs;
  48227. };
  48228. /**
  48229. * Parses an input manager serialized JSON to restore the previous list of inputs
  48230. * and states associated to a camera.
  48231. * @param parsedCamera Defines the JSON to parse
  48232. */
  48233. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48234. var parsedInputs = parsedCamera.inputsmgr;
  48235. if (parsedInputs) {
  48236. this.clear();
  48237. for (var n in parsedInputs) {
  48238. var construct = BABYLON.CameraInputTypes[n];
  48239. if (construct) {
  48240. var parsedinput = parsedInputs[n];
  48241. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48242. this.add(input);
  48243. }
  48244. }
  48245. }
  48246. else {
  48247. //2016-03-08 this part is for managing backward compatibility
  48248. for (var n in this.attached) {
  48249. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48250. if (construct) {
  48251. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48252. this.remove(this.attached[n]);
  48253. this.add(input);
  48254. }
  48255. }
  48256. }
  48257. };
  48258. return CameraInputsManager;
  48259. }());
  48260. BABYLON.CameraInputsManager = CameraInputsManager;
  48261. })(BABYLON || (BABYLON = {}));
  48262. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48263. var BABYLON;
  48264. (function (BABYLON) {
  48265. /**
  48266. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48267. * This is the base of the follow, arc rotate cameras and Free camera
  48268. * @see http://doc.babylonjs.com/features/cameras
  48269. */
  48270. var TargetCamera = /** @class */ (function (_super) {
  48271. __extends(TargetCamera, _super);
  48272. /**
  48273. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48274. * This is the base of the follow, arc rotate cameras and Free camera
  48275. * @see http://doc.babylonjs.com/features/cameras
  48276. * @param name Defines the name of the camera in the scene
  48277. * @param position Defines the start position of the camera in the scene
  48278. * @param scene Defines the scene the camera belongs to
  48279. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48280. */
  48281. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48282. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48283. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48284. /**
  48285. * Define the current direction the camera is moving to
  48286. */
  48287. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48288. /**
  48289. * Define the current rotation the camera is rotating to
  48290. */
  48291. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48292. /**
  48293. * Define the current rotation of the camera
  48294. */
  48295. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48296. /**
  48297. * Define the current speed of the camera
  48298. */
  48299. _this.speed = 2.0;
  48300. /**
  48301. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48302. * around all axis.
  48303. */
  48304. _this.noRotationConstraint = false;
  48305. /**
  48306. * Define the current target of the camera as an object or a position.
  48307. */
  48308. _this.lockedTarget = null;
  48309. /** @hidden */
  48310. _this._currentTarget = BABYLON.Vector3.Zero();
  48311. /** @hidden */
  48312. _this._viewMatrix = BABYLON.Matrix.Zero();
  48313. /** @hidden */
  48314. _this._camMatrix = BABYLON.Matrix.Zero();
  48315. /** @hidden */
  48316. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48317. /** @hidden */
  48318. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48319. /** @hidden */
  48320. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48321. /** @hidden */
  48322. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48323. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48324. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48325. _this._defaultUp = BABYLON.Vector3.Up();
  48326. _this._cachedRotationZ = 0;
  48327. _this._cachedQuaternionRotationZ = 0;
  48328. return _this;
  48329. }
  48330. /**
  48331. * Gets the position in front of the camera at a given distance.
  48332. * @param distance The distance from the camera we want the position to be
  48333. * @returns the position
  48334. */
  48335. TargetCamera.prototype.getFrontPosition = function (distance) {
  48336. this.getWorldMatrix();
  48337. var direction = this.getTarget().subtract(this.position);
  48338. direction.normalize();
  48339. direction.scaleInPlace(distance);
  48340. return this.globalPosition.add(direction);
  48341. };
  48342. /** @hidden */
  48343. TargetCamera.prototype._getLockedTargetPosition = function () {
  48344. if (!this.lockedTarget) {
  48345. return null;
  48346. }
  48347. if (this.lockedTarget.absolutePosition) {
  48348. this.lockedTarget.computeWorldMatrix();
  48349. }
  48350. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48351. };
  48352. /**
  48353. * Store current camera state of the camera (fov, position, rotation, etc..)
  48354. * @returns the camera
  48355. */
  48356. TargetCamera.prototype.storeState = function () {
  48357. this._storedPosition = this.position.clone();
  48358. this._storedRotation = this.rotation.clone();
  48359. if (this.rotationQuaternion) {
  48360. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48361. }
  48362. return _super.prototype.storeState.call(this);
  48363. };
  48364. /**
  48365. * Restored camera state. You must call storeState() first
  48366. * @returns whether it was successful or not
  48367. * @hidden
  48368. */
  48369. TargetCamera.prototype._restoreStateValues = function () {
  48370. if (!_super.prototype._restoreStateValues.call(this)) {
  48371. return false;
  48372. }
  48373. this.position = this._storedPosition.clone();
  48374. this.rotation = this._storedRotation.clone();
  48375. if (this.rotationQuaternion) {
  48376. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48377. }
  48378. this.cameraDirection.copyFromFloats(0, 0, 0);
  48379. this.cameraRotation.copyFromFloats(0, 0);
  48380. return true;
  48381. };
  48382. /** @hidden */
  48383. TargetCamera.prototype._initCache = function () {
  48384. _super.prototype._initCache.call(this);
  48385. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48386. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48387. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48388. };
  48389. /** @hidden */
  48390. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48391. if (!ignoreParentClass) {
  48392. _super.prototype._updateCache.call(this);
  48393. }
  48394. var lockedTargetPosition = this._getLockedTargetPosition();
  48395. if (!lockedTargetPosition) {
  48396. this._cache.lockedTarget = null;
  48397. }
  48398. else {
  48399. if (!this._cache.lockedTarget) {
  48400. this._cache.lockedTarget = lockedTargetPosition.clone();
  48401. }
  48402. else {
  48403. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48404. }
  48405. }
  48406. this._cache.rotation.copyFrom(this.rotation);
  48407. if (this.rotationQuaternion) {
  48408. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48409. }
  48410. };
  48411. // Synchronized
  48412. /** @hidden */
  48413. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48414. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48415. return false;
  48416. }
  48417. var lockedTargetPosition = this._getLockedTargetPosition();
  48418. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48419. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48420. };
  48421. // Methods
  48422. /** @hidden */
  48423. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48424. var engine = this.getEngine();
  48425. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48426. };
  48427. // Target
  48428. /** @hidden */
  48429. TargetCamera.prototype.setTarget = function (target) {
  48430. this.upVector.normalize();
  48431. if (this.position.z === target.z) {
  48432. this.position.z += BABYLON.Epsilon;
  48433. }
  48434. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48435. this._camMatrix.invert();
  48436. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48437. var vDir = target.subtract(this.position);
  48438. if (vDir.x >= 0.0) {
  48439. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48440. }
  48441. else {
  48442. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48443. }
  48444. this.rotation.z = 0;
  48445. if (isNaN(this.rotation.x)) {
  48446. this.rotation.x = 0;
  48447. }
  48448. if (isNaN(this.rotation.y)) {
  48449. this.rotation.y = 0;
  48450. }
  48451. if (isNaN(this.rotation.z)) {
  48452. this.rotation.z = 0;
  48453. }
  48454. if (this.rotationQuaternion) {
  48455. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48456. }
  48457. };
  48458. /**
  48459. * Return the current target position of the camera. This value is expressed in local space.
  48460. * @returns the target position
  48461. */
  48462. TargetCamera.prototype.getTarget = function () {
  48463. return this._currentTarget;
  48464. };
  48465. /** @hidden */
  48466. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48467. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48468. };
  48469. /** @hidden */
  48470. TargetCamera.prototype._updatePosition = function () {
  48471. if (this.parent) {
  48472. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48473. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48474. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48475. return;
  48476. }
  48477. this.position.addInPlace(this.cameraDirection);
  48478. };
  48479. /** @hidden */
  48480. TargetCamera.prototype._checkInputs = function () {
  48481. var needToMove = this._decideIfNeedsToMove();
  48482. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48483. // Move
  48484. if (needToMove) {
  48485. this._updatePosition();
  48486. }
  48487. // Rotate
  48488. if (needToRotate) {
  48489. this.rotation.x += this.cameraRotation.x;
  48490. this.rotation.y += this.cameraRotation.y;
  48491. //rotate, if quaternion is set and rotation was used
  48492. if (this.rotationQuaternion) {
  48493. var len = this.rotation.lengthSquared();
  48494. if (len) {
  48495. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48496. }
  48497. }
  48498. if (!this.noRotationConstraint) {
  48499. var limit = (Math.PI / 2) * 0.95;
  48500. if (this.rotation.x > limit) {
  48501. this.rotation.x = limit;
  48502. }
  48503. if (this.rotation.x < -limit) {
  48504. this.rotation.x = -limit;
  48505. }
  48506. }
  48507. }
  48508. // Inertia
  48509. if (needToMove) {
  48510. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48511. this.cameraDirection.x = 0;
  48512. }
  48513. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48514. this.cameraDirection.y = 0;
  48515. }
  48516. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48517. this.cameraDirection.z = 0;
  48518. }
  48519. this.cameraDirection.scaleInPlace(this.inertia);
  48520. }
  48521. if (needToRotate) {
  48522. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48523. this.cameraRotation.x = 0;
  48524. }
  48525. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48526. this.cameraRotation.y = 0;
  48527. }
  48528. this.cameraRotation.scaleInPlace(this.inertia);
  48529. }
  48530. _super.prototype._checkInputs.call(this);
  48531. };
  48532. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48533. if (this.rotationQuaternion) {
  48534. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48535. }
  48536. else {
  48537. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48538. }
  48539. };
  48540. /**
  48541. * 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)
  48542. * @returns the current camera
  48543. */
  48544. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48545. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48546. return this;
  48547. };
  48548. /** @hidden */
  48549. TargetCamera.prototype._getViewMatrix = function () {
  48550. if (this.lockedTarget) {
  48551. this.setTarget(this._getLockedTargetPosition());
  48552. }
  48553. // Compute
  48554. this._updateCameraRotationMatrix();
  48555. // Apply the changed rotation to the upVector
  48556. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48557. this._rotateUpVectorWithCameraRotationMatrix();
  48558. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48559. }
  48560. else if (this._cachedRotationZ != this.rotation.z) {
  48561. this._rotateUpVectorWithCameraRotationMatrix();
  48562. this._cachedRotationZ = this.rotation.z;
  48563. }
  48564. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48565. // Computing target and final matrix
  48566. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48567. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48568. return this._viewMatrix;
  48569. };
  48570. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48571. if (this.parent) {
  48572. var parentWorldMatrix = this.parent.getWorldMatrix();
  48573. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48574. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48575. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48576. this._markSyncedWithParent();
  48577. }
  48578. else {
  48579. this._globalPosition.copyFrom(position);
  48580. this._globalCurrentTarget.copyFrom(target);
  48581. this._globalCurrentUpVector.copyFrom(up);
  48582. }
  48583. if (this.getScene().useRightHandedSystem) {
  48584. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48585. }
  48586. else {
  48587. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48588. }
  48589. };
  48590. /**
  48591. * @hidden
  48592. */
  48593. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48594. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48595. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48596. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48597. if (!this.rotationQuaternion) {
  48598. this.rotationQuaternion = new BABYLON.Quaternion();
  48599. }
  48600. rigCamera._cameraRigParams = {};
  48601. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48602. }
  48603. return rigCamera;
  48604. }
  48605. return null;
  48606. };
  48607. /**
  48608. * @hidden
  48609. */
  48610. TargetCamera.prototype._updateRigCameras = function () {
  48611. var camLeft = this._rigCameras[0];
  48612. var camRight = this._rigCameras[1];
  48613. switch (this.cameraRigMode) {
  48614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48616. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48617. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48618. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48619. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48620. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48621. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48622. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48623. camLeft.setTarget(this.getTarget());
  48624. camRight.setTarget(this.getTarget());
  48625. break;
  48626. case BABYLON.Camera.RIG_MODE_VR:
  48627. if (camLeft.rotationQuaternion) {
  48628. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48629. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48630. }
  48631. else {
  48632. camLeft.rotation.copyFrom(this.rotation);
  48633. camRight.rotation.copyFrom(this.rotation);
  48634. }
  48635. camLeft.position.copyFrom(this.position);
  48636. camRight.position.copyFrom(this.position);
  48637. break;
  48638. }
  48639. _super.prototype._updateRigCameras.call(this);
  48640. };
  48641. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48642. if (!this._rigCamTransformMatrix) {
  48643. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48644. }
  48645. var target = this.getTarget();
  48646. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48647. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48649. };
  48650. /**
  48651. * Gets the current object class name.
  48652. * @return the class name
  48653. */
  48654. TargetCamera.prototype.getClassName = function () {
  48655. return "TargetCamera";
  48656. };
  48657. __decorate([
  48658. BABYLON.serializeAsVector3()
  48659. ], TargetCamera.prototype, "rotation", void 0);
  48660. __decorate([
  48661. BABYLON.serialize()
  48662. ], TargetCamera.prototype, "speed", void 0);
  48663. __decorate([
  48664. BABYLON.serializeAsMeshReference("lockedTargetId")
  48665. ], TargetCamera.prototype, "lockedTarget", void 0);
  48666. return TargetCamera;
  48667. }(BABYLON.Camera));
  48668. BABYLON.TargetCamera = TargetCamera;
  48669. })(BABYLON || (BABYLON = {}));
  48670. //# sourceMappingURL=babylon.targetCamera.js.map
  48671. var BABYLON;
  48672. (function (BABYLON) {
  48673. /**
  48674. * Manage the mouse inputs to control the movement of a free camera.
  48675. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48676. */
  48677. var FreeCameraMouseInput = /** @class */ (function () {
  48678. /**
  48679. * Manage the mouse inputs to control the movement of a free camera.
  48680. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48681. * @param touchEnabled Defines if touch is enabled or not
  48682. */
  48683. function FreeCameraMouseInput(
  48684. /**
  48685. * Define if touch is enabled in the mouse input
  48686. */
  48687. touchEnabled) {
  48688. if (touchEnabled === void 0) { touchEnabled = true; }
  48689. this.touchEnabled = touchEnabled;
  48690. /**
  48691. * Defines the buttons associated with the input to handle camera move.
  48692. */
  48693. this.buttons = [0, 1, 2];
  48694. /**
  48695. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48696. */
  48697. this.angularSensibility = 2000.0;
  48698. this.previousPosition = null;
  48699. }
  48700. /**
  48701. * Attach the input controls to a specific dom element to get the input from.
  48702. * @param element Defines the element the controls should be listened from
  48703. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48704. */
  48705. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48706. var _this = this;
  48707. var engine = this.camera.getEngine();
  48708. if (!this._pointerInput) {
  48709. this._pointerInput = function (p, s) {
  48710. var evt = p.event;
  48711. if (engine.isInVRExclusivePointerMode) {
  48712. return;
  48713. }
  48714. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48715. return;
  48716. }
  48717. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48718. return;
  48719. }
  48720. var srcElement = (evt.srcElement || evt.target);
  48721. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48722. try {
  48723. srcElement.setPointerCapture(evt.pointerId);
  48724. }
  48725. catch (e) {
  48726. //Nothing to do with the error. Execution will continue.
  48727. }
  48728. _this.previousPosition = {
  48729. x: evt.clientX,
  48730. y: evt.clientY
  48731. };
  48732. if (!noPreventDefault) {
  48733. evt.preventDefault();
  48734. element.focus();
  48735. }
  48736. }
  48737. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48738. try {
  48739. srcElement.releasePointerCapture(evt.pointerId);
  48740. }
  48741. catch (e) {
  48742. //Nothing to do with the error.
  48743. }
  48744. _this.previousPosition = null;
  48745. if (!noPreventDefault) {
  48746. evt.preventDefault();
  48747. }
  48748. }
  48749. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48750. if (!_this.previousPosition || engine.isPointerLock) {
  48751. return;
  48752. }
  48753. var offsetX = evt.clientX - _this.previousPosition.x;
  48754. if (_this.camera.getScene().useRightHandedSystem) {
  48755. offsetX *= -1;
  48756. }
  48757. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48758. offsetX *= -1;
  48759. }
  48760. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48761. var offsetY = evt.clientY - _this.previousPosition.y;
  48762. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48763. _this.previousPosition = {
  48764. x: evt.clientX,
  48765. y: evt.clientY
  48766. };
  48767. if (!noPreventDefault) {
  48768. evt.preventDefault();
  48769. }
  48770. }
  48771. };
  48772. }
  48773. this._onMouseMove = function (evt) {
  48774. if (!engine.isPointerLock) {
  48775. return;
  48776. }
  48777. if (engine.isInVRExclusivePointerMode) {
  48778. return;
  48779. }
  48780. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48781. if (_this.camera.getScene().useRightHandedSystem) {
  48782. offsetX *= -1;
  48783. }
  48784. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48785. offsetX *= -1;
  48786. }
  48787. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48788. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48789. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48790. _this.previousPosition = null;
  48791. if (!noPreventDefault) {
  48792. evt.preventDefault();
  48793. }
  48794. };
  48795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48796. element.addEventListener("mousemove", this._onMouseMove, false);
  48797. };
  48798. /**
  48799. * Detach the current controls from the specified dom element.
  48800. * @param element Defines the element to stop listening the inputs from
  48801. */
  48802. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48803. if (this._observer && element) {
  48804. this.camera.getScene().onPointerObservable.remove(this._observer);
  48805. if (this._onMouseMove) {
  48806. element.removeEventListener("mousemove", this._onMouseMove);
  48807. }
  48808. this._observer = null;
  48809. this._onMouseMove = null;
  48810. this.previousPosition = null;
  48811. }
  48812. };
  48813. /**
  48814. * Gets the class name of the current intput.
  48815. * @returns the class name
  48816. */
  48817. FreeCameraMouseInput.prototype.getClassName = function () {
  48818. return "FreeCameraMouseInput";
  48819. };
  48820. /**
  48821. * Get the friendly name associated with the input class.
  48822. * @returns the input friendly name
  48823. */
  48824. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48825. return "mouse";
  48826. };
  48827. __decorate([
  48828. BABYLON.serialize()
  48829. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48830. __decorate([
  48831. BABYLON.serialize()
  48832. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48833. return FreeCameraMouseInput;
  48834. }());
  48835. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48836. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48837. })(BABYLON || (BABYLON = {}));
  48838. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48839. var BABYLON;
  48840. (function (BABYLON) {
  48841. /**
  48842. * Manage the keyboard inputs to control the movement of a free camera.
  48843. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48844. */
  48845. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48846. function FreeCameraKeyboardMoveInput() {
  48847. /**
  48848. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48849. */
  48850. this.keysUp = [38];
  48851. /**
  48852. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48853. */
  48854. this.keysDown = [40];
  48855. /**
  48856. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48857. */
  48858. this.keysLeft = [37];
  48859. /**
  48860. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48861. */
  48862. this.keysRight = [39];
  48863. this._keys = new Array();
  48864. }
  48865. /**
  48866. * Attach the input controls to a specific dom element to get the input from.
  48867. * @param element Defines the element the controls should be listened from
  48868. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48869. */
  48870. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48871. var _this = this;
  48872. if (this._onCanvasBlurObserver) {
  48873. return;
  48874. }
  48875. this._scene = this.camera.getScene();
  48876. this._engine = this._scene.getEngine();
  48877. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48878. _this._keys = [];
  48879. });
  48880. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48881. var evt = info.event;
  48882. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48883. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48884. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48885. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48886. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48887. var index = _this._keys.indexOf(evt.keyCode);
  48888. if (index === -1) {
  48889. _this._keys.push(evt.keyCode);
  48890. }
  48891. if (!noPreventDefault) {
  48892. evt.preventDefault();
  48893. }
  48894. }
  48895. }
  48896. else {
  48897. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48898. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48899. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48900. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48901. var index = _this._keys.indexOf(evt.keyCode);
  48902. if (index >= 0) {
  48903. _this._keys.splice(index, 1);
  48904. }
  48905. if (!noPreventDefault) {
  48906. evt.preventDefault();
  48907. }
  48908. }
  48909. }
  48910. });
  48911. };
  48912. /**
  48913. * Detach the current controls from the specified dom element.
  48914. * @param element Defines the element to stop listening the inputs from
  48915. */
  48916. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48917. if (this._scene) {
  48918. if (this._onKeyboardObserver) {
  48919. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48920. }
  48921. if (this._onCanvasBlurObserver) {
  48922. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48923. }
  48924. this._onKeyboardObserver = null;
  48925. this._onCanvasBlurObserver = null;
  48926. }
  48927. this._keys = [];
  48928. };
  48929. /**
  48930. * Update the current camera state depending on the inputs that have been used this frame.
  48931. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48932. */
  48933. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48934. if (this._onKeyboardObserver) {
  48935. var camera = this.camera;
  48936. // Keyboard
  48937. for (var index = 0; index < this._keys.length; index++) {
  48938. var keyCode = this._keys[index];
  48939. var speed = camera._computeLocalCameraSpeed();
  48940. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48941. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48942. }
  48943. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48944. camera._localDirection.copyFromFloats(0, 0, speed);
  48945. }
  48946. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48947. camera._localDirection.copyFromFloats(speed, 0, 0);
  48948. }
  48949. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48950. camera._localDirection.copyFromFloats(0, 0, -speed);
  48951. }
  48952. if (camera.getScene().useRightHandedSystem) {
  48953. camera._localDirection.z *= -1;
  48954. }
  48955. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48956. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48957. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48958. }
  48959. }
  48960. };
  48961. /**
  48962. * Gets the class name of the current intput.
  48963. * @returns the class name
  48964. */
  48965. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48966. return "FreeCameraKeyboardMoveInput";
  48967. };
  48968. /** @hidden */
  48969. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48970. this._keys = [];
  48971. };
  48972. /**
  48973. * Get the friendly name associated with the input class.
  48974. * @returns the input friendly name
  48975. */
  48976. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48977. return "keyboard";
  48978. };
  48979. __decorate([
  48980. BABYLON.serialize()
  48981. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48982. __decorate([
  48983. BABYLON.serialize()
  48984. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48985. __decorate([
  48986. BABYLON.serialize()
  48987. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48988. __decorate([
  48989. BABYLON.serialize()
  48990. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48991. return FreeCameraKeyboardMoveInput;
  48992. }());
  48993. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48994. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48995. })(BABYLON || (BABYLON = {}));
  48996. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48997. var BABYLON;
  48998. (function (BABYLON) {
  48999. /**
  49000. * Default Inputs manager for the FreeCamera.
  49001. * It groups all the default supported inputs for ease of use.
  49002. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49003. */
  49004. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49005. __extends(FreeCameraInputsManager, _super);
  49006. /**
  49007. * Instantiates a new FreeCameraInputsManager.
  49008. * @param camera Defines the camera the inputs belong to
  49009. */
  49010. function FreeCameraInputsManager(camera) {
  49011. return _super.call(this, camera) || this;
  49012. }
  49013. /**
  49014. * Add keyboard input support to the input manager.
  49015. * @returns the current input manager
  49016. */
  49017. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49018. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49019. return this;
  49020. };
  49021. /**
  49022. * Add mouse input support to the input manager.
  49023. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49024. * @returns the current input manager
  49025. */
  49026. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49027. if (touchEnabled === void 0) { touchEnabled = true; }
  49028. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49029. return this;
  49030. };
  49031. /**
  49032. * Add orientation input support to the input manager.
  49033. * @returns the current input manager
  49034. */
  49035. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49036. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49037. return this;
  49038. };
  49039. /**
  49040. * Add touch input support to the input manager.
  49041. * @returns the current input manager
  49042. */
  49043. FreeCameraInputsManager.prototype.addTouch = function () {
  49044. this.add(new BABYLON.FreeCameraTouchInput());
  49045. return this;
  49046. };
  49047. /**
  49048. * Add virtual joystick input support to the input manager.
  49049. * @returns the current input manager
  49050. */
  49051. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49052. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49053. return this;
  49054. };
  49055. return FreeCameraInputsManager;
  49056. }(BABYLON.CameraInputsManager));
  49057. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49058. })(BABYLON || (BABYLON = {}));
  49059. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49060. var BABYLON;
  49061. (function (BABYLON) {
  49062. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49063. // Forcing to use the Universal camera
  49064. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49065. });
  49066. /**
  49067. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49068. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49069. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49070. */
  49071. var FreeCamera = /** @class */ (function (_super) {
  49072. __extends(FreeCamera, _super);
  49073. /**
  49074. * Instantiates a Free Camera.
  49075. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49076. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49077. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49078. * @param name Define the name of the camera in the scene
  49079. * @param position Define the start position of the camera in the scene
  49080. * @param scene Define the scene the camera belongs to
  49081. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49082. */
  49083. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49084. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49085. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49086. /**
  49087. * Define the collision ellipsoid of the camera.
  49088. * This is helpful to simulate a camera body like the player body around the camera
  49089. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49090. */
  49091. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49092. /**
  49093. * Define an offset for the position of the ellipsoid around the camera.
  49094. * This can be helpful to determine the center of the body near the gravity center of the body
  49095. * instead of its head.
  49096. */
  49097. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49098. /**
  49099. * Enable or disable collisions of the camera with the rest of the scene objects.
  49100. */
  49101. _this.checkCollisions = false;
  49102. /**
  49103. * Enable or disable gravity on the camera.
  49104. */
  49105. _this.applyGravity = false;
  49106. _this._needMoveForGravity = false;
  49107. _this._oldPosition = BABYLON.Vector3.Zero();
  49108. _this._diffPosition = BABYLON.Vector3.Zero();
  49109. _this._newPosition = BABYLON.Vector3.Zero();
  49110. // Collisions
  49111. _this._collisionMask = -1;
  49112. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49113. if (collidedMesh === void 0) { collidedMesh = null; }
  49114. //TODO move this to the collision coordinator!
  49115. if (_this.getScene().workerCollisions) {
  49116. newPosition.multiplyInPlace(_this._collider._radius);
  49117. }
  49118. var updatePosition = function (newPos) {
  49119. _this._newPosition.copyFrom(newPos);
  49120. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49121. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49122. _this.position.addInPlace(_this._diffPosition);
  49123. if (_this.onCollide && collidedMesh) {
  49124. _this.onCollide(collidedMesh);
  49125. }
  49126. }
  49127. };
  49128. updatePosition(newPosition);
  49129. };
  49130. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49131. _this.inputs.addKeyboard().addMouse();
  49132. return _this;
  49133. }
  49134. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49135. /**
  49136. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49137. * Higher values reduce sensitivity.
  49138. */
  49139. get: function () {
  49140. var mouse = this.inputs.attached["mouse"];
  49141. if (mouse) {
  49142. return mouse.angularSensibility;
  49143. }
  49144. return 0;
  49145. },
  49146. /**
  49147. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49148. * Higher values reduce sensitivity.
  49149. */
  49150. set: function (value) {
  49151. var mouse = this.inputs.attached["mouse"];
  49152. if (mouse) {
  49153. mouse.angularSensibility = value;
  49154. }
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49160. /**
  49161. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49162. */
  49163. get: function () {
  49164. var keyboard = this.inputs.attached["keyboard"];
  49165. if (keyboard) {
  49166. return keyboard.keysUp;
  49167. }
  49168. return [];
  49169. },
  49170. set: function (value) {
  49171. var keyboard = this.inputs.attached["keyboard"];
  49172. if (keyboard) {
  49173. keyboard.keysUp = value;
  49174. }
  49175. },
  49176. enumerable: true,
  49177. configurable: true
  49178. });
  49179. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49180. /**
  49181. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49182. */
  49183. get: function () {
  49184. var keyboard = this.inputs.attached["keyboard"];
  49185. if (keyboard) {
  49186. return keyboard.keysDown;
  49187. }
  49188. return [];
  49189. },
  49190. set: function (value) {
  49191. var keyboard = this.inputs.attached["keyboard"];
  49192. if (keyboard) {
  49193. keyboard.keysDown = value;
  49194. }
  49195. },
  49196. enumerable: true,
  49197. configurable: true
  49198. });
  49199. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49200. /**
  49201. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49202. */
  49203. get: function () {
  49204. var keyboard = this.inputs.attached["keyboard"];
  49205. if (keyboard) {
  49206. return keyboard.keysLeft;
  49207. }
  49208. return [];
  49209. },
  49210. set: function (value) {
  49211. var keyboard = this.inputs.attached["keyboard"];
  49212. if (keyboard) {
  49213. keyboard.keysLeft = value;
  49214. }
  49215. },
  49216. enumerable: true,
  49217. configurable: true
  49218. });
  49219. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49220. /**
  49221. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49222. */
  49223. get: function () {
  49224. var keyboard = this.inputs.attached["keyboard"];
  49225. if (keyboard) {
  49226. return keyboard.keysRight;
  49227. }
  49228. return [];
  49229. },
  49230. set: function (value) {
  49231. var keyboard = this.inputs.attached["keyboard"];
  49232. if (keyboard) {
  49233. keyboard.keysRight = value;
  49234. }
  49235. },
  49236. enumerable: true,
  49237. configurable: true
  49238. });
  49239. /**
  49240. * Attached controls to the current camera.
  49241. * @param element Defines the element the controls should be listened from
  49242. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49243. */
  49244. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49245. this.inputs.attachElement(element, noPreventDefault);
  49246. };
  49247. /**
  49248. * Detach the current controls from the camera.
  49249. * The camera will stop reacting to inputs.
  49250. * @param element Defines the element to stop listening the inputs from
  49251. */
  49252. FreeCamera.prototype.detachControl = function (element) {
  49253. this.inputs.detachElement(element);
  49254. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49255. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49256. };
  49257. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49258. /**
  49259. * Define a collision mask to limit the list of object the camera can collide with
  49260. */
  49261. get: function () {
  49262. return this._collisionMask;
  49263. },
  49264. set: function (mask) {
  49265. this._collisionMask = !isNaN(mask) ? mask : -1;
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. /** @hidden */
  49271. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49272. var globalPosition;
  49273. if (this.parent) {
  49274. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49275. }
  49276. else {
  49277. globalPosition = this.position;
  49278. }
  49279. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49280. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49281. if (!this._collider) {
  49282. this._collider = new BABYLON.Collider();
  49283. }
  49284. this._collider._radius = this.ellipsoid;
  49285. this._collider.collisionMask = this._collisionMask;
  49286. //no need for clone, as long as gravity is not on.
  49287. var actualDisplacement = displacement;
  49288. //add gravity to the direction to prevent the dual-collision checking
  49289. if (this.applyGravity) {
  49290. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49291. actualDisplacement = displacement.add(this.getScene().gravity);
  49292. }
  49293. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49294. };
  49295. /** @hidden */
  49296. FreeCamera.prototype._checkInputs = function () {
  49297. if (!this._localDirection) {
  49298. this._localDirection = BABYLON.Vector3.Zero();
  49299. this._transformedDirection = BABYLON.Vector3.Zero();
  49300. }
  49301. this.inputs.checkInputs();
  49302. _super.prototype._checkInputs.call(this);
  49303. };
  49304. /** @hidden */
  49305. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49306. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49307. };
  49308. /** @hidden */
  49309. FreeCamera.prototype._updatePosition = function () {
  49310. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49311. this._collideWithWorld(this.cameraDirection);
  49312. }
  49313. else {
  49314. _super.prototype._updatePosition.call(this);
  49315. }
  49316. };
  49317. /**
  49318. * Destroy the camera and release the current resources hold by it.
  49319. */
  49320. FreeCamera.prototype.dispose = function () {
  49321. this.inputs.clear();
  49322. _super.prototype.dispose.call(this);
  49323. };
  49324. /**
  49325. * Gets the current object class name.
  49326. * @return the class name
  49327. */
  49328. FreeCamera.prototype.getClassName = function () {
  49329. return "FreeCamera";
  49330. };
  49331. __decorate([
  49332. BABYLON.serializeAsVector3()
  49333. ], FreeCamera.prototype, "ellipsoid", void 0);
  49334. __decorate([
  49335. BABYLON.serializeAsVector3()
  49336. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], FreeCamera.prototype, "checkCollisions", void 0);
  49340. __decorate([
  49341. BABYLON.serialize()
  49342. ], FreeCamera.prototype, "applyGravity", void 0);
  49343. return FreeCamera;
  49344. }(BABYLON.TargetCamera));
  49345. BABYLON.FreeCamera = FreeCamera;
  49346. })(BABYLON || (BABYLON = {}));
  49347. //# sourceMappingURL=babylon.freeCamera.js.map
  49348. var BABYLON;
  49349. (function (BABYLON) {
  49350. /**
  49351. * Listen to mouse events to control the camera.
  49352. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49353. */
  49354. var FlyCameraMouseInput = /** @class */ (function () {
  49355. /**
  49356. * Listen to mouse events to control the camera.
  49357. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49358. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49359. */
  49360. function FlyCameraMouseInput(touchEnabled) {
  49361. if (touchEnabled === void 0) { touchEnabled = true; }
  49362. /**
  49363. * Defines the buttons associated with the input to handle camera rotation.
  49364. */
  49365. this.buttons = [0, 1, 2];
  49366. /**
  49367. * Assign buttons for Yaw control.
  49368. */
  49369. this.buttonsYaw = [-1, 0, 1];
  49370. /**
  49371. * Assign buttons for Pitch control.
  49372. */
  49373. this.buttonsPitch = [-1, 0, 1];
  49374. /**
  49375. * Assign buttons for Roll control.
  49376. */
  49377. this.buttonsRoll = [2];
  49378. /**
  49379. * Detect if any button is being pressed while mouse is moved.
  49380. * -1 = Mouse locked.
  49381. * 0 = Left button.
  49382. * 1 = Middle Button.
  49383. * 2 = Right Button.
  49384. */
  49385. this.activeButton = -1;
  49386. /**
  49387. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49388. * Higher values reduce its sensitivity.
  49389. */
  49390. this.angularSensibility = 1000.0;
  49391. this.previousPosition = null;
  49392. }
  49393. /**
  49394. * Attach the mouse control to the HTML DOM element.
  49395. * @param element Defines the element that listens to the input events.
  49396. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49397. */
  49398. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49399. var _this = this;
  49400. this.element = element;
  49401. this.noPreventDefault = noPreventDefault;
  49402. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49403. _this._pointerInput(p, s);
  49404. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49405. // Correct Roll by rate, if enabled.
  49406. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49407. if (_this.camera.rollCorrect) {
  49408. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49409. }
  49410. });
  49411. // Helper function to keep 'this'.
  49412. this._mousemoveCallback = function (e) {
  49413. _this._onMouseMove(e);
  49414. };
  49415. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49416. };
  49417. /**
  49418. * Detach the current controls from the specified dom element.
  49419. * @param element Defines the element to stop listening the inputs from
  49420. */
  49421. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49422. if (this._observer && element) {
  49423. this.camera.getScene().onPointerObservable.remove(this._observer);
  49424. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49425. if (this._mousemoveCallback) {
  49426. element.removeEventListener("mousemove", this._mousemoveCallback);
  49427. }
  49428. this._observer = null;
  49429. this._rollObserver = null;
  49430. this.previousPosition = null;
  49431. this.noPreventDefault = undefined;
  49432. }
  49433. };
  49434. /**
  49435. * Gets the class name of the current input.
  49436. * @returns the class name.
  49437. */
  49438. FlyCameraMouseInput.prototype.getClassName = function () {
  49439. return "FlyCameraMouseInput";
  49440. };
  49441. /**
  49442. * Get the friendly name associated with the input class.
  49443. * @returns the input's friendly name.
  49444. */
  49445. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49446. return "mouse";
  49447. };
  49448. // Track mouse movement, when the pointer is not locked.
  49449. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49450. var e = p.event;
  49451. var camera = this.camera;
  49452. var engine = camera.getEngine();
  49453. if (engine.isInVRExclusivePointerMode) {
  49454. return;
  49455. }
  49456. if (!this.touchEnabled && e.pointerType === "touch") {
  49457. return;
  49458. }
  49459. // Mouse is moved but an unknown mouse button is pressed.
  49460. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49461. return;
  49462. }
  49463. var srcElement = (e.srcElement || e.target);
  49464. // Mouse down.
  49465. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49466. try {
  49467. srcElement.setPointerCapture(e.pointerId);
  49468. }
  49469. catch (e) {
  49470. // Nothing to do with the error. Execution continues.
  49471. }
  49472. this.previousPosition = {
  49473. x: e.clientX,
  49474. y: e.clientY
  49475. };
  49476. this.activeButton = e.button;
  49477. if (!this.noPreventDefault) {
  49478. e.preventDefault();
  49479. this.element.focus();
  49480. }
  49481. }
  49482. else
  49483. // Mouse up.
  49484. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49485. try {
  49486. srcElement.releasePointerCapture(e.pointerId);
  49487. }
  49488. catch (e) {
  49489. // Nothing to do with the error. Execution continues.
  49490. }
  49491. this.activeButton = -1;
  49492. this.previousPosition = null;
  49493. if (!this.noPreventDefault) {
  49494. e.preventDefault();
  49495. }
  49496. }
  49497. else
  49498. // Mouse move.
  49499. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49500. if (!this.previousPosition || engine.isPointerLock) {
  49501. return;
  49502. }
  49503. var offsetX = e.clientX - this.previousPosition.x;
  49504. var offsetY = e.clientY - this.previousPosition.y;
  49505. this.rotateCamera(offsetX, offsetY);
  49506. this.previousPosition = {
  49507. x: e.clientX,
  49508. y: e.clientY
  49509. };
  49510. if (!this.noPreventDefault) {
  49511. e.preventDefault();
  49512. }
  49513. }
  49514. };
  49515. // Track mouse movement, when pointer is locked.
  49516. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49517. var camera = this.camera;
  49518. var engine = camera.getEngine();
  49519. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49520. return;
  49521. }
  49522. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49523. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49524. this.rotateCamera(offsetX, offsetY);
  49525. this.previousPosition = null;
  49526. if (!this.noPreventDefault) {
  49527. e.preventDefault();
  49528. }
  49529. };
  49530. /**
  49531. * Rotate camera by mouse offset.
  49532. */
  49533. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49534. var _this = this;
  49535. var camera = this.camera;
  49536. var scene = this.camera.getScene();
  49537. if (scene.useRightHandedSystem) {
  49538. offsetX *= -1;
  49539. }
  49540. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49541. offsetX *= -1;
  49542. }
  49543. var x = offsetX / this.angularSensibility;
  49544. var y = offsetY / this.angularSensibility;
  49545. // Initialize to current rotation.
  49546. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49547. var rotationChange;
  49548. // Pitch.
  49549. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49550. // Apply change in Radians to vector Angle.
  49551. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49552. // Apply Pitch to quaternion.
  49553. currentRotation.multiplyInPlace(rotationChange);
  49554. }
  49555. // Yaw.
  49556. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49557. // Apply change in Radians to vector Angle.
  49558. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49559. // Apply Yaw to quaternion.
  49560. currentRotation.multiplyInPlace(rotationChange);
  49561. // Add Roll, if banked turning is enabled, within Roll limit.
  49562. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49563. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49564. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49565. // Apply change in Radians to vector Angle.
  49566. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49567. // Apply Yaw to quaternion.
  49568. currentRotation.multiplyInPlace(rotationChange);
  49569. }
  49570. }
  49571. // Roll.
  49572. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  49573. // Apply change in Radians to vector Angle.
  49574. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  49575. // Track Rolling.
  49576. camera._trackRoll -= x;
  49577. // Apply Pitch to quaternion.
  49578. currentRotation.multiplyInPlace(rotationChange);
  49579. }
  49580. // Apply rotationQuaternion to Euler camera.rotation.
  49581. currentRotation.toEulerAnglesToRef(camera.rotation);
  49582. };
  49583. __decorate([
  49584. BABYLON.serialize()
  49585. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  49586. __decorate([
  49587. BABYLON.serialize()
  49588. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  49589. return FlyCameraMouseInput;
  49590. }());
  49591. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  49592. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  49593. })(BABYLON || (BABYLON = {}));
  49594. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  49595. var BABYLON;
  49596. (function (BABYLON) {
  49597. /**
  49598. * Listen to keyboard events to control the camera.
  49599. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49600. */
  49601. var FlyCameraKeyboardInput = /** @class */ (function () {
  49602. function FlyCameraKeyboardInput() {
  49603. /**
  49604. * The list of keyboard keys used to control the forward move of the camera.
  49605. */
  49606. this.keysForward = [87];
  49607. /**
  49608. * The list of keyboard keys used to control the backward move of the camera.
  49609. */
  49610. this.keysBackward = [83];
  49611. /**
  49612. * The list of keyboard keys used to control the forward move of the camera.
  49613. */
  49614. this.keysUp = [69];
  49615. /**
  49616. * The list of keyboard keys used to control the backward move of the camera.
  49617. */
  49618. this.keysDown = [81];
  49619. /**
  49620. * The list of keyboard keys used to control the right strafe move of the camera.
  49621. */
  49622. this.keysRight = [68];
  49623. /**
  49624. * The list of keyboard keys used to control the left strafe move of the camera.
  49625. */
  49626. this.keysLeft = [65];
  49627. this._keys = new Array();
  49628. }
  49629. /**
  49630. * Attach the input controls to a specific dom element to get the input from.
  49631. * @param element Defines the element the controls should be listened from
  49632. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49633. */
  49634. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  49635. var _this = this;
  49636. if (this._onCanvasBlurObserver) {
  49637. return;
  49638. }
  49639. this._scene = this.camera.getScene();
  49640. this._engine = this._scene.getEngine();
  49641. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49642. _this._keys = [];
  49643. });
  49644. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49645. var evt = info.event;
  49646. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49647. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49648. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49649. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49650. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49651. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49652. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49653. var index = _this._keys.indexOf(evt.keyCode);
  49654. if (index === -1) {
  49655. _this._keys.push(evt.keyCode);
  49656. }
  49657. if (!noPreventDefault) {
  49658. evt.preventDefault();
  49659. }
  49660. }
  49661. }
  49662. else {
  49663. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49664. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49665. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49668. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49669. var index = _this._keys.indexOf(evt.keyCode);
  49670. if (index >= 0) {
  49671. _this._keys.splice(index, 1);
  49672. }
  49673. if (!noPreventDefault) {
  49674. evt.preventDefault();
  49675. }
  49676. }
  49677. }
  49678. });
  49679. };
  49680. /**
  49681. * Detach the current controls from the specified dom element.
  49682. * @param element Defines the element to stop listening the inputs from
  49683. */
  49684. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  49685. if (this._scene) {
  49686. if (this._onKeyboardObserver) {
  49687. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49688. }
  49689. if (this._onCanvasBlurObserver) {
  49690. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49691. }
  49692. this._onKeyboardObserver = null;
  49693. this._onCanvasBlurObserver = null;
  49694. }
  49695. this._keys = [];
  49696. };
  49697. /**
  49698. * Gets the class name of the current intput.
  49699. * @returns the class name
  49700. */
  49701. FlyCameraKeyboardInput.prototype.getClassName = function () {
  49702. return "FlyCameraKeyboardInput";
  49703. };
  49704. /** @hidden */
  49705. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  49706. this._keys = [];
  49707. };
  49708. /**
  49709. * Get the friendly name associated with the input class.
  49710. * @returns the input friendly name
  49711. */
  49712. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  49713. return "keyboard";
  49714. };
  49715. /**
  49716. * Update the current camera state depending on the inputs that have been used this frame.
  49717. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49718. */
  49719. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  49720. if (this._onKeyboardObserver) {
  49721. var camera = this.camera;
  49722. // Keyboard
  49723. for (var index = 0; index < this._keys.length; index++) {
  49724. var keyCode = this._keys[index];
  49725. var speed = camera._computeLocalCameraSpeed();
  49726. if (this.keysForward.indexOf(keyCode) !== -1) {
  49727. camera._localDirection.copyFromFloats(0, 0, speed);
  49728. }
  49729. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  49730. camera._localDirection.copyFromFloats(0, 0, -speed);
  49731. }
  49732. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49733. camera._localDirection.copyFromFloats(0, speed, 0);
  49734. }
  49735. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49736. camera._localDirection.copyFromFloats(0, -speed, 0);
  49737. }
  49738. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49739. camera._localDirection.copyFromFloats(speed, 0, 0);
  49740. }
  49741. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  49742. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49743. }
  49744. if (camera.getScene().useRightHandedSystem) {
  49745. camera._localDirection.z *= -1;
  49746. }
  49747. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49748. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49749. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49750. }
  49751. }
  49752. };
  49753. __decorate([
  49754. BABYLON.serialize()
  49755. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  49756. __decorate([
  49757. BABYLON.serialize()
  49758. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  49759. __decorate([
  49760. BABYLON.serialize()
  49761. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  49762. __decorate([
  49763. BABYLON.serialize()
  49764. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  49765. __decorate([
  49766. BABYLON.serialize()
  49767. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  49771. return FlyCameraKeyboardInput;
  49772. }());
  49773. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  49774. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  49775. })(BABYLON || (BABYLON = {}));
  49776. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  49777. var BABYLON;
  49778. (function (BABYLON) {
  49779. /**
  49780. * Default Inputs manager for the FlyCamera.
  49781. * It groups all the default supported inputs for ease of use.
  49782. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49783. */
  49784. var FlyCameraInputsManager = /** @class */ (function (_super) {
  49785. __extends(FlyCameraInputsManager, _super);
  49786. /**
  49787. * Instantiates a new FlyCameraInputsManager.
  49788. * @param camera Defines the camera the inputs belong to.
  49789. */
  49790. function FlyCameraInputsManager(camera) {
  49791. return _super.call(this, camera) || this;
  49792. }
  49793. /**
  49794. * Add keyboard input support to the input manager.
  49795. * @returns the new FlyCameraKeyboardMoveInput().
  49796. */
  49797. FlyCameraInputsManager.prototype.addKeyboard = function () {
  49798. this.add(new BABYLON.FlyCameraKeyboardInput());
  49799. return this;
  49800. };
  49801. /**
  49802. * Add mouse input support to the input manager.
  49803. * @param touchEnabled Enable touch screen support.
  49804. * @returns the new FlyCameraMouseInput().
  49805. */
  49806. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49807. if (touchEnabled === void 0) { touchEnabled = true; }
  49808. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  49809. return this;
  49810. };
  49811. return FlyCameraInputsManager;
  49812. }(BABYLON.CameraInputsManager));
  49813. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  49814. })(BABYLON || (BABYLON = {}));
  49815. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  49816. var BABYLON;
  49817. (function (BABYLON) {
  49818. /**
  49819. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49820. * such as in a 3D Space Shooter or a Flight Simulator.
  49821. */
  49822. var FlyCamera = /** @class */ (function (_super) {
  49823. __extends(FlyCamera, _super);
  49824. /**
  49825. * Instantiates a FlyCamera.
  49826. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49827. * such as in a 3D Space Shooter or a Flight Simulator.
  49828. * @param name Define the name of the camera in the scene.
  49829. * @param position Define the starting position of the camera in the scene.
  49830. * @param scene Define the scene the camera belongs to.
  49831. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  49832. */
  49833. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49834. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49835. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49836. /**
  49837. * Define the collision ellipsoid of the camera.
  49838. * This is helpful for simulating a camera body, like a player's body.
  49839. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49840. */
  49841. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  49842. /**
  49843. * Define an offset for the position of the ellipsoid around the camera.
  49844. * This can be helpful if the camera is attached away from the player's body center,
  49845. * such as at its head.
  49846. */
  49847. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49848. /**
  49849. * Enable or disable collisions of the camera with the rest of the scene objects.
  49850. */
  49851. _this.checkCollisions = false;
  49852. /**
  49853. * Enable or disable gravity on the camera.
  49854. */
  49855. _this.applyGravity = false;
  49856. /**
  49857. * Define the current direction the camera is moving to.
  49858. */
  49859. _this.cameraDirection = BABYLON.Vector3.Zero();
  49860. /**
  49861. * Track Roll to maintain the wanted Rolling when looking around.
  49862. */
  49863. _this._trackRoll = 0;
  49864. /**
  49865. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  49866. */
  49867. _this.rollCorrect = 100;
  49868. /**
  49869. * Mimic a banked turn, Rolling the camera when Yawing.
  49870. * It's recommended to use rollCorrect = 10 for faster banking correction.
  49871. */
  49872. _this.bankedTurn = false;
  49873. /**
  49874. * Limit in radians for how much Roll banking will add. (Default: 90°)
  49875. */
  49876. _this.bankedTurnLimit = Math.PI / 2;
  49877. /**
  49878. * Value of 0 disables the banked Roll.
  49879. * Value of 1 is equal to the Yaw angle in radians.
  49880. */
  49881. _this.bankedTurnMultiplier = 1;
  49882. _this._needMoveForGravity = false;
  49883. _this._oldPosition = BABYLON.Vector3.Zero();
  49884. _this._diffPosition = BABYLON.Vector3.Zero();
  49885. _this._newPosition = BABYLON.Vector3.Zero();
  49886. // Collisions.
  49887. _this._collisionMask = -1;
  49888. /** @hidden */
  49889. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49890. if (collidedMesh === void 0) { collidedMesh = null; }
  49891. // TODO Move this to the collision coordinator!
  49892. if (_this.getScene().workerCollisions) {
  49893. newPosition.multiplyInPlace(_this._collider._radius);
  49894. }
  49895. var updatePosition = function (newPos) {
  49896. _this._newPosition.copyFrom(newPos);
  49897. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49898. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49899. _this.position.addInPlace(_this._diffPosition);
  49900. if (_this.onCollide && collidedMesh) {
  49901. _this.onCollide(collidedMesh);
  49902. }
  49903. }
  49904. };
  49905. updatePosition(newPosition);
  49906. };
  49907. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  49908. _this.inputs.addKeyboard().addMouse();
  49909. return _this;
  49910. }
  49911. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  49912. /**
  49913. * Gets the input sensibility for mouse input.
  49914. * Higher values reduce sensitivity.
  49915. */
  49916. get: function () {
  49917. var mouse = this.inputs.attached["mouse"];
  49918. if (mouse) {
  49919. return mouse.angularSensibility;
  49920. }
  49921. return 0;
  49922. },
  49923. /**
  49924. * Sets the input sensibility for a mouse input.
  49925. * Higher values reduce sensitivity.
  49926. */
  49927. set: function (value) {
  49928. var mouse = this.inputs.attached["mouse"];
  49929. if (mouse) {
  49930. mouse.angularSensibility = value;
  49931. }
  49932. },
  49933. enumerable: true,
  49934. configurable: true
  49935. });
  49936. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  49937. /**
  49938. * Get the keys for camera movement forward.
  49939. */
  49940. get: function () {
  49941. var keyboard = this.inputs.attached["keyboard"];
  49942. if (keyboard) {
  49943. return keyboard.keysForward;
  49944. }
  49945. return [];
  49946. },
  49947. /**
  49948. * Set the keys for camera movement forward.
  49949. */
  49950. set: function (value) {
  49951. var keyboard = this.inputs.attached["keyboard"];
  49952. if (keyboard) {
  49953. keyboard.keysForward = value;
  49954. }
  49955. },
  49956. enumerable: true,
  49957. configurable: true
  49958. });
  49959. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  49960. /**
  49961. * Get the keys for camera movement backward.
  49962. */
  49963. get: function () {
  49964. var keyboard = this.inputs.attached["keyboard"];
  49965. if (keyboard) {
  49966. return keyboard.keysBackward;
  49967. }
  49968. return [];
  49969. },
  49970. set: function (value) {
  49971. var keyboard = this.inputs.attached["keyboard"];
  49972. if (keyboard) {
  49973. keyboard.keysBackward = value;
  49974. }
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  49980. /**
  49981. * Get the keys for camera movement up.
  49982. */
  49983. get: function () {
  49984. var keyboard = this.inputs.attached["keyboard"];
  49985. if (keyboard) {
  49986. return keyboard.keysUp;
  49987. }
  49988. return [];
  49989. },
  49990. /**
  49991. * Set the keys for camera movement up.
  49992. */
  49993. set: function (value) {
  49994. var keyboard = this.inputs.attached["keyboard"];
  49995. if (keyboard) {
  49996. keyboard.keysUp = value;
  49997. }
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50003. /**
  50004. * Get the keys for camera movement down.
  50005. */
  50006. get: function () {
  50007. var keyboard = this.inputs.attached["keyboard"];
  50008. if (keyboard) {
  50009. return keyboard.keysDown;
  50010. }
  50011. return [];
  50012. },
  50013. /**
  50014. * Set the keys for camera movement down.
  50015. */
  50016. set: function (value) {
  50017. var keyboard = this.inputs.attached["keyboard"];
  50018. if (keyboard) {
  50019. keyboard.keysDown = value;
  50020. }
  50021. },
  50022. enumerable: true,
  50023. configurable: true
  50024. });
  50025. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50026. /**
  50027. * Get the keys for camera movement left.
  50028. */
  50029. get: function () {
  50030. var keyboard = this.inputs.attached["keyboard"];
  50031. if (keyboard) {
  50032. return keyboard.keysLeft;
  50033. }
  50034. return [];
  50035. },
  50036. /**
  50037. * Set the keys for camera movement left.
  50038. */
  50039. set: function (value) {
  50040. var keyboard = this.inputs.attached["keyboard"];
  50041. if (keyboard) {
  50042. keyboard.keysLeft = value;
  50043. }
  50044. },
  50045. enumerable: true,
  50046. configurable: true
  50047. });
  50048. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50049. /**
  50050. * Set the keys for camera movement right.
  50051. */
  50052. get: function () {
  50053. var keyboard = this.inputs.attached["keyboard"];
  50054. if (keyboard) {
  50055. return keyboard.keysRight;
  50056. }
  50057. return [];
  50058. },
  50059. /**
  50060. * Set the keys for camera movement right.
  50061. */
  50062. set: function (value) {
  50063. var keyboard = this.inputs.attached["keyboard"];
  50064. if (keyboard) {
  50065. keyboard.keysRight = value;
  50066. }
  50067. },
  50068. enumerable: true,
  50069. configurable: true
  50070. });
  50071. /**
  50072. * Attach a control to the HTML DOM element.
  50073. * @param element Defines the element that listens to the input events.
  50074. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50075. */
  50076. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50077. this.inputs.attachElement(element, noPreventDefault);
  50078. };
  50079. /**
  50080. * Detach a control from the HTML DOM element.
  50081. * The camera will stop reacting to that input.
  50082. * @param element Defines the element that listens to the input events.
  50083. */
  50084. FlyCamera.prototype.detachControl = function (element) {
  50085. this.inputs.detachElement(element);
  50086. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50087. };
  50088. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50089. /**
  50090. * Get the mask that the camera ignores in collision events.
  50091. */
  50092. get: function () {
  50093. return this._collisionMask;
  50094. },
  50095. /**
  50096. * Set the mask that the camera ignores in collision events.
  50097. */
  50098. set: function (mask) {
  50099. this._collisionMask = !isNaN(mask) ? mask : -1;
  50100. },
  50101. enumerable: true,
  50102. configurable: true
  50103. });
  50104. /** @hidden */
  50105. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50106. var globalPosition;
  50107. if (this.parent) {
  50108. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50109. }
  50110. else {
  50111. globalPosition = this.position;
  50112. }
  50113. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50114. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50115. if (!this._collider) {
  50116. this._collider = new BABYLON.Collider();
  50117. }
  50118. this._collider._radius = this.ellipsoid;
  50119. this._collider.collisionMask = this._collisionMask;
  50120. // No need for clone, as long as gravity is not on.
  50121. var actualDisplacement = displacement;
  50122. // Add gravity to direction to prevent dual-collision checking.
  50123. if (this.applyGravity) {
  50124. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50125. actualDisplacement = displacement.add(this.getScene().gravity);
  50126. }
  50127. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50128. };
  50129. /** @hidden */
  50130. FlyCamera.prototype._checkInputs = function () {
  50131. if (!this._localDirection) {
  50132. this._localDirection = BABYLON.Vector3.Zero();
  50133. this._transformedDirection = BABYLON.Vector3.Zero();
  50134. }
  50135. this.inputs.checkInputs();
  50136. _super.prototype._checkInputs.call(this);
  50137. };
  50138. /** @hidden */
  50139. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50140. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50141. };
  50142. /** @hidden */
  50143. FlyCamera.prototype._updatePosition = function () {
  50144. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50145. this._collideWithWorld(this.cameraDirection);
  50146. }
  50147. else {
  50148. _super.prototype._updatePosition.call(this);
  50149. }
  50150. };
  50151. /**
  50152. * Restore the Roll to its target value at the rate specified.
  50153. * @param rate - Higher means slower restoring.
  50154. * @hidden
  50155. */
  50156. FlyCamera.prototype.restoreRoll = function (rate) {
  50157. var limit = this._trackRoll; // Target Roll.
  50158. var z = this.rotation.z; // Current Roll.
  50159. var delta = limit - z; // Difference in Roll.
  50160. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50161. // If the difference is noticable, restore the Roll.
  50162. if (Math.abs(delta) >= minRad) {
  50163. // Change Z rotation towards the target Roll.
  50164. this.rotation.z += delta / rate;
  50165. // Match when near enough.
  50166. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50167. this.rotation.z = limit;
  50168. }
  50169. }
  50170. };
  50171. /**
  50172. * Destroy the camera and release the current resources held by it.
  50173. */
  50174. FlyCamera.prototype.dispose = function () {
  50175. this.inputs.clear();
  50176. _super.prototype.dispose.call(this);
  50177. };
  50178. /**
  50179. * Get the current object class name.
  50180. * @returns the class name.
  50181. */
  50182. FlyCamera.prototype.getClassName = function () {
  50183. return "FlyCamera";
  50184. };
  50185. __decorate([
  50186. BABYLON.serializeAsVector3()
  50187. ], FlyCamera.prototype, "ellipsoid", void 0);
  50188. __decorate([
  50189. BABYLON.serializeAsVector3()
  50190. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50191. __decorate([
  50192. BABYLON.serialize()
  50193. ], FlyCamera.prototype, "checkCollisions", void 0);
  50194. __decorate([
  50195. BABYLON.serialize()
  50196. ], FlyCamera.prototype, "applyGravity", void 0);
  50197. return FlyCamera;
  50198. }(BABYLON.TargetCamera));
  50199. BABYLON.FlyCamera = FlyCamera;
  50200. })(BABYLON || (BABYLON = {}));
  50201. //# sourceMappingURL=babylon.flyCamera.js.map
  50202. var BABYLON;
  50203. (function (BABYLON) {
  50204. /**
  50205. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50206. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50207. */
  50208. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50209. function ArcRotateCameraKeyboardMoveInput() {
  50210. /**
  50211. * Defines the list of key codes associated with the up action (increase alpha)
  50212. */
  50213. this.keysUp = [38];
  50214. /**
  50215. * Defines the list of key codes associated with the down action (decrease alpha)
  50216. */
  50217. this.keysDown = [40];
  50218. /**
  50219. * Defines the list of key codes associated with the left action (increase beta)
  50220. */
  50221. this.keysLeft = [37];
  50222. /**
  50223. * Defines the list of key codes associated with the right action (decrease beta)
  50224. */
  50225. this.keysRight = [39];
  50226. /**
  50227. * Defines the list of key codes associated with the reset action.
  50228. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50229. */
  50230. this.keysReset = [220];
  50231. /**
  50232. * Defines the panning sensibility of the inputs.
  50233. * (How fast is the camera paning)
  50234. */
  50235. this.panningSensibility = 50.0;
  50236. /**
  50237. * Defines the zooming sensibility of the inputs.
  50238. * (How fast is the camera zooming)
  50239. */
  50240. this.zoomingSensibility = 25.0;
  50241. /**
  50242. * Defines wether maintaining the alt key down switch the movement mode from
  50243. * orientation to zoom.
  50244. */
  50245. this.useAltToZoom = true;
  50246. /**
  50247. * Rotation speed of the camera
  50248. */
  50249. this.angularSpeed = 0.01;
  50250. this._keys = new Array();
  50251. }
  50252. /**
  50253. * Attach the input controls to a specific dom element to get the input from.
  50254. * @param element Defines the element the controls should be listened from
  50255. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50256. */
  50257. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50258. var _this = this;
  50259. if (this._onCanvasBlurObserver) {
  50260. return;
  50261. }
  50262. this._scene = this.camera.getScene();
  50263. this._engine = this._scene.getEngine();
  50264. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50265. _this._keys = [];
  50266. });
  50267. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50268. var evt = info.event;
  50269. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50270. _this._ctrlPressed = evt.ctrlKey;
  50271. _this._altPressed = evt.altKey;
  50272. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50273. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50274. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50275. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50276. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50277. var index = _this._keys.indexOf(evt.keyCode);
  50278. if (index === -1) {
  50279. _this._keys.push(evt.keyCode);
  50280. }
  50281. if (evt.preventDefault) {
  50282. if (!noPreventDefault) {
  50283. evt.preventDefault();
  50284. }
  50285. }
  50286. }
  50287. }
  50288. else {
  50289. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50290. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50291. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50292. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50293. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50294. var index = _this._keys.indexOf(evt.keyCode);
  50295. if (index >= 0) {
  50296. _this._keys.splice(index, 1);
  50297. }
  50298. if (evt.preventDefault) {
  50299. if (!noPreventDefault) {
  50300. evt.preventDefault();
  50301. }
  50302. }
  50303. }
  50304. }
  50305. });
  50306. };
  50307. /**
  50308. * Detach the current controls from the specified dom element.
  50309. * @param element Defines the element to stop listening the inputs from
  50310. */
  50311. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50312. if (this._scene) {
  50313. if (this._onKeyboardObserver) {
  50314. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50315. }
  50316. if (this._onCanvasBlurObserver) {
  50317. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50318. }
  50319. this._onKeyboardObserver = null;
  50320. this._onCanvasBlurObserver = null;
  50321. }
  50322. this._keys = [];
  50323. };
  50324. /**
  50325. * Update the current camera state depending on the inputs that have been used this frame.
  50326. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50327. */
  50328. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50329. if (this._onKeyboardObserver) {
  50330. var camera = this.camera;
  50331. for (var index = 0; index < this._keys.length; index++) {
  50332. var keyCode = this._keys[index];
  50333. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50334. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50335. camera.inertialPanningX -= 1 / this.panningSensibility;
  50336. }
  50337. else {
  50338. camera.inertialAlphaOffset -= this.angularSpeed;
  50339. }
  50340. }
  50341. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50342. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50343. camera.inertialPanningY += 1 / this.panningSensibility;
  50344. }
  50345. else if (this._altPressed && this.useAltToZoom) {
  50346. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50347. }
  50348. else {
  50349. camera.inertialBetaOffset -= this.angularSpeed;
  50350. }
  50351. }
  50352. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50353. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50354. camera.inertialPanningX += 1 / this.panningSensibility;
  50355. }
  50356. else {
  50357. camera.inertialAlphaOffset += this.angularSpeed;
  50358. }
  50359. }
  50360. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50361. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50362. camera.inertialPanningY -= 1 / this.panningSensibility;
  50363. }
  50364. else if (this._altPressed && this.useAltToZoom) {
  50365. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50366. }
  50367. else {
  50368. camera.inertialBetaOffset += this.angularSpeed;
  50369. }
  50370. }
  50371. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50372. if (camera.useInputToRestoreState) {
  50373. camera.restoreState();
  50374. }
  50375. }
  50376. }
  50377. }
  50378. };
  50379. /**
  50380. * Gets the class name of the current intput.
  50381. * @returns the class name
  50382. */
  50383. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50384. return "ArcRotateCameraKeyboardMoveInput";
  50385. };
  50386. /**
  50387. * Get the friendly name associated with the input class.
  50388. * @returns the input friendly name
  50389. */
  50390. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50391. return "keyboard";
  50392. };
  50393. __decorate([
  50394. BABYLON.serialize()
  50395. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50396. __decorate([
  50397. BABYLON.serialize()
  50398. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50399. __decorate([
  50400. BABYLON.serialize()
  50401. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50402. __decorate([
  50403. BABYLON.serialize()
  50404. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50405. __decorate([
  50406. BABYLON.serialize()
  50407. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50408. __decorate([
  50409. BABYLON.serialize()
  50410. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50411. __decorate([
  50412. BABYLON.serialize()
  50413. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50414. __decorate([
  50415. BABYLON.serialize()
  50416. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50417. __decorate([
  50418. BABYLON.serialize()
  50419. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50420. return ArcRotateCameraKeyboardMoveInput;
  50421. }());
  50422. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50423. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50424. })(BABYLON || (BABYLON = {}));
  50425. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  50426. var BABYLON;
  50427. (function (BABYLON) {
  50428. /**
  50429. * Manage the mouse wheel inputs to control an arc rotate camera.
  50430. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50431. */
  50432. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50433. function ArcRotateCameraMouseWheelInput() {
  50434. /**
  50435. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50436. */
  50437. this.wheelPrecision = 3.0;
  50438. /**
  50439. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50440. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50441. */
  50442. this.wheelDeltaPercentage = 0;
  50443. }
  50444. /**
  50445. * Attach the input controls to a specific dom element to get the input from.
  50446. * @param element Defines the element the controls should be listened from
  50447. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50448. */
  50449. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50450. var _this = this;
  50451. this._wheel = function (p, s) {
  50452. //sanity check - this should be a PointerWheel event.
  50453. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50454. return;
  50455. }
  50456. var event = p.event;
  50457. var delta = 0;
  50458. if (event.wheelDelta) {
  50459. if (_this.wheelDeltaPercentage) {
  50460. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50461. if (event.wheelDelta > 0) {
  50462. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50463. }
  50464. else {
  50465. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50466. }
  50467. }
  50468. else {
  50469. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50470. }
  50471. }
  50472. else if (event.detail) {
  50473. delta = -event.detail / _this.wheelPrecision;
  50474. }
  50475. if (delta) {
  50476. _this.camera.inertialRadiusOffset += delta;
  50477. }
  50478. if (event.preventDefault) {
  50479. if (!noPreventDefault) {
  50480. event.preventDefault();
  50481. }
  50482. }
  50483. };
  50484. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50485. };
  50486. /**
  50487. * Detach the current controls from the specified dom element.
  50488. * @param element Defines the element to stop listening the inputs from
  50489. */
  50490. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50491. if (this._observer && element) {
  50492. this.camera.getScene().onPointerObservable.remove(this._observer);
  50493. this._observer = null;
  50494. this._wheel = null;
  50495. }
  50496. };
  50497. /**
  50498. * Gets the class name of the current intput.
  50499. * @returns the class name
  50500. */
  50501. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50502. return "ArcRotateCameraMouseWheelInput";
  50503. };
  50504. /**
  50505. * Get the friendly name associated with the input class.
  50506. * @returns the input friendly name
  50507. */
  50508. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50509. return "mousewheel";
  50510. };
  50511. __decorate([
  50512. BABYLON.serialize()
  50513. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50514. __decorate([
  50515. BABYLON.serialize()
  50516. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50517. return ArcRotateCameraMouseWheelInput;
  50518. }());
  50519. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50520. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50521. })(BABYLON || (BABYLON = {}));
  50522. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  50523. var BABYLON;
  50524. (function (BABYLON) {
  50525. /**
  50526. * Manage the pointers inputs to control an arc rotate camera.
  50527. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50528. */
  50529. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50530. function ArcRotateCameraPointersInput() {
  50531. /**
  50532. * Defines the buttons associated with the input to handle camera move.
  50533. */
  50534. this.buttons = [0, 1, 2];
  50535. /**
  50536. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50537. */
  50538. this.angularSensibilityX = 1000.0;
  50539. /**
  50540. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50541. */
  50542. this.angularSensibilityY = 1000.0;
  50543. /**
  50544. * Defines the pointer pinch precision or how fast is the camera zooming.
  50545. */
  50546. this.pinchPrecision = 12.0;
  50547. /**
  50548. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50549. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50550. */
  50551. this.pinchDeltaPercentage = 0;
  50552. /**
  50553. * Defines the pointer panning sensibility or how fast is the camera moving.
  50554. */
  50555. this.panningSensibility = 1000.0;
  50556. /**
  50557. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50558. */
  50559. this.multiTouchPanning = true;
  50560. /**
  50561. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50562. */
  50563. this.multiTouchPanAndZoom = true;
  50564. /**
  50565. * Revers pinch action direction.
  50566. */
  50567. this.pinchInwards = true;
  50568. this._isPanClick = false;
  50569. }
  50570. /**
  50571. * Attach the input controls to a specific dom element to get the input from.
  50572. * @param element Defines the element the controls should be listened from
  50573. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50574. */
  50575. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  50576. var _this = this;
  50577. var engine = this.camera.getEngine();
  50578. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  50579. var pointA = null;
  50580. var pointB = null;
  50581. var previousPinchSquaredDistance = 0;
  50582. var initialDistance = 0;
  50583. var twoFingerActivityCount = 0;
  50584. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  50585. this._pointerInput = function (p, s) {
  50586. var evt = p.event;
  50587. var isTouch = p.event.pointerType === "touch";
  50588. if (engine.isInVRExclusivePointerMode) {
  50589. return;
  50590. }
  50591. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  50592. return;
  50593. }
  50594. var srcElement = (evt.srcElement || evt.target);
  50595. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50596. try {
  50597. srcElement.setPointerCapture(evt.pointerId);
  50598. }
  50599. catch (e) {
  50600. //Nothing to do with the error. Execution will continue.
  50601. }
  50602. // Manage panning with pan button click
  50603. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  50604. // manage pointers
  50605. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  50606. if (pointA === null) {
  50607. pointA = cacheSoloPointer;
  50608. }
  50609. else if (pointB === null) {
  50610. pointB = cacheSoloPointer;
  50611. }
  50612. if (!noPreventDefault) {
  50613. evt.preventDefault();
  50614. element.focus();
  50615. }
  50616. }
  50617. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  50618. if (_this.camera.useInputToRestoreState) {
  50619. _this.camera.restoreState();
  50620. }
  50621. }
  50622. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50623. try {
  50624. srcElement.releasePointerCapture(evt.pointerId);
  50625. }
  50626. catch (e) {
  50627. //Nothing to do with the error.
  50628. }
  50629. cacheSoloPointer = null;
  50630. previousPinchSquaredDistance = 0;
  50631. previousMultiTouchPanPosition.isPaning = false;
  50632. previousMultiTouchPanPosition.isPinching = false;
  50633. twoFingerActivityCount = 0;
  50634. initialDistance = 0;
  50635. if (!isTouch) {
  50636. pointB = null; // Mouse and pen are mono pointer
  50637. }
  50638. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  50639. //but emptying completly pointers collection is required to fix a bug on iPhone :
  50640. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  50641. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  50642. if (engine._badOS) {
  50643. pointA = pointB = null;
  50644. }
  50645. else {
  50646. //only remove the impacted pointer in case of multitouch allowing on most
  50647. //platforms switching from rotate to zoom and pan seamlessly.
  50648. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  50649. pointA = pointB;
  50650. pointB = null;
  50651. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50652. }
  50653. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  50654. pointB = null;
  50655. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50656. }
  50657. else {
  50658. pointA = pointB = null;
  50659. }
  50660. }
  50661. if (!noPreventDefault) {
  50662. evt.preventDefault();
  50663. }
  50664. }
  50665. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50666. if (!noPreventDefault) {
  50667. evt.preventDefault();
  50668. }
  50669. // One button down
  50670. if (pointA && pointB === null && cacheSoloPointer) {
  50671. if (_this.panningSensibility !== 0 &&
  50672. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  50673. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  50674. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  50675. }
  50676. else {
  50677. var offsetX = evt.clientX - cacheSoloPointer.x;
  50678. var offsetY = evt.clientY - cacheSoloPointer.y;
  50679. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50680. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50681. }
  50682. cacheSoloPointer.x = evt.clientX;
  50683. cacheSoloPointer.y = evt.clientY;
  50684. }
  50685. // Two buttons down: pinch/pan
  50686. else if (pointA && pointB) {
  50687. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  50688. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  50689. ed.x = evt.clientX;
  50690. ed.y = evt.clientY;
  50691. var direction = _this.pinchInwards ? 1 : -1;
  50692. var distX = pointA.x - pointB.x;
  50693. var distY = pointA.y - pointB.y;
  50694. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  50695. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  50696. if (previousPinchSquaredDistance === 0) {
  50697. initialDistance = pinchDistance;
  50698. previousPinchSquaredDistance = pinchSquaredDistance;
  50699. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  50700. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  50701. return;
  50702. }
  50703. if (_this.multiTouchPanAndZoom) {
  50704. if (_this.pinchDeltaPercentage) {
  50705. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50706. }
  50707. else {
  50708. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50709. (_this.pinchPrecision *
  50710. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50711. direction);
  50712. }
  50713. if (_this.panningSensibility !== 0) {
  50714. var pointersCenterX = (pointA.x + pointB.x) / 2;
  50715. var pointersCenterY = (pointA.y + pointB.y) / 2;
  50716. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  50717. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  50718. previousMultiTouchPanPosition.x = pointersCenterX;
  50719. previousMultiTouchPanPosition.y = pointersCenterY;
  50720. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  50721. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  50722. }
  50723. }
  50724. else {
  50725. twoFingerActivityCount++;
  50726. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  50727. if (_this.pinchDeltaPercentage) {
  50728. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50729. }
  50730. else {
  50731. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50732. (_this.pinchPrecision *
  50733. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50734. direction);
  50735. }
  50736. previousMultiTouchPanPosition.isPaning = false;
  50737. previousMultiTouchPanPosition.isPinching = true;
  50738. }
  50739. else {
  50740. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  50741. if (!previousMultiTouchPanPosition.isPaning) {
  50742. previousMultiTouchPanPosition.isPaning = true;
  50743. previousMultiTouchPanPosition.isPinching = false;
  50744. previousMultiTouchPanPosition.x = ed.x;
  50745. previousMultiTouchPanPosition.y = ed.y;
  50746. return;
  50747. }
  50748. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  50749. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  50750. }
  50751. }
  50752. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  50753. previousMultiTouchPanPosition.x = ed.x;
  50754. previousMultiTouchPanPosition.y = ed.y;
  50755. }
  50756. }
  50757. previousPinchSquaredDistance = pinchSquaredDistance;
  50758. }
  50759. }
  50760. };
  50761. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  50762. this._onContextMenu = function (evt) {
  50763. evt.preventDefault();
  50764. };
  50765. if (!this.camera._useCtrlForPanning) {
  50766. element.addEventListener("contextmenu", this._onContextMenu, false);
  50767. }
  50768. this._onLostFocus = function () {
  50769. //this._keys = [];
  50770. pointA = pointB = null;
  50771. previousPinchSquaredDistance = 0;
  50772. previousMultiTouchPanPosition.isPaning = false;
  50773. previousMultiTouchPanPosition.isPinching = false;
  50774. twoFingerActivityCount = 0;
  50775. cacheSoloPointer = null;
  50776. initialDistance = 0;
  50777. };
  50778. this._onMouseMove = function (evt) {
  50779. if (!engine.isPointerLock) {
  50780. return;
  50781. }
  50782. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  50783. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  50784. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50785. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50786. if (!noPreventDefault) {
  50787. evt.preventDefault();
  50788. }
  50789. };
  50790. this._onGestureStart = function (e) {
  50791. if (window.MSGesture === undefined) {
  50792. return;
  50793. }
  50794. if (!_this._MSGestureHandler) {
  50795. _this._MSGestureHandler = new MSGesture();
  50796. _this._MSGestureHandler.target = element;
  50797. }
  50798. _this._MSGestureHandler.addPointer(e.pointerId);
  50799. };
  50800. this._onGesture = function (e) {
  50801. _this.camera.radius *= e.scale;
  50802. if (e.preventDefault) {
  50803. if (!noPreventDefault) {
  50804. e.stopPropagation();
  50805. e.preventDefault();
  50806. }
  50807. }
  50808. };
  50809. element.addEventListener("mousemove", this._onMouseMove, false);
  50810. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  50811. element.addEventListener("MSGestureChange", this._onGesture, false);
  50812. BABYLON.Tools.RegisterTopRootEvents([
  50813. { name: "blur", handler: this._onLostFocus }
  50814. ]);
  50815. };
  50816. /**
  50817. * Detach the current controls from the specified dom element.
  50818. * @param element Defines the element to stop listening the inputs from
  50819. */
  50820. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  50821. if (this._onLostFocus) {
  50822. BABYLON.Tools.UnregisterTopRootEvents([
  50823. { name: "blur", handler: this._onLostFocus }
  50824. ]);
  50825. }
  50826. if (element && this._observer) {
  50827. this.camera.getScene().onPointerObservable.remove(this._observer);
  50828. this._observer = null;
  50829. if (this._onContextMenu) {
  50830. element.removeEventListener("contextmenu", this._onContextMenu);
  50831. }
  50832. if (this._onMouseMove) {
  50833. element.removeEventListener("mousemove", this._onMouseMove);
  50834. }
  50835. if (this._onGestureStart) {
  50836. element.removeEventListener("MSPointerDown", this._onGestureStart);
  50837. }
  50838. if (this._onGesture) {
  50839. element.removeEventListener("MSGestureChange", this._onGesture);
  50840. }
  50841. this._isPanClick = false;
  50842. this.pinchInwards = true;
  50843. this._onMouseMove = null;
  50844. this._onGestureStart = null;
  50845. this._onGesture = null;
  50846. this._MSGestureHandler = null;
  50847. this._onLostFocus = null;
  50848. this._onContextMenu = null;
  50849. }
  50850. };
  50851. /**
  50852. * Gets the class name of the current intput.
  50853. * @returns the class name
  50854. */
  50855. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  50856. return "ArcRotateCameraPointersInput";
  50857. };
  50858. /**
  50859. * Get the friendly name associated with the input class.
  50860. * @returns the input friendly name
  50861. */
  50862. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  50863. return "pointers";
  50864. };
  50865. __decorate([
  50866. BABYLON.serialize()
  50867. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  50868. __decorate([
  50869. BABYLON.serialize()
  50870. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  50871. __decorate([
  50872. BABYLON.serialize()
  50873. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  50874. __decorate([
  50875. BABYLON.serialize()
  50876. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  50877. __decorate([
  50878. BABYLON.serialize()
  50879. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  50880. __decorate([
  50881. BABYLON.serialize()
  50882. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  50883. __decorate([
  50884. BABYLON.serialize()
  50885. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  50886. __decorate([
  50887. BABYLON.serialize()
  50888. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  50889. return ArcRotateCameraPointersInput;
  50890. }());
  50891. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  50892. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  50893. })(BABYLON || (BABYLON = {}));
  50894. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  50895. var BABYLON;
  50896. (function (BABYLON) {
  50897. /**
  50898. * Default Inputs manager for the ArcRotateCamera.
  50899. * It groups all the default supported inputs for ease of use.
  50900. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50901. */
  50902. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  50903. __extends(ArcRotateCameraInputsManager, _super);
  50904. /**
  50905. * Instantiates a new ArcRotateCameraInputsManager.
  50906. * @param camera Defines the camera the inputs belong to
  50907. */
  50908. function ArcRotateCameraInputsManager(camera) {
  50909. return _super.call(this, camera) || this;
  50910. }
  50911. /**
  50912. * Add mouse wheel input support to the input manager.
  50913. * @returns the current input manager
  50914. */
  50915. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  50916. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  50917. return this;
  50918. };
  50919. /**
  50920. * Add pointers input support to the input manager.
  50921. * @returns the current input manager
  50922. */
  50923. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  50924. this.add(new BABYLON.ArcRotateCameraPointersInput());
  50925. return this;
  50926. };
  50927. /**
  50928. * Add keyboard input support to the input manager.
  50929. * @returns the current input manager
  50930. */
  50931. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  50932. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  50933. return this;
  50934. };
  50935. /**
  50936. * Add orientation input support to the input manager.
  50937. * @returns the current input manager
  50938. */
  50939. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  50940. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  50941. return this;
  50942. };
  50943. return ArcRotateCameraInputsManager;
  50944. }(BABYLON.CameraInputsManager));
  50945. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  50946. })(BABYLON || (BABYLON = {}));
  50947. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  50948. var BABYLON;
  50949. (function (BABYLON) {
  50950. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  50951. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  50952. });
  50953. /**
  50954. * This represents an orbital type of camera.
  50955. *
  50956. * 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.
  50957. * 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.
  50958. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  50959. */
  50960. var ArcRotateCamera = /** @class */ (function (_super) {
  50961. __extends(ArcRotateCamera, _super);
  50962. /**
  50963. * Instantiates a new ArcRotateCamera in a given scene
  50964. * @param name Defines the name of the camera
  50965. * @param alpha Defines the camera rotation along the logitudinal axis
  50966. * @param beta Defines the camera rotation along the latitudinal axis
  50967. * @param radius Defines the camera distance from its target
  50968. * @param target Defines the camera target
  50969. * @param scene Defines the scene the camera belongs to
  50970. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  50971. */
  50972. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  50973. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  50974. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  50975. /**
  50976. * Current inertia value on the longitudinal axis.
  50977. * The bigger this number the longer it will take for the camera to stop.
  50978. */
  50979. _this.inertialAlphaOffset = 0;
  50980. /**
  50981. * Current inertia value on the latitudinal axis.
  50982. * The bigger this number the longer it will take for the camera to stop.
  50983. */
  50984. _this.inertialBetaOffset = 0;
  50985. /**
  50986. * Current inertia value on the radius axis.
  50987. * The bigger this number the longer it will take for the camera to stop.
  50988. */
  50989. _this.inertialRadiusOffset = 0;
  50990. /**
  50991. * Minimum allowed angle on the longitudinal axis.
  50992. * This can help limiting how the Camera is able to move in the scene.
  50993. */
  50994. _this.lowerAlphaLimit = null;
  50995. /**
  50996. * Maximum allowed angle on the longitudinal axis.
  50997. * This can help limiting how the Camera is able to move in the scene.
  50998. */
  50999. _this.upperAlphaLimit = null;
  51000. /**
  51001. * Minimum allowed angle on the latitudinal axis.
  51002. * This can help limiting how the Camera is able to move in the scene.
  51003. */
  51004. _this.lowerBetaLimit = 0.01;
  51005. /**
  51006. * Maximum allowed angle on the latitudinal axis.
  51007. * This can help limiting how the Camera is able to move in the scene.
  51008. */
  51009. _this.upperBetaLimit = Math.PI;
  51010. /**
  51011. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51012. * This can help limiting how the Camera is able to move in the scene.
  51013. */
  51014. _this.lowerRadiusLimit = null;
  51015. /**
  51016. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51017. * This can help limiting how the Camera is able to move in the scene.
  51018. */
  51019. _this.upperRadiusLimit = null;
  51020. /**
  51021. * Defines the current inertia value used during panning of the camera along the X axis.
  51022. */
  51023. _this.inertialPanningX = 0;
  51024. /**
  51025. * Defines the current inertia value used during panning of the camera along the Y axis.
  51026. */
  51027. _this.inertialPanningY = 0;
  51028. /**
  51029. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51030. * Basically if your fingers moves away from more than this distance you will be considered
  51031. * in pinch mode.
  51032. */
  51033. _this.pinchToPanMaxDistance = 20;
  51034. /**
  51035. * Defines the maximum distance the camera can pan.
  51036. * This could help keeping the cammera always in your scene.
  51037. */
  51038. _this.panningDistanceLimit = null;
  51039. /**
  51040. * Defines the target of the camera before paning.
  51041. */
  51042. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51043. /**
  51044. * Defines the value of the inertia used during panning.
  51045. * 0 would mean stop inertia and one would mean no decelleration at all.
  51046. */
  51047. _this.panningInertia = 0.9;
  51048. //-- end properties for backward compatibility for inputs
  51049. /**
  51050. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51051. */
  51052. _this.zoomOnFactor = 1;
  51053. /**
  51054. * Defines a screen offset for the camera position.
  51055. */
  51056. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51057. /**
  51058. * Allows the camera to be completely reversed.
  51059. * If false the camera can not arrive upside down.
  51060. */
  51061. _this.allowUpsideDown = true;
  51062. /**
  51063. * Define if double tap/click is used to restore the previously saved state of the camera.
  51064. */
  51065. _this.useInputToRestoreState = true;
  51066. /** @hidden */
  51067. _this._viewMatrix = new BABYLON.Matrix();
  51068. /**
  51069. * Defines the allowed panning axis.
  51070. */
  51071. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51072. /**
  51073. * Observable triggered when the mesh target has been changed on the camera.
  51074. */
  51075. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51076. /**
  51077. * Defines whether the camera should check collision with the objects oh the scene.
  51078. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51079. */
  51080. _this.checkCollisions = false;
  51081. /**
  51082. * Defines the collision radius of the camera.
  51083. * This simulates a sphere around the camera.
  51084. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51085. */
  51086. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51087. _this._previousPosition = BABYLON.Vector3.Zero();
  51088. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51089. _this._newPosition = BABYLON.Vector3.Zero();
  51090. _this._computationVector = BABYLON.Vector3.Zero();
  51091. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51092. if (collidedMesh === void 0) { collidedMesh = null; }
  51093. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51094. newPosition.multiplyInPlace(_this._collider._radius);
  51095. }
  51096. if (!collidedMesh) {
  51097. _this._previousPosition.copyFrom(_this.position);
  51098. }
  51099. else {
  51100. _this.setPosition(newPosition);
  51101. if (_this.onCollide) {
  51102. _this.onCollide(collidedMesh);
  51103. }
  51104. }
  51105. // Recompute because of constraints
  51106. var cosa = Math.cos(_this.alpha);
  51107. var sina = Math.sin(_this.alpha);
  51108. var cosb = Math.cos(_this.beta);
  51109. var sinb = Math.sin(_this.beta);
  51110. if (sinb === 0) {
  51111. sinb = 0.0001;
  51112. }
  51113. var target = _this._getTargetPosition();
  51114. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51115. target.addToRef(_this._computationVector, _this._newPosition);
  51116. _this.position.copyFrom(_this._newPosition);
  51117. var up = _this.upVector;
  51118. if (_this.allowUpsideDown && _this.beta < 0) {
  51119. up = up.clone();
  51120. up = up.negate();
  51121. }
  51122. _this._computeViewMatrix(_this.position, target, up);
  51123. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  51124. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  51125. _this._collisionTriggered = false;
  51126. };
  51127. _this._target = BABYLON.Vector3.Zero();
  51128. if (target) {
  51129. _this.setTarget(target);
  51130. }
  51131. _this.alpha = alpha;
  51132. _this.beta = beta;
  51133. _this.radius = radius;
  51134. _this.getViewMatrix();
  51135. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51136. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51137. return _this;
  51138. }
  51139. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51140. /**
  51141. * Defines the target point of the camera.
  51142. * The camera looks towards it form the radius distance.
  51143. */
  51144. get: function () {
  51145. return this._target;
  51146. },
  51147. set: function (value) {
  51148. this.setTarget(value);
  51149. },
  51150. enumerable: true,
  51151. configurable: true
  51152. });
  51153. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51154. //-- begin properties for backward compatibility for inputs
  51155. /**
  51156. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51157. */
  51158. get: function () {
  51159. var pointers = this.inputs.attached["pointers"];
  51160. if (pointers) {
  51161. return pointers.angularSensibilityX;
  51162. }
  51163. return 0;
  51164. },
  51165. set: function (value) {
  51166. var pointers = this.inputs.attached["pointers"];
  51167. if (pointers) {
  51168. pointers.angularSensibilityX = value;
  51169. }
  51170. },
  51171. enumerable: true,
  51172. configurable: true
  51173. });
  51174. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51175. /**
  51176. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51177. */
  51178. get: function () {
  51179. var pointers = this.inputs.attached["pointers"];
  51180. if (pointers) {
  51181. return pointers.angularSensibilityY;
  51182. }
  51183. return 0;
  51184. },
  51185. set: function (value) {
  51186. var pointers = this.inputs.attached["pointers"];
  51187. if (pointers) {
  51188. pointers.angularSensibilityY = value;
  51189. }
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51195. /**
  51196. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51197. */
  51198. get: function () {
  51199. var pointers = this.inputs.attached["pointers"];
  51200. if (pointers) {
  51201. return pointers.pinchPrecision;
  51202. }
  51203. return 0;
  51204. },
  51205. set: function (value) {
  51206. var pointers = this.inputs.attached["pointers"];
  51207. if (pointers) {
  51208. pointers.pinchPrecision = value;
  51209. }
  51210. },
  51211. enumerable: true,
  51212. configurable: true
  51213. });
  51214. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51215. /**
  51216. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51217. * It will be used instead of pinchDeltaPrecision if different from 0.
  51218. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51219. */
  51220. get: function () {
  51221. var pointers = this.inputs.attached["pointers"];
  51222. if (pointers) {
  51223. return pointers.pinchDeltaPercentage;
  51224. }
  51225. return 0;
  51226. },
  51227. set: function (value) {
  51228. var pointers = this.inputs.attached["pointers"];
  51229. if (pointers) {
  51230. pointers.pinchDeltaPercentage = value;
  51231. }
  51232. },
  51233. enumerable: true,
  51234. configurable: true
  51235. });
  51236. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51237. /**
  51238. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51239. */
  51240. get: function () {
  51241. var pointers = this.inputs.attached["pointers"];
  51242. if (pointers) {
  51243. return pointers.panningSensibility;
  51244. }
  51245. return 0;
  51246. },
  51247. set: function (value) {
  51248. var pointers = this.inputs.attached["pointers"];
  51249. if (pointers) {
  51250. pointers.panningSensibility = value;
  51251. }
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51257. /**
  51258. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51259. */
  51260. get: function () {
  51261. var keyboard = this.inputs.attached["keyboard"];
  51262. if (keyboard) {
  51263. return keyboard.keysUp;
  51264. }
  51265. return [];
  51266. },
  51267. set: function (value) {
  51268. var keyboard = this.inputs.attached["keyboard"];
  51269. if (keyboard) {
  51270. keyboard.keysUp = value;
  51271. }
  51272. },
  51273. enumerable: true,
  51274. configurable: true
  51275. });
  51276. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51277. /**
  51278. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51279. */
  51280. get: function () {
  51281. var keyboard = this.inputs.attached["keyboard"];
  51282. if (keyboard) {
  51283. return keyboard.keysDown;
  51284. }
  51285. return [];
  51286. },
  51287. set: function (value) {
  51288. var keyboard = this.inputs.attached["keyboard"];
  51289. if (keyboard) {
  51290. keyboard.keysDown = value;
  51291. }
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51297. /**
  51298. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51299. */
  51300. get: function () {
  51301. var keyboard = this.inputs.attached["keyboard"];
  51302. if (keyboard) {
  51303. return keyboard.keysLeft;
  51304. }
  51305. return [];
  51306. },
  51307. set: function (value) {
  51308. var keyboard = this.inputs.attached["keyboard"];
  51309. if (keyboard) {
  51310. keyboard.keysLeft = value;
  51311. }
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51317. /**
  51318. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51319. */
  51320. get: function () {
  51321. var keyboard = this.inputs.attached["keyboard"];
  51322. if (keyboard) {
  51323. return keyboard.keysRight;
  51324. }
  51325. return [];
  51326. },
  51327. set: function (value) {
  51328. var keyboard = this.inputs.attached["keyboard"];
  51329. if (keyboard) {
  51330. keyboard.keysRight = value;
  51331. }
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51337. /**
  51338. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51339. */
  51340. get: function () {
  51341. var mousewheel = this.inputs.attached["mousewheel"];
  51342. if (mousewheel) {
  51343. return mousewheel.wheelPrecision;
  51344. }
  51345. return 0;
  51346. },
  51347. set: function (value) {
  51348. var mousewheel = this.inputs.attached["mousewheel"];
  51349. if (mousewheel) {
  51350. mousewheel.wheelPrecision = value;
  51351. }
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51357. /**
  51358. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51359. * It will be used instead of pinchDeltaPrecision if different from 0.
  51360. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51361. */
  51362. get: function () {
  51363. var mousewheel = this.inputs.attached["mousewheel"];
  51364. if (mousewheel) {
  51365. return mousewheel.wheelDeltaPercentage;
  51366. }
  51367. return 0;
  51368. },
  51369. set: function (value) {
  51370. var mousewheel = this.inputs.attached["mousewheel"];
  51371. if (mousewheel) {
  51372. mousewheel.wheelDeltaPercentage = value;
  51373. }
  51374. },
  51375. enumerable: true,
  51376. configurable: true
  51377. });
  51378. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51379. /**
  51380. * Gets the bouncing behavior of the camera if it has been enabled.
  51381. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51382. */
  51383. get: function () {
  51384. return this._bouncingBehavior;
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51390. /**
  51391. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51392. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51393. */
  51394. get: function () {
  51395. return this._bouncingBehavior != null;
  51396. },
  51397. set: function (value) {
  51398. if (value === this.useBouncingBehavior) {
  51399. return;
  51400. }
  51401. if (value) {
  51402. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51403. this.addBehavior(this._bouncingBehavior);
  51404. }
  51405. else if (this._bouncingBehavior) {
  51406. this.removeBehavior(this._bouncingBehavior);
  51407. this._bouncingBehavior = null;
  51408. }
  51409. },
  51410. enumerable: true,
  51411. configurable: true
  51412. });
  51413. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51414. /**
  51415. * Gets the framing behavior of the camera if it has been enabled.
  51416. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51417. */
  51418. get: function () {
  51419. return this._framingBehavior;
  51420. },
  51421. enumerable: true,
  51422. configurable: true
  51423. });
  51424. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51425. /**
  51426. * Defines if the framing behavior of the camera is enabled on the camera.
  51427. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51428. */
  51429. get: function () {
  51430. return this._framingBehavior != null;
  51431. },
  51432. set: function (value) {
  51433. if (value === this.useFramingBehavior) {
  51434. return;
  51435. }
  51436. if (value) {
  51437. this._framingBehavior = new BABYLON.FramingBehavior();
  51438. this.addBehavior(this._framingBehavior);
  51439. }
  51440. else if (this._framingBehavior) {
  51441. this.removeBehavior(this._framingBehavior);
  51442. this._framingBehavior = null;
  51443. }
  51444. },
  51445. enumerable: true,
  51446. configurable: true
  51447. });
  51448. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51449. /**
  51450. * Gets the auto rotation behavior of the camera if it has been enabled.
  51451. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51452. */
  51453. get: function () {
  51454. return this._autoRotationBehavior;
  51455. },
  51456. enumerable: true,
  51457. configurable: true
  51458. });
  51459. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51460. /**
  51461. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51462. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51463. */
  51464. get: function () {
  51465. return this._autoRotationBehavior != null;
  51466. },
  51467. set: function (value) {
  51468. if (value === this.useAutoRotationBehavior) {
  51469. return;
  51470. }
  51471. if (value) {
  51472. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51473. this.addBehavior(this._autoRotationBehavior);
  51474. }
  51475. else if (this._autoRotationBehavior) {
  51476. this.removeBehavior(this._autoRotationBehavior);
  51477. this._autoRotationBehavior = null;
  51478. }
  51479. },
  51480. enumerable: true,
  51481. configurable: true
  51482. });
  51483. // Cache
  51484. /** @hidden */
  51485. ArcRotateCamera.prototype._initCache = function () {
  51486. _super.prototype._initCache.call(this);
  51487. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51488. this._cache.alpha = undefined;
  51489. this._cache.beta = undefined;
  51490. this._cache.radius = undefined;
  51491. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51492. };
  51493. /** @hidden */
  51494. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51495. if (!ignoreParentClass) {
  51496. _super.prototype._updateCache.call(this);
  51497. }
  51498. this._cache._target.copyFrom(this._getTargetPosition());
  51499. this._cache.alpha = this.alpha;
  51500. this._cache.beta = this.beta;
  51501. this._cache.radius = this.radius;
  51502. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51503. };
  51504. ArcRotateCamera.prototype._getTargetPosition = function () {
  51505. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51506. var pos = this._targetHost.getAbsolutePosition();
  51507. if (this._targetBoundingCenter) {
  51508. pos.addToRef(this._targetBoundingCenter, this._target);
  51509. }
  51510. else {
  51511. this._target.copyFrom(pos);
  51512. }
  51513. }
  51514. var lockedTargetPosition = this._getLockedTargetPosition();
  51515. if (lockedTargetPosition) {
  51516. return lockedTargetPosition;
  51517. }
  51518. return this._target;
  51519. };
  51520. /**
  51521. * Stores the current state of the camera (alpha, beta, radius and target)
  51522. * @returns the camera itself
  51523. */
  51524. ArcRotateCamera.prototype.storeState = function () {
  51525. this._storedAlpha = this.alpha;
  51526. this._storedBeta = this.beta;
  51527. this._storedRadius = this.radius;
  51528. this._storedTarget = this._getTargetPosition().clone();
  51529. return _super.prototype.storeState.call(this);
  51530. };
  51531. /**
  51532. * @hidden
  51533. * Restored camera state. You must call storeState() first
  51534. */
  51535. ArcRotateCamera.prototype._restoreStateValues = function () {
  51536. if (!_super.prototype._restoreStateValues.call(this)) {
  51537. return false;
  51538. }
  51539. this.alpha = this._storedAlpha;
  51540. this.beta = this._storedBeta;
  51541. this.radius = this._storedRadius;
  51542. this.setTarget(this._storedTarget.clone());
  51543. this.inertialAlphaOffset = 0;
  51544. this.inertialBetaOffset = 0;
  51545. this.inertialRadiusOffset = 0;
  51546. this.inertialPanningX = 0;
  51547. this.inertialPanningY = 0;
  51548. return true;
  51549. };
  51550. // Synchronized
  51551. /** @hidden */
  51552. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51553. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51554. return false;
  51555. }
  51556. return this._cache._target.equals(this._getTargetPosition())
  51557. && this._cache.alpha === this.alpha
  51558. && this._cache.beta === this.beta
  51559. && this._cache.radius === this.radius
  51560. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51561. };
  51562. /**
  51563. * Attached controls to the current camera.
  51564. * @param element Defines the element the controls should be listened from
  51565. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51566. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51567. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  51568. */
  51569. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  51570. var _this = this;
  51571. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  51572. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  51573. this._useCtrlForPanning = useCtrlForPanning;
  51574. this._panningMouseButton = panningMouseButton;
  51575. this.inputs.attachElement(element, noPreventDefault);
  51576. this._reset = function () {
  51577. _this.inertialAlphaOffset = 0;
  51578. _this.inertialBetaOffset = 0;
  51579. _this.inertialRadiusOffset = 0;
  51580. _this.inertialPanningX = 0;
  51581. _this.inertialPanningY = 0;
  51582. };
  51583. };
  51584. /**
  51585. * Detach the current controls from the camera.
  51586. * The camera will stop reacting to inputs.
  51587. * @param element Defines the element to stop listening the inputs from
  51588. */
  51589. ArcRotateCamera.prototype.detachControl = function (element) {
  51590. this.inputs.detachElement(element);
  51591. if (this._reset) {
  51592. this._reset();
  51593. }
  51594. };
  51595. /** @hidden */
  51596. ArcRotateCamera.prototype._checkInputs = function () {
  51597. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  51598. if (this._collisionTriggered) {
  51599. return;
  51600. }
  51601. this.inputs.checkInputs();
  51602. // Inertia
  51603. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  51604. var inertialAlphaOffset = this.inertialAlphaOffset;
  51605. if (this.beta <= 0) {
  51606. inertialAlphaOffset *= -1;
  51607. }
  51608. if (this.getScene().useRightHandedSystem) {
  51609. inertialAlphaOffset *= -1;
  51610. }
  51611. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  51612. inertialAlphaOffset *= -1;
  51613. }
  51614. this.alpha += inertialAlphaOffset;
  51615. this.beta += this.inertialBetaOffset;
  51616. this.radius -= this.inertialRadiusOffset;
  51617. this.inertialAlphaOffset *= this.inertia;
  51618. this.inertialBetaOffset *= this.inertia;
  51619. this.inertialRadiusOffset *= this.inertia;
  51620. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  51621. this.inertialAlphaOffset = 0;
  51622. }
  51623. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  51624. this.inertialBetaOffset = 0;
  51625. }
  51626. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  51627. this.inertialRadiusOffset = 0;
  51628. }
  51629. }
  51630. // Panning inertia
  51631. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  51632. if (!this._localDirection) {
  51633. this._localDirection = BABYLON.Vector3.Zero();
  51634. this._transformedDirection = BABYLON.Vector3.Zero();
  51635. }
  51636. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  51637. this._localDirection.multiplyInPlace(this.panningAxis);
  51638. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  51639. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  51640. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  51641. if (!this.panningAxis.y) {
  51642. this._transformedDirection.y = 0;
  51643. }
  51644. if (!this._targetHost) {
  51645. if (this.panningDistanceLimit) {
  51646. this._transformedDirection.addInPlace(this._target);
  51647. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  51648. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  51649. this._target.copyFrom(this._transformedDirection);
  51650. }
  51651. }
  51652. else {
  51653. this._target.addInPlace(this._transformedDirection);
  51654. }
  51655. }
  51656. this.inertialPanningX *= this.panningInertia;
  51657. this.inertialPanningY *= this.panningInertia;
  51658. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  51659. this.inertialPanningX = 0;
  51660. }
  51661. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  51662. this.inertialPanningY = 0;
  51663. }
  51664. }
  51665. // Limits
  51666. this._checkLimits();
  51667. _super.prototype._checkInputs.call(this);
  51668. };
  51669. ArcRotateCamera.prototype._checkLimits = function () {
  51670. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  51671. if (this.allowUpsideDown && this.beta > Math.PI) {
  51672. this.beta = this.beta - (2 * Math.PI);
  51673. }
  51674. }
  51675. else {
  51676. if (this.beta < this.lowerBetaLimit) {
  51677. this.beta = this.lowerBetaLimit;
  51678. }
  51679. }
  51680. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  51681. if (this.allowUpsideDown && this.beta < -Math.PI) {
  51682. this.beta = this.beta + (2 * Math.PI);
  51683. }
  51684. }
  51685. else {
  51686. if (this.beta > this.upperBetaLimit) {
  51687. this.beta = this.upperBetaLimit;
  51688. }
  51689. }
  51690. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  51691. this.alpha = this.lowerAlphaLimit;
  51692. }
  51693. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  51694. this.alpha = this.upperAlphaLimit;
  51695. }
  51696. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  51697. this.radius = this.lowerRadiusLimit;
  51698. }
  51699. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  51700. this.radius = this.upperRadiusLimit;
  51701. }
  51702. };
  51703. /**
  51704. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  51705. */
  51706. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  51707. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  51708. this.radius = this._computationVector.length();
  51709. if (this.radius === 0) {
  51710. this.radius = 0.0001; // Just to avoid division by zero
  51711. }
  51712. // Alpha
  51713. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  51714. if (this._computationVector.z < 0) {
  51715. this.alpha = 2 * Math.PI - this.alpha;
  51716. }
  51717. // Beta
  51718. this.beta = Math.acos(this._computationVector.y / this.radius);
  51719. this._checkLimits();
  51720. };
  51721. /**
  51722. * Use a position to define the current camera related information like aplha, beta and radius
  51723. * @param position Defines the position to set the camera at
  51724. */
  51725. ArcRotateCamera.prototype.setPosition = function (position) {
  51726. if (this.position.equals(position)) {
  51727. return;
  51728. }
  51729. this.position.copyFrom(position);
  51730. this.rebuildAnglesAndRadius();
  51731. };
  51732. /**
  51733. * Defines the target the camera should look at.
  51734. * This will automatically adapt alpha beta and radius to fit within the new target.
  51735. * @param target Defines the new target as a Vector or a mesh
  51736. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  51737. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  51738. */
  51739. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  51740. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  51741. if (allowSamePosition === void 0) { allowSamePosition = false; }
  51742. if (target.getBoundingInfo) {
  51743. if (toBoundingCenter) {
  51744. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  51745. }
  51746. else {
  51747. this._targetBoundingCenter = null;
  51748. }
  51749. this._targetHost = target;
  51750. this._target = this._getTargetPosition();
  51751. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  51752. }
  51753. else {
  51754. var newTarget = target;
  51755. var currentTarget = this._getTargetPosition();
  51756. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  51757. return;
  51758. }
  51759. this._targetHost = null;
  51760. this._target = newTarget;
  51761. this._targetBoundingCenter = null;
  51762. this.onMeshTargetChangedObservable.notifyObservers(null);
  51763. }
  51764. this.rebuildAnglesAndRadius();
  51765. };
  51766. /** @hidden */
  51767. ArcRotateCamera.prototype._getViewMatrix = function () {
  51768. // Compute
  51769. var cosa = Math.cos(this.alpha);
  51770. var sina = Math.sin(this.alpha);
  51771. var cosb = Math.cos(this.beta);
  51772. var sinb = Math.sin(this.beta);
  51773. if (sinb === 0) {
  51774. sinb = 0.0001;
  51775. }
  51776. var target = this._getTargetPosition();
  51777. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  51778. target.addToRef(this._computationVector, this._newPosition);
  51779. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  51780. if (!this._collider) {
  51781. this._collider = new BABYLON.Collider();
  51782. }
  51783. this._collider._radius = this.collisionRadius;
  51784. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  51785. this._collisionTriggered = true;
  51786. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  51787. }
  51788. else {
  51789. this.position.copyFrom(this._newPosition);
  51790. var up = this.upVector;
  51791. if (this.allowUpsideDown && sinb < 0) {
  51792. up = up.clone();
  51793. up = up.negate();
  51794. }
  51795. this._computeViewMatrix(this.position, target, up);
  51796. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  51797. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  51798. }
  51799. this._currentTarget = target;
  51800. return this._viewMatrix;
  51801. };
  51802. /**
  51803. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  51804. * @param meshes Defines the mesh to zoom on
  51805. * @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)
  51806. */
  51807. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  51808. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51809. meshes = meshes || this.getScene().meshes;
  51810. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  51811. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  51812. this.radius = distance * this.zoomOnFactor;
  51813. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  51814. };
  51815. /**
  51816. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  51817. * The target will be changed but the radius
  51818. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  51819. * @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)
  51820. */
  51821. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  51822. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51823. var meshesOrMinMaxVector;
  51824. var distance;
  51825. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  51826. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  51827. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  51828. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  51829. }
  51830. else { //minMaxVector and distance
  51831. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  51832. meshesOrMinMaxVector = minMaxVectorAndDistance;
  51833. distance = minMaxVectorAndDistance.distance;
  51834. }
  51835. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  51836. if (!doNotUpdateMaxZ) {
  51837. this.maxZ = distance * 2;
  51838. }
  51839. };
  51840. /**
  51841. * @override
  51842. * Override Camera.createRigCamera
  51843. */
  51844. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  51845. var alphaShift = 0;
  51846. switch (this.cameraRigMode) {
  51847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51848. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51849. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51850. case BABYLON.Camera.RIG_MODE_VR:
  51851. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  51852. break;
  51853. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51854. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  51855. break;
  51856. }
  51857. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  51858. rigCam._cameraRigParams = {};
  51859. return rigCam;
  51860. };
  51861. /**
  51862. * @hidden
  51863. * @override
  51864. * Override Camera._updateRigCameras
  51865. */
  51866. ArcRotateCamera.prototype._updateRigCameras = function () {
  51867. var camLeft = this._rigCameras[0];
  51868. var camRight = this._rigCameras[1];
  51869. camLeft.beta = camRight.beta = this.beta;
  51870. camLeft.radius = camRight.radius = this.radius;
  51871. switch (this.cameraRigMode) {
  51872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51873. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51874. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51875. case BABYLON.Camera.RIG_MODE_VR:
  51876. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51877. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51878. break;
  51879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51880. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51881. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51882. break;
  51883. }
  51884. _super.prototype._updateRigCameras.call(this);
  51885. };
  51886. /**
  51887. * Destroy the camera and release the current resources hold by it.
  51888. */
  51889. ArcRotateCamera.prototype.dispose = function () {
  51890. this.inputs.clear();
  51891. _super.prototype.dispose.call(this);
  51892. };
  51893. /**
  51894. * Gets the current object class name.
  51895. * @return the class name
  51896. */
  51897. ArcRotateCamera.prototype.getClassName = function () {
  51898. return "ArcRotateCamera";
  51899. };
  51900. __decorate([
  51901. BABYLON.serialize()
  51902. ], ArcRotateCamera.prototype, "alpha", void 0);
  51903. __decorate([
  51904. BABYLON.serialize()
  51905. ], ArcRotateCamera.prototype, "beta", void 0);
  51906. __decorate([
  51907. BABYLON.serialize()
  51908. ], ArcRotateCamera.prototype, "radius", void 0);
  51909. __decorate([
  51910. BABYLON.serializeAsVector3("target")
  51911. ], ArcRotateCamera.prototype, "_target", void 0);
  51912. __decorate([
  51913. BABYLON.serialize()
  51914. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  51915. __decorate([
  51916. BABYLON.serialize()
  51917. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  51918. __decorate([
  51919. BABYLON.serialize()
  51920. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  51921. __decorate([
  51922. BABYLON.serialize()
  51923. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  51924. __decorate([
  51925. BABYLON.serialize()
  51926. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  51927. __decorate([
  51928. BABYLON.serialize()
  51929. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  51930. __decorate([
  51931. BABYLON.serialize()
  51932. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  51933. __decorate([
  51934. BABYLON.serialize()
  51935. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  51936. __decorate([
  51937. BABYLON.serialize()
  51938. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  51939. __decorate([
  51940. BABYLON.serialize()
  51941. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  51942. __decorate([
  51943. BABYLON.serialize()
  51944. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  51945. __decorate([
  51946. BABYLON.serialize()
  51947. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  51948. __decorate([
  51949. BABYLON.serialize()
  51950. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  51951. __decorate([
  51952. BABYLON.serializeAsVector3()
  51953. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  51954. __decorate([
  51955. BABYLON.serialize()
  51956. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  51957. __decorate([
  51958. BABYLON.serialize()
  51959. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  51960. __decorate([
  51961. BABYLON.serialize()
  51962. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  51963. __decorate([
  51964. BABYLON.serialize()
  51965. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  51966. __decorate([
  51967. BABYLON.serialize()
  51968. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  51969. return ArcRotateCamera;
  51970. }(BABYLON.TargetCamera));
  51971. BABYLON.ArcRotateCamera = ArcRotateCamera;
  51972. })(BABYLON || (BABYLON = {}));
  51973. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  51974. var BABYLON;
  51975. (function (BABYLON) {
  51976. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  51977. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  51978. });
  51979. /**
  51980. * The HemisphericLight simulates the ambient environment light,
  51981. * so the passed direction is the light reflection direction, not the incoming direction.
  51982. */
  51983. var HemisphericLight = /** @class */ (function (_super) {
  51984. __extends(HemisphericLight, _super);
  51985. /**
  51986. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  51987. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  51988. * The HemisphericLight can't cast shadows.
  51989. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51990. * @param name The friendly name of the light
  51991. * @param direction The direction of the light reflection
  51992. * @param scene The scene the light belongs to
  51993. */
  51994. function HemisphericLight(name, direction, scene) {
  51995. var _this = _super.call(this, name, scene) || this;
  51996. /**
  51997. * The groundColor is the light in the opposite direction to the one specified during creation.
  51998. * 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.
  51999. */
  52000. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52001. _this.direction = direction || BABYLON.Vector3.Up();
  52002. return _this;
  52003. }
  52004. HemisphericLight.prototype._buildUniformLayout = function () {
  52005. this._uniformBuffer.addUniform("vLightData", 4);
  52006. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52007. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52008. this._uniformBuffer.addUniform("vLightGround", 3);
  52009. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52010. this._uniformBuffer.addUniform("depthValues", 2);
  52011. this._uniformBuffer.create();
  52012. };
  52013. /**
  52014. * Returns the string "HemisphericLight".
  52015. * @return The class name
  52016. */
  52017. HemisphericLight.prototype.getClassName = function () {
  52018. return "HemisphericLight";
  52019. };
  52020. /**
  52021. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52022. * Returns the updated direction.
  52023. * @param target The target the direction should point to
  52024. * @return The computed direction
  52025. */
  52026. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52027. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52028. return this.direction;
  52029. };
  52030. /**
  52031. * Returns the shadow generator associated to the light.
  52032. * @returns Always null for hemispheric lights because it does not support shadows.
  52033. */
  52034. HemisphericLight.prototype.getShadowGenerator = function () {
  52035. return null;
  52036. };
  52037. /**
  52038. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52039. * @param effect The effect to update
  52040. * @param lightIndex The index of the light in the effect to update
  52041. * @returns The hemispheric light
  52042. */
  52043. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52044. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52045. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52046. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52047. return this;
  52048. };
  52049. /**
  52050. * Computes the world matrix of the node
  52051. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52052. * @param useWasUpdatedFlag defines a reserved property
  52053. * @returns the world matrix
  52054. */
  52055. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52056. if (!this._worldMatrix) {
  52057. this._worldMatrix = BABYLON.Matrix.Identity();
  52058. }
  52059. return this._worldMatrix;
  52060. };
  52061. /**
  52062. * Returns the integer 3.
  52063. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52064. */
  52065. HemisphericLight.prototype.getTypeID = function () {
  52066. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52067. };
  52068. /**
  52069. * Prepares the list of defines specific to the light type.
  52070. * @param defines the list of defines
  52071. * @param lightIndex defines the index of the light for the effect
  52072. */
  52073. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52074. defines["HEMILIGHT" + lightIndex] = true;
  52075. };
  52076. __decorate([
  52077. BABYLON.serializeAsColor3()
  52078. ], HemisphericLight.prototype, "groundColor", void 0);
  52079. __decorate([
  52080. BABYLON.serializeAsVector3()
  52081. ], HemisphericLight.prototype, "direction", void 0);
  52082. return HemisphericLight;
  52083. }(BABYLON.Light));
  52084. BABYLON.HemisphericLight = HemisphericLight;
  52085. })(BABYLON || (BABYLON = {}));
  52086. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52087. var BABYLON;
  52088. (function (BABYLON) {
  52089. /**
  52090. * Base implementation IShadowLight
  52091. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52092. */
  52093. var ShadowLight = /** @class */ (function (_super) {
  52094. __extends(ShadowLight, _super);
  52095. function ShadowLight() {
  52096. var _this = _super !== null && _super.apply(this, arguments) || this;
  52097. _this._needProjectionMatrixCompute = true;
  52098. return _this;
  52099. }
  52100. ShadowLight.prototype._setPosition = function (value) {
  52101. this._position = value;
  52102. };
  52103. Object.defineProperty(ShadowLight.prototype, "position", {
  52104. /**
  52105. * Sets the position the shadow will be casted from. Also use as the light position for both
  52106. * point and spot lights.
  52107. */
  52108. get: function () {
  52109. return this._position;
  52110. },
  52111. /**
  52112. * Sets the position the shadow will be casted from. Also use as the light position for both
  52113. * point and spot lights.
  52114. */
  52115. set: function (value) {
  52116. this._setPosition(value);
  52117. },
  52118. enumerable: true,
  52119. configurable: true
  52120. });
  52121. ShadowLight.prototype._setDirection = function (value) {
  52122. this._direction = value;
  52123. };
  52124. Object.defineProperty(ShadowLight.prototype, "direction", {
  52125. /**
  52126. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52127. * Also use as the light direction on spot and directional lights.
  52128. */
  52129. get: function () {
  52130. return this._direction;
  52131. },
  52132. /**
  52133. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52134. * Also use as the light direction on spot and directional lights.
  52135. */
  52136. set: function (value) {
  52137. this._setDirection(value);
  52138. },
  52139. enumerable: true,
  52140. configurable: true
  52141. });
  52142. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52143. /**
  52144. * Gets the shadow projection clipping minimum z value.
  52145. */
  52146. get: function () {
  52147. return this._shadowMinZ;
  52148. },
  52149. /**
  52150. * Sets the shadow projection clipping minimum z value.
  52151. */
  52152. set: function (value) {
  52153. this._shadowMinZ = value;
  52154. this.forceProjectionMatrixCompute();
  52155. },
  52156. enumerable: true,
  52157. configurable: true
  52158. });
  52159. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52160. /**
  52161. * Sets the shadow projection clipping maximum z value.
  52162. */
  52163. get: function () {
  52164. return this._shadowMaxZ;
  52165. },
  52166. /**
  52167. * Gets the shadow projection clipping maximum z value.
  52168. */
  52169. set: function (value) {
  52170. this._shadowMaxZ = value;
  52171. this.forceProjectionMatrixCompute();
  52172. },
  52173. enumerable: true,
  52174. configurable: true
  52175. });
  52176. /**
  52177. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52178. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52179. */
  52180. ShadowLight.prototype.computeTransformedInformation = function () {
  52181. if (this.parent && this.parent.getWorldMatrix) {
  52182. if (!this.transformedPosition) {
  52183. this.transformedPosition = BABYLON.Vector3.Zero();
  52184. }
  52185. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52186. // In case the direction is present.
  52187. if (this.direction) {
  52188. if (!this.transformedDirection) {
  52189. this.transformedDirection = BABYLON.Vector3.Zero();
  52190. }
  52191. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52192. }
  52193. return true;
  52194. }
  52195. return false;
  52196. };
  52197. /**
  52198. * Return the depth scale used for the shadow map.
  52199. * @returns the depth scale.
  52200. */
  52201. ShadowLight.prototype.getDepthScale = function () {
  52202. return 50.0;
  52203. };
  52204. /**
  52205. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52206. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52207. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52208. */
  52209. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52210. return this.transformedDirection ? this.transformedDirection : this.direction;
  52211. };
  52212. /**
  52213. * Returns the ShadowLight absolute position in the World.
  52214. * @returns the position vector in world space
  52215. */
  52216. ShadowLight.prototype.getAbsolutePosition = function () {
  52217. return this.transformedPosition ? this.transformedPosition : this.position;
  52218. };
  52219. /**
  52220. * Sets the ShadowLight direction toward the passed target.
  52221. * @param target The point tot target in local space
  52222. * @returns the updated ShadowLight direction
  52223. */
  52224. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52225. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52226. return this.direction;
  52227. };
  52228. /**
  52229. * Returns the light rotation in euler definition.
  52230. * @returns the x y z rotation in local space.
  52231. */
  52232. ShadowLight.prototype.getRotation = function () {
  52233. this.direction.normalize();
  52234. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52235. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52236. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52237. };
  52238. /**
  52239. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52240. * @returns true if a cube texture needs to be use
  52241. */
  52242. ShadowLight.prototype.needCube = function () {
  52243. return false;
  52244. };
  52245. /**
  52246. * Detects if the projection matrix requires to be recomputed this frame.
  52247. * @returns true if it requires to be recomputed otherwise, false.
  52248. */
  52249. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52250. return this._needProjectionMatrixCompute;
  52251. };
  52252. /**
  52253. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52254. */
  52255. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52256. this._needProjectionMatrixCompute = true;
  52257. };
  52258. /** @hidden */
  52259. ShadowLight.prototype._initCache = function () {
  52260. _super.prototype._initCache.call(this);
  52261. this._cache.position = BABYLON.Vector3.Zero();
  52262. };
  52263. /** @hidden */
  52264. ShadowLight.prototype._isSynchronized = function () {
  52265. if (!this._cache.position.equals(this.position)) {
  52266. return false;
  52267. }
  52268. return true;
  52269. };
  52270. /**
  52271. * Computes the world matrix of the node
  52272. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52273. * @returns the world matrix
  52274. */
  52275. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52276. if (!force && this.isSynchronized()) {
  52277. this._currentRenderId = this.getScene().getRenderId();
  52278. return this._worldMatrix;
  52279. }
  52280. this._updateCache();
  52281. this._cache.position.copyFrom(this.position);
  52282. if (!this._worldMatrix) {
  52283. this._worldMatrix = BABYLON.Matrix.Identity();
  52284. }
  52285. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52286. if (this.parent && this.parent.getWorldMatrix) {
  52287. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52288. this._markSyncedWithParent();
  52289. }
  52290. // Cache the determinant
  52291. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52292. return this._worldMatrix;
  52293. };
  52294. /**
  52295. * Gets the minZ used for shadow according to both the scene and the light.
  52296. * @param activeCamera The camera we are returning the min for
  52297. * @returns the depth min z
  52298. */
  52299. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52300. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52301. };
  52302. /**
  52303. * Gets the maxZ used for shadow according to both the scene and the light.
  52304. * @param activeCamera The camera we are returning the max for
  52305. * @returns the depth max z
  52306. */
  52307. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52308. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52309. };
  52310. /**
  52311. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52312. * @param matrix The materix to updated with the projection information
  52313. * @param viewMatrix The transform matrix of the light
  52314. * @param renderList The list of mesh to render in the map
  52315. * @returns The current light
  52316. */
  52317. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52318. if (this.customProjectionMatrixBuilder) {
  52319. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52320. }
  52321. else {
  52322. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52323. }
  52324. return this;
  52325. };
  52326. __decorate([
  52327. BABYLON.serializeAsVector3()
  52328. ], ShadowLight.prototype, "position", null);
  52329. __decorate([
  52330. BABYLON.serializeAsVector3()
  52331. ], ShadowLight.prototype, "direction", null);
  52332. __decorate([
  52333. BABYLON.serialize()
  52334. ], ShadowLight.prototype, "shadowMinZ", null);
  52335. __decorate([
  52336. BABYLON.serialize()
  52337. ], ShadowLight.prototype, "shadowMaxZ", null);
  52338. return ShadowLight;
  52339. }(BABYLON.Light));
  52340. BABYLON.ShadowLight = ShadowLight;
  52341. })(BABYLON || (BABYLON = {}));
  52342. //# sourceMappingURL=babylon.shadowLight.js.map
  52343. var BABYLON;
  52344. (function (BABYLON) {
  52345. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52346. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52347. });
  52348. /**
  52349. * A point light is a light defined by an unique point in world space.
  52350. * The light is emitted in every direction from this point.
  52351. * A good example of a point light is a standard light bulb.
  52352. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52353. */
  52354. var PointLight = /** @class */ (function (_super) {
  52355. __extends(PointLight, _super);
  52356. /**
  52357. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52358. * A PointLight emits the light in every direction.
  52359. * It can cast shadows.
  52360. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52361. * ```javascript
  52362. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52363. * ```
  52364. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52365. * @param name The light friendly name
  52366. * @param position The position of the point light in the scene
  52367. * @param scene The scene the lights belongs to
  52368. */
  52369. function PointLight(name, position, scene) {
  52370. var _this = _super.call(this, name, scene) || this;
  52371. _this._shadowAngle = Math.PI / 2;
  52372. _this.position = position;
  52373. return _this;
  52374. }
  52375. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52376. /**
  52377. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52378. * This specifies what angle the shadow will use to be created.
  52379. *
  52380. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52381. */
  52382. get: function () {
  52383. return this._shadowAngle;
  52384. },
  52385. /**
  52386. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52387. * This specifies what angle the shadow will use to be created.
  52388. *
  52389. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52390. */
  52391. set: function (value) {
  52392. this._shadowAngle = value;
  52393. this.forceProjectionMatrixCompute();
  52394. },
  52395. enumerable: true,
  52396. configurable: true
  52397. });
  52398. Object.defineProperty(PointLight.prototype, "direction", {
  52399. /**
  52400. * Gets the direction if it has been set.
  52401. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52402. */
  52403. get: function () {
  52404. return this._direction;
  52405. },
  52406. /**
  52407. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52408. */
  52409. set: function (value) {
  52410. var previousNeedCube = this.needCube();
  52411. this._direction = value;
  52412. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52413. this._shadowGenerator.recreateShadowMap();
  52414. }
  52415. },
  52416. enumerable: true,
  52417. configurable: true
  52418. });
  52419. /**
  52420. * Returns the string "PointLight"
  52421. * @returns the class name
  52422. */
  52423. PointLight.prototype.getClassName = function () {
  52424. return "PointLight";
  52425. };
  52426. /**
  52427. * Returns the integer 0.
  52428. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52429. */
  52430. PointLight.prototype.getTypeID = function () {
  52431. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52432. };
  52433. /**
  52434. * Specifies wether or not the shadowmap should be a cube texture.
  52435. * @returns true if the shadowmap needs to be a cube texture.
  52436. */
  52437. PointLight.prototype.needCube = function () {
  52438. return !this.direction;
  52439. };
  52440. /**
  52441. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52442. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52443. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52444. */
  52445. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52446. if (this.direction) {
  52447. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52448. }
  52449. else {
  52450. switch (faceIndex) {
  52451. case 0:
  52452. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52453. case 1:
  52454. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52455. case 2:
  52456. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52457. case 3:
  52458. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52459. case 4:
  52460. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52461. case 5:
  52462. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52463. }
  52464. }
  52465. return BABYLON.Vector3.Zero();
  52466. };
  52467. /**
  52468. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52469. * - fov = PI / 2
  52470. * - aspect ratio : 1.0
  52471. * - z-near and far equal to the active camera minZ and maxZ.
  52472. * Returns the PointLight.
  52473. */
  52474. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52475. var activeCamera = this.getScene().activeCamera;
  52476. if (!activeCamera) {
  52477. return;
  52478. }
  52479. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52480. };
  52481. PointLight.prototype._buildUniformLayout = function () {
  52482. this._uniformBuffer.addUniform("vLightData", 4);
  52483. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52484. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52485. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52486. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52487. this._uniformBuffer.addUniform("depthValues", 2);
  52488. this._uniformBuffer.create();
  52489. };
  52490. /**
  52491. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52492. * @param effect The effect to update
  52493. * @param lightIndex The index of the light in the effect to update
  52494. * @returns The point light
  52495. */
  52496. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52497. if (this.computeTransformedInformation()) {
  52498. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52499. }
  52500. else {
  52501. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52502. }
  52503. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52504. return this;
  52505. };
  52506. /**
  52507. * Prepares the list of defines specific to the light type.
  52508. * @param defines the list of defines
  52509. * @param lightIndex defines the index of the light for the effect
  52510. */
  52511. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52512. defines["POINTLIGHT" + lightIndex] = true;
  52513. };
  52514. __decorate([
  52515. BABYLON.serialize()
  52516. ], PointLight.prototype, "shadowAngle", null);
  52517. return PointLight;
  52518. }(BABYLON.ShadowLight));
  52519. BABYLON.PointLight = PointLight;
  52520. })(BABYLON || (BABYLON = {}));
  52521. //# sourceMappingURL=babylon.pointLight.js.map
  52522. var BABYLON;
  52523. (function (BABYLON) {
  52524. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52525. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52526. });
  52527. /**
  52528. * A directional light is defined by a direction (what a surprise!).
  52529. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52530. * 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.
  52531. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52532. */
  52533. var DirectionalLight = /** @class */ (function (_super) {
  52534. __extends(DirectionalLight, _super);
  52535. /**
  52536. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52537. * The directional light is emitted from everywhere in the given direction.
  52538. * It can cast shadows.
  52539. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52540. * @param name The friendly name of the light
  52541. * @param direction The direction of the light
  52542. * @param scene The scene the light belongs to
  52543. */
  52544. function DirectionalLight(name, direction, scene) {
  52545. var _this = _super.call(this, name, scene) || this;
  52546. _this._shadowFrustumSize = 0;
  52547. _this._shadowOrthoScale = 0.1;
  52548. /**
  52549. * Automatically compute the projection matrix to best fit (including all the casters)
  52550. * on each frame.
  52551. */
  52552. _this.autoUpdateExtends = true;
  52553. // Cache
  52554. _this._orthoLeft = Number.MAX_VALUE;
  52555. _this._orthoRight = Number.MIN_VALUE;
  52556. _this._orthoTop = Number.MIN_VALUE;
  52557. _this._orthoBottom = Number.MAX_VALUE;
  52558. _this.position = direction.scale(-1.0);
  52559. _this.direction = direction;
  52560. return _this;
  52561. }
  52562. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52563. /**
  52564. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52565. */
  52566. get: function () {
  52567. return this._shadowFrustumSize;
  52568. },
  52569. /**
  52570. * Specifies a fix frustum size for the shadow generation.
  52571. */
  52572. set: function (value) {
  52573. this._shadowFrustumSize = value;
  52574. this.forceProjectionMatrixCompute();
  52575. },
  52576. enumerable: true,
  52577. configurable: true
  52578. });
  52579. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  52580. /**
  52581. * Gets the shadow projection scale against the optimal computed one.
  52582. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52583. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52584. */
  52585. get: function () {
  52586. return this._shadowOrthoScale;
  52587. },
  52588. /**
  52589. * Sets the shadow projection scale against the optimal computed one.
  52590. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52591. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52592. */
  52593. set: function (value) {
  52594. this._shadowOrthoScale = value;
  52595. this.forceProjectionMatrixCompute();
  52596. },
  52597. enumerable: true,
  52598. configurable: true
  52599. });
  52600. /**
  52601. * Returns the string "DirectionalLight".
  52602. * @return The class name
  52603. */
  52604. DirectionalLight.prototype.getClassName = function () {
  52605. return "DirectionalLight";
  52606. };
  52607. /**
  52608. * Returns the integer 1.
  52609. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52610. */
  52611. DirectionalLight.prototype.getTypeID = function () {
  52612. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  52613. };
  52614. /**
  52615. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  52616. * Returns the DirectionalLight Shadow projection matrix.
  52617. */
  52618. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52619. if (this.shadowFrustumSize > 0) {
  52620. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  52621. }
  52622. else {
  52623. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52624. }
  52625. };
  52626. /**
  52627. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  52628. * Returns the DirectionalLight Shadow projection matrix.
  52629. */
  52630. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  52631. var activeCamera = this.getScene().activeCamera;
  52632. if (!activeCamera) {
  52633. return;
  52634. }
  52635. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  52636. };
  52637. /**
  52638. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  52639. * Returns the DirectionalLight Shadow projection matrix.
  52640. */
  52641. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52642. var activeCamera = this.getScene().activeCamera;
  52643. if (!activeCamera) {
  52644. return;
  52645. }
  52646. // Check extends
  52647. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  52648. var tempVector3 = BABYLON.Vector3.Zero();
  52649. this._orthoLeft = Number.MAX_VALUE;
  52650. this._orthoRight = Number.MIN_VALUE;
  52651. this._orthoTop = Number.MIN_VALUE;
  52652. this._orthoBottom = Number.MAX_VALUE;
  52653. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  52654. var mesh = renderList[meshIndex];
  52655. if (!mesh) {
  52656. continue;
  52657. }
  52658. var boundingInfo = mesh.getBoundingInfo();
  52659. var boundingBox = boundingInfo.boundingBox;
  52660. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  52661. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  52662. if (tempVector3.x < this._orthoLeft) {
  52663. this._orthoLeft = tempVector3.x;
  52664. }
  52665. if (tempVector3.y < this._orthoBottom) {
  52666. this._orthoBottom = tempVector3.y;
  52667. }
  52668. if (tempVector3.x > this._orthoRight) {
  52669. this._orthoRight = tempVector3.x;
  52670. }
  52671. if (tempVector3.y > this._orthoTop) {
  52672. this._orthoTop = tempVector3.y;
  52673. }
  52674. }
  52675. }
  52676. }
  52677. var xOffset = this._orthoRight - this._orthoLeft;
  52678. var yOffset = this._orthoTop - this._orthoBottom;
  52679. 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);
  52680. };
  52681. DirectionalLight.prototype._buildUniformLayout = function () {
  52682. this._uniformBuffer.addUniform("vLightData", 4);
  52683. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52684. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52685. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52686. this._uniformBuffer.addUniform("depthValues", 2);
  52687. this._uniformBuffer.create();
  52688. };
  52689. /**
  52690. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  52691. * @param effect The effect to update
  52692. * @param lightIndex The index of the light in the effect to update
  52693. * @returns The directional light
  52694. */
  52695. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  52696. if (this.computeTransformedInformation()) {
  52697. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  52698. return this;
  52699. }
  52700. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  52701. return this;
  52702. };
  52703. /**
  52704. * Gets the minZ used for shadow according to both the scene and the light.
  52705. *
  52706. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52707. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52708. * @param activeCamera The camera we are returning the min for
  52709. * @returns the depth min z
  52710. */
  52711. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  52712. return 1;
  52713. };
  52714. /**
  52715. * Gets the maxZ used for shadow according to both the scene and the light.
  52716. *
  52717. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52718. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52719. * @param activeCamera The camera we are returning the max for
  52720. * @returns the depth max z
  52721. */
  52722. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  52723. return 1;
  52724. };
  52725. /**
  52726. * Prepares the list of defines specific to the light type.
  52727. * @param defines the list of defines
  52728. * @param lightIndex defines the index of the light for the effect
  52729. */
  52730. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52731. defines["DIRLIGHT" + lightIndex] = true;
  52732. };
  52733. __decorate([
  52734. BABYLON.serialize()
  52735. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  52736. __decorate([
  52737. BABYLON.serialize()
  52738. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  52739. __decorate([
  52740. BABYLON.serialize()
  52741. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  52742. return DirectionalLight;
  52743. }(BABYLON.ShadowLight));
  52744. BABYLON.DirectionalLight = DirectionalLight;
  52745. })(BABYLON || (BABYLON = {}));
  52746. //# sourceMappingURL=babylon.directionalLight.js.map
  52747. var BABYLON;
  52748. (function (BABYLON) {
  52749. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  52750. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  52751. });
  52752. /**
  52753. * A spot light is defined by a position, a direction, an angle, and an exponent.
  52754. * These values define a cone of light starting from the position, emitting toward the direction.
  52755. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  52756. * and the exponent defines the speed of the decay of the light with distance (reach).
  52757. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52758. */
  52759. var SpotLight = /** @class */ (function (_super) {
  52760. __extends(SpotLight, _super);
  52761. /**
  52762. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  52763. * It can cast shadows.
  52764. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52765. * @param name The light friendly name
  52766. * @param position The position of the spot light in the scene
  52767. * @param direction The direction of the light in the scene
  52768. * @param angle The cone angle of the light in Radians
  52769. * @param exponent The light decay speed with the distance from the emission spot
  52770. * @param scene The scene the lights belongs to
  52771. */
  52772. function SpotLight(name, position, direction, angle, exponent, scene) {
  52773. var _this = _super.call(this, name, scene) || this;
  52774. _this._innerAngle = 0;
  52775. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  52776. _this._projectionTextureLightNear = 1e-6;
  52777. _this._projectionTextureLightFar = 1000.0;
  52778. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  52779. _this._projectionTextureViewLightDirty = true;
  52780. _this._projectionTextureProjectionLightDirty = true;
  52781. _this._projectionTextureDirty = true;
  52782. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  52783. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  52784. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  52785. _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);
  52786. _this.position = position;
  52787. _this.direction = direction;
  52788. _this.angle = angle;
  52789. _this.exponent = exponent;
  52790. return _this;
  52791. }
  52792. Object.defineProperty(SpotLight.prototype, "angle", {
  52793. /**
  52794. * Gets the cone angle of the spot light in Radians.
  52795. */
  52796. get: function () {
  52797. return this._angle;
  52798. },
  52799. /**
  52800. * Sets the cone angle of the spot light in Radians.
  52801. */
  52802. set: function (value) {
  52803. this._angle = value;
  52804. this._cosHalfAngle = Math.cos(value * 0.5);
  52805. this._projectionTextureProjectionLightDirty = true;
  52806. this.forceProjectionMatrixCompute();
  52807. this._computeAngleValues();
  52808. },
  52809. enumerable: true,
  52810. configurable: true
  52811. });
  52812. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  52813. /**
  52814. * Only used in gltf falloff mode, this defines the angle where
  52815. * the directional falloff will start before cutting at angle which could be seen
  52816. * as outer angle.
  52817. */
  52818. get: function () {
  52819. return this._innerAngle;
  52820. },
  52821. /**
  52822. * Only used in gltf falloff mode, this defines the angle where
  52823. * the directional falloff will start before cutting at angle which could be seen
  52824. * as outer angle.
  52825. */
  52826. set: function (value) {
  52827. this._innerAngle = value;
  52828. this._computeAngleValues();
  52829. },
  52830. enumerable: true,
  52831. configurable: true
  52832. });
  52833. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  52834. /**
  52835. * Allows scaling the angle of the light for shadow generation only.
  52836. */
  52837. get: function () {
  52838. return this._shadowAngleScale;
  52839. },
  52840. /**
  52841. * Allows scaling the angle of the light for shadow generation only.
  52842. */
  52843. set: function (value) {
  52844. this._shadowAngleScale = value;
  52845. this.forceProjectionMatrixCompute();
  52846. },
  52847. enumerable: true,
  52848. configurable: true
  52849. });
  52850. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  52851. /**
  52852. * Allows reading the projecton texture
  52853. */
  52854. get: function () {
  52855. return this._projectionTextureMatrix;
  52856. },
  52857. enumerable: true,
  52858. configurable: true
  52859. });
  52860. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  52861. /**
  52862. * Gets the near clip of the Spotlight for texture projection.
  52863. */
  52864. get: function () {
  52865. return this._projectionTextureLightNear;
  52866. },
  52867. /**
  52868. * Sets the near clip of the Spotlight for texture projection.
  52869. */
  52870. set: function (value) {
  52871. this._projectionTextureLightNear = value;
  52872. this._projectionTextureProjectionLightDirty = true;
  52873. },
  52874. enumerable: true,
  52875. configurable: true
  52876. });
  52877. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  52878. /**
  52879. * Gets the far clip of the Spotlight for texture projection.
  52880. */
  52881. get: function () {
  52882. return this._projectionTextureLightFar;
  52883. },
  52884. /**
  52885. * Sets the far clip of the Spotlight for texture projection.
  52886. */
  52887. set: function (value) {
  52888. this._projectionTextureLightFar = value;
  52889. this._projectionTextureProjectionLightDirty = true;
  52890. },
  52891. enumerable: true,
  52892. configurable: true
  52893. });
  52894. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  52895. /**
  52896. * Gets the Up vector of the Spotlight for texture projection.
  52897. */
  52898. get: function () {
  52899. return this._projectionTextureUpDirection;
  52900. },
  52901. /**
  52902. * Sets the Up vector of the Spotlight for texture projection.
  52903. */
  52904. set: function (value) {
  52905. this._projectionTextureUpDirection = value;
  52906. this._projectionTextureProjectionLightDirty = true;
  52907. },
  52908. enumerable: true,
  52909. configurable: true
  52910. });
  52911. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  52912. /**
  52913. * Gets the projection texture of the light.
  52914. */
  52915. get: function () {
  52916. return this._projectionTexture;
  52917. },
  52918. /**
  52919. * Sets the projection texture of the light.
  52920. */
  52921. set: function (value) {
  52922. this._projectionTexture = value;
  52923. this._projectionTextureDirty = true;
  52924. },
  52925. enumerable: true,
  52926. configurable: true
  52927. });
  52928. /**
  52929. * Returns the string "SpotLight".
  52930. * @returns the class name
  52931. */
  52932. SpotLight.prototype.getClassName = function () {
  52933. return "SpotLight";
  52934. };
  52935. /**
  52936. * Returns the integer 2.
  52937. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52938. */
  52939. SpotLight.prototype.getTypeID = function () {
  52940. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  52941. };
  52942. /**
  52943. * Overrides the direction setter to recompute the projection texture view light Matrix.
  52944. */
  52945. SpotLight.prototype._setDirection = function (value) {
  52946. _super.prototype._setDirection.call(this, value);
  52947. this._projectionTextureViewLightDirty = true;
  52948. };
  52949. /**
  52950. * Overrides the position setter to recompute the projection texture view light Matrix.
  52951. */
  52952. SpotLight.prototype._setPosition = function (value) {
  52953. _super.prototype._setPosition.call(this, value);
  52954. this._projectionTextureViewLightDirty = true;
  52955. };
  52956. /**
  52957. * 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.
  52958. * Returns the SpotLight.
  52959. */
  52960. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52961. var activeCamera = this.getScene().activeCamera;
  52962. if (!activeCamera) {
  52963. return;
  52964. }
  52965. this._shadowAngleScale = this._shadowAngleScale || 1;
  52966. var angle = this._shadowAngleScale * this._angle;
  52967. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52968. };
  52969. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  52970. this._projectionTextureViewLightDirty = false;
  52971. this._projectionTextureDirty = true;
  52972. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  52973. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  52974. };
  52975. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  52976. this._projectionTextureProjectionLightDirty = false;
  52977. this._projectionTextureDirty = true;
  52978. var light_far = this.projectionTextureLightFar;
  52979. var light_near = this.projectionTextureLightNear;
  52980. var P = light_far / (light_far - light_near);
  52981. var Q = -P * light_near;
  52982. var S = 1.0 / Math.tan(this._angle / 2.0);
  52983. var A = 1.0;
  52984. 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);
  52985. };
  52986. /**
  52987. * Main function for light texture projection matrix computing.
  52988. */
  52989. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  52990. this._projectionTextureDirty = false;
  52991. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  52992. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  52993. };
  52994. SpotLight.prototype._buildUniformLayout = function () {
  52995. this._uniformBuffer.addUniform("vLightData", 4);
  52996. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52997. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52998. this._uniformBuffer.addUniform("vLightDirection", 3);
  52999. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53000. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53001. this._uniformBuffer.addUniform("depthValues", 2);
  53002. this._uniformBuffer.create();
  53003. };
  53004. SpotLight.prototype._computeAngleValues = function () {
  53005. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53006. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53007. };
  53008. /**
  53009. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53010. * @param effect The effect to update
  53011. * @param lightIndex The index of the light in the effect to update
  53012. * @returns The spot light
  53013. */
  53014. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53015. var normalizeDirection;
  53016. if (this.computeTransformedInformation()) {
  53017. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53018. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53019. }
  53020. else {
  53021. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53022. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53023. }
  53024. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53025. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53026. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53027. if (this._projectionTextureViewLightDirty) {
  53028. this._computeProjectionTextureViewLightMatrix();
  53029. }
  53030. if (this._projectionTextureProjectionLightDirty) {
  53031. this._computeProjectionTextureProjectionLightMatrix();
  53032. }
  53033. if (this._projectionTextureDirty) {
  53034. this._computeProjectionTextureMatrix();
  53035. }
  53036. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53037. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53038. }
  53039. return this;
  53040. };
  53041. /**
  53042. * Disposes the light and the associated resources.
  53043. */
  53044. SpotLight.prototype.dispose = function () {
  53045. _super.prototype.dispose.call(this);
  53046. if (this._projectionTexture) {
  53047. this._projectionTexture.dispose();
  53048. }
  53049. };
  53050. /**
  53051. * Prepares the list of defines specific to the light type.
  53052. * @param defines the list of defines
  53053. * @param lightIndex defines the index of the light for the effect
  53054. */
  53055. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53056. defines["SPOTLIGHT" + lightIndex] = true;
  53057. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53058. };
  53059. __decorate([
  53060. BABYLON.serialize()
  53061. ], SpotLight.prototype, "angle", null);
  53062. __decorate([
  53063. BABYLON.serialize()
  53064. ], SpotLight.prototype, "innerAngle", null);
  53065. __decorate([
  53066. BABYLON.serialize()
  53067. ], SpotLight.prototype, "shadowAngleScale", null);
  53068. __decorate([
  53069. BABYLON.serialize()
  53070. ], SpotLight.prototype, "exponent", void 0);
  53071. __decorate([
  53072. BABYLON.serialize()
  53073. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53074. __decorate([
  53075. BABYLON.serialize()
  53076. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53077. __decorate([
  53078. BABYLON.serialize()
  53079. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53080. __decorate([
  53081. BABYLON.serializeAsTexture("projectedLightTexture")
  53082. ], SpotLight.prototype, "_projectionTexture", void 0);
  53083. return SpotLight;
  53084. }(BABYLON.ShadowLight));
  53085. BABYLON.SpotLight = SpotLight;
  53086. })(BABYLON || (BABYLON = {}));
  53087. //# sourceMappingURL=babylon.spotLight.js.map
  53088. var BABYLON;
  53089. (function (BABYLON) {
  53090. /**
  53091. * Class used to override all child animations of a given target
  53092. */
  53093. var AnimationPropertiesOverride = /** @class */ (function () {
  53094. function AnimationPropertiesOverride() {
  53095. /**
  53096. * Gets or sets a value indicating if animation blending must be used
  53097. */
  53098. this.enableBlending = false;
  53099. /**
  53100. * Gets or sets the blending speed to use when enableBlending is true
  53101. */
  53102. this.blendingSpeed = 0.01;
  53103. /**
  53104. * Gets or sets the default loop mode to use
  53105. */
  53106. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53107. }
  53108. return AnimationPropertiesOverride;
  53109. }());
  53110. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53111. })(BABYLON || (BABYLON = {}));
  53112. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53113. var BABYLON;
  53114. (function (BABYLON) {
  53115. /**
  53116. * Represents the range of an animation
  53117. */
  53118. var AnimationRange = /** @class */ (function () {
  53119. /**
  53120. * Initializes the range of an animation
  53121. * @param name The name of the animation range
  53122. * @param from The starting frame of the animation
  53123. * @param to The ending frame of the animation
  53124. */
  53125. function AnimationRange(
  53126. /**The name of the animation range**/
  53127. name,
  53128. /**The starting frame of the animation */
  53129. from,
  53130. /**The ending frame of the animation*/
  53131. to) {
  53132. this.name = name;
  53133. this.from = from;
  53134. this.to = to;
  53135. }
  53136. /**
  53137. * Makes a copy of the animation range
  53138. * @returns A copy of the animation range
  53139. */
  53140. AnimationRange.prototype.clone = function () {
  53141. return new AnimationRange(this.name, this.from, this.to);
  53142. };
  53143. return AnimationRange;
  53144. }());
  53145. BABYLON.AnimationRange = AnimationRange;
  53146. /**
  53147. * Composed of a frame, and an action function
  53148. */
  53149. var AnimationEvent = /** @class */ (function () {
  53150. /**
  53151. * Initializes the animation event
  53152. * @param frame The frame for which the event is triggered
  53153. * @param action The event to perform when triggered
  53154. * @param onlyOnce Specifies if the event should be triggered only once
  53155. */
  53156. function AnimationEvent(
  53157. /** The frame for which the event is triggered **/
  53158. frame,
  53159. /** The event to perform when triggered **/
  53160. action,
  53161. /** Specifies if the event should be triggered only once**/
  53162. onlyOnce) {
  53163. this.frame = frame;
  53164. this.action = action;
  53165. this.onlyOnce = onlyOnce;
  53166. /**
  53167. * Specifies if the animation event is done
  53168. */
  53169. this.isDone = false;
  53170. }
  53171. /** @hidden */
  53172. AnimationEvent.prototype._clone = function () {
  53173. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53174. };
  53175. return AnimationEvent;
  53176. }());
  53177. BABYLON.AnimationEvent = AnimationEvent;
  53178. /**
  53179. * A cursor which tracks a point on a path
  53180. */
  53181. var PathCursor = /** @class */ (function () {
  53182. /**
  53183. * Initializes the path cursor
  53184. * @param path The path to track
  53185. */
  53186. function PathCursor(path) {
  53187. this.path = path;
  53188. /**
  53189. * Stores path cursor callbacks for when an onchange event is triggered
  53190. */
  53191. this._onchange = new Array();
  53192. /**
  53193. * The value of the path cursor
  53194. */
  53195. this.value = 0;
  53196. /**
  53197. * The animation array of the path cursor
  53198. */
  53199. this.animations = new Array();
  53200. }
  53201. /**
  53202. * Gets the cursor point on the path
  53203. * @returns A point on the path cursor at the cursor location
  53204. */
  53205. PathCursor.prototype.getPoint = function () {
  53206. var point = this.path.getPointAtLengthPosition(this.value);
  53207. return new BABYLON.Vector3(point.x, 0, point.y);
  53208. };
  53209. /**
  53210. * Moves the cursor ahead by the step amount
  53211. * @param step The amount to move the cursor forward
  53212. * @returns This path cursor
  53213. */
  53214. PathCursor.prototype.moveAhead = function (step) {
  53215. if (step === void 0) { step = 0.002; }
  53216. this.move(step);
  53217. return this;
  53218. };
  53219. /**
  53220. * Moves the cursor behind by the step amount
  53221. * @param step The amount to move the cursor back
  53222. * @returns This path cursor
  53223. */
  53224. PathCursor.prototype.moveBack = function (step) {
  53225. if (step === void 0) { step = 0.002; }
  53226. this.move(-step);
  53227. return this;
  53228. };
  53229. /**
  53230. * Moves the cursor by the step amount
  53231. * If the step amount is greater than one, an exception is thrown
  53232. * @param step The amount to move the cursor
  53233. * @returns This path cursor
  53234. */
  53235. PathCursor.prototype.move = function (step) {
  53236. if (Math.abs(step) > 1) {
  53237. throw "step size should be less than 1.";
  53238. }
  53239. this.value += step;
  53240. this.ensureLimits();
  53241. this.raiseOnChange();
  53242. return this;
  53243. };
  53244. /**
  53245. * Ensures that the value is limited between zero and one
  53246. * @returns This path cursor
  53247. */
  53248. PathCursor.prototype.ensureLimits = function () {
  53249. while (this.value > 1) {
  53250. this.value -= 1;
  53251. }
  53252. while (this.value < 0) {
  53253. this.value += 1;
  53254. }
  53255. return this;
  53256. };
  53257. /**
  53258. * Runs onchange callbacks on change (used by the animation engine)
  53259. * @returns This path cursor
  53260. */
  53261. PathCursor.prototype.raiseOnChange = function () {
  53262. var _this = this;
  53263. this._onchange.forEach(function (f) { return f(_this); });
  53264. return this;
  53265. };
  53266. /**
  53267. * Executes a function on change
  53268. * @param f A path cursor onchange callback
  53269. * @returns This path cursor
  53270. */
  53271. PathCursor.prototype.onchange = function (f) {
  53272. this._onchange.push(f);
  53273. return this;
  53274. };
  53275. return PathCursor;
  53276. }());
  53277. BABYLON.PathCursor = PathCursor;
  53278. /**
  53279. * Enum for the animation key frame interpolation type
  53280. */
  53281. var AnimationKeyInterpolation;
  53282. (function (AnimationKeyInterpolation) {
  53283. /**
  53284. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53285. */
  53286. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53287. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53288. /**
  53289. * Class used to store any kind of animation
  53290. */
  53291. var Animation = /** @class */ (function () {
  53292. /**
  53293. * Initializes the animation
  53294. * @param name Name of the animation
  53295. * @param targetProperty Property to animate
  53296. * @param framePerSecond The frames per second of the animation
  53297. * @param dataType The data type of the animation
  53298. * @param loopMode The loop mode of the animation
  53299. * @param enableBlendings Specifies if blending should be enabled
  53300. */
  53301. function Animation(
  53302. /**Name of the animation */
  53303. name,
  53304. /**Property to animate */
  53305. targetProperty,
  53306. /**The frames per second of the animation */
  53307. framePerSecond,
  53308. /**The data type of the animation */
  53309. dataType,
  53310. /**The loop mode of the animation */
  53311. loopMode,
  53312. /**Specifies if blending should be enabled */
  53313. enableBlending) {
  53314. this.name = name;
  53315. this.targetProperty = targetProperty;
  53316. this.framePerSecond = framePerSecond;
  53317. this.dataType = dataType;
  53318. this.loopMode = loopMode;
  53319. this.enableBlending = enableBlending;
  53320. /**
  53321. * @hidden Internal use only
  53322. */
  53323. this._runtimeAnimations = new Array();
  53324. /**
  53325. * The set of event that will be linked to this animation
  53326. */
  53327. this._events = new Array();
  53328. /**
  53329. * Stores the blending speed of the animation
  53330. */
  53331. this.blendingSpeed = 0.01;
  53332. /**
  53333. * Stores the animation ranges for the animation
  53334. */
  53335. this._ranges = {};
  53336. this.targetPropertyPath = targetProperty.split(".");
  53337. this.dataType = dataType;
  53338. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53339. }
  53340. /**
  53341. * @hidden Internal use
  53342. */
  53343. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53344. var dataType = undefined;
  53345. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53346. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53347. }
  53348. else if (from instanceof BABYLON.Quaternion) {
  53349. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53350. }
  53351. else if (from instanceof BABYLON.Vector3) {
  53352. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53353. }
  53354. else if (from instanceof BABYLON.Vector2) {
  53355. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53356. }
  53357. else if (from instanceof BABYLON.Color3) {
  53358. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53359. }
  53360. else if (from instanceof BABYLON.Size) {
  53361. dataType = Animation.ANIMATIONTYPE_SIZE;
  53362. }
  53363. if (dataType == undefined) {
  53364. return null;
  53365. }
  53366. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53367. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53368. animation.setKeys(keys);
  53369. if (easingFunction !== undefined) {
  53370. animation.setEasingFunction(easingFunction);
  53371. }
  53372. return animation;
  53373. };
  53374. /**
  53375. * Sets up an animation
  53376. * @param property The property to animate
  53377. * @param animationType The animation type to apply
  53378. * @param framePerSecond The frames per second of the animation
  53379. * @param easingFunction The easing function used in the animation
  53380. * @returns The created animation
  53381. */
  53382. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53383. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53384. animation.setEasingFunction(easingFunction);
  53385. return animation;
  53386. };
  53387. /**
  53388. * Create and start an animation on a node
  53389. * @param name defines the name of the global animation that will be run on all nodes
  53390. * @param node defines the root node where the animation will take place
  53391. * @param targetProperty defines property to animate
  53392. * @param framePerSecond defines the number of frame per second yo use
  53393. * @param totalFrame defines the number of frames in total
  53394. * @param from defines the initial value
  53395. * @param to defines the final value
  53396. * @param loopMode defines which loop mode you want to use (off by default)
  53397. * @param easingFunction defines the easing function to use (linear by default)
  53398. * @param onAnimationEnd defines the callback to call when animation end
  53399. * @returns the animatable created for this animation
  53400. */
  53401. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53402. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53403. if (!animation) {
  53404. return null;
  53405. }
  53406. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53407. };
  53408. /**
  53409. * Create and start an animation on a node and its descendants
  53410. * @param name defines the name of the global animation that will be run on all nodes
  53411. * @param node defines the root node where the animation will take place
  53412. * @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
  53413. * @param targetProperty defines property to animate
  53414. * @param framePerSecond defines the number of frame per second to use
  53415. * @param totalFrame defines the number of frames in total
  53416. * @param from defines the initial value
  53417. * @param to defines the final value
  53418. * @param loopMode defines which loop mode you want to use (off by default)
  53419. * @param easingFunction defines the easing function to use (linear by default)
  53420. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53421. * @returns the list of animatables created for all nodes
  53422. * @example https://www.babylonjs-playground.com/#MH0VLI
  53423. */
  53424. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53425. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53426. if (!animation) {
  53427. return null;
  53428. }
  53429. var scene = node.getScene();
  53430. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53431. };
  53432. /**
  53433. * Creates a new animation, merges it with the existing animations and starts it
  53434. * @param name Name of the animation
  53435. * @param node Node which contains the scene that begins the animations
  53436. * @param targetProperty Specifies which property to animate
  53437. * @param framePerSecond The frames per second of the animation
  53438. * @param totalFrame The total number of frames
  53439. * @param from The frame at the beginning of the animation
  53440. * @param to The frame at the end of the animation
  53441. * @param loopMode Specifies the loop mode of the animation
  53442. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53443. * @param onAnimationEnd Callback to run once the animation is complete
  53444. * @returns Nullable animation
  53445. */
  53446. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53447. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53448. if (!animation) {
  53449. return null;
  53450. }
  53451. node.animations.push(animation);
  53452. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53453. };
  53454. /**
  53455. * Transition property of an host to the target Value
  53456. * @param property The property to transition
  53457. * @param targetValue The target Value of the property
  53458. * @param host The object where the property to animate belongs
  53459. * @param scene Scene used to run the animation
  53460. * @param frameRate Framerate (in frame/s) to use
  53461. * @param transition The transition type we want to use
  53462. * @param duration The duration of the animation, in milliseconds
  53463. * @param onAnimationEnd Callback trigger at the end of the animation
  53464. * @returns Nullable animation
  53465. */
  53466. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53467. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53468. if (duration <= 0) {
  53469. host[property] = targetValue;
  53470. if (onAnimationEnd) {
  53471. onAnimationEnd();
  53472. }
  53473. return null;
  53474. }
  53475. var endFrame = frameRate * (duration / 1000);
  53476. transition.setKeys([{
  53477. frame: 0,
  53478. value: host[property].clone ? host[property].clone() : host[property]
  53479. },
  53480. {
  53481. frame: endFrame,
  53482. value: targetValue
  53483. }]);
  53484. if (!host.animations) {
  53485. host.animations = [];
  53486. }
  53487. host.animations.push(transition);
  53488. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53489. animation.onAnimationEnd = onAnimationEnd;
  53490. return animation;
  53491. };
  53492. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53493. /**
  53494. * Return the array of runtime animations currently using this animation
  53495. */
  53496. get: function () {
  53497. return this._runtimeAnimations;
  53498. },
  53499. enumerable: true,
  53500. configurable: true
  53501. });
  53502. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53503. /**
  53504. * Specifies if any of the runtime animations are currently running
  53505. */
  53506. get: function () {
  53507. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53508. var runtimeAnimation = _a[_i];
  53509. if (!runtimeAnimation.isStopped) {
  53510. return true;
  53511. }
  53512. }
  53513. return false;
  53514. },
  53515. enumerable: true,
  53516. configurable: true
  53517. });
  53518. // Methods
  53519. /**
  53520. * Converts the animation to a string
  53521. * @param fullDetails support for multiple levels of logging within scene loading
  53522. * @returns String form of the animation
  53523. */
  53524. Animation.prototype.toString = function (fullDetails) {
  53525. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53526. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53527. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53528. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53529. if (fullDetails) {
  53530. ret += ", Ranges: {";
  53531. var first = true;
  53532. for (var name in this._ranges) {
  53533. if (first) {
  53534. ret += ", ";
  53535. first = false;
  53536. }
  53537. ret += name;
  53538. }
  53539. ret += "}";
  53540. }
  53541. return ret;
  53542. };
  53543. /**
  53544. * Add an event to this animation
  53545. * @param event Event to add
  53546. */
  53547. Animation.prototype.addEvent = function (event) {
  53548. this._events.push(event);
  53549. };
  53550. /**
  53551. * Remove all events found at the given frame
  53552. * @param frame The frame to remove events from
  53553. */
  53554. Animation.prototype.removeEvents = function (frame) {
  53555. for (var index = 0; index < this._events.length; index++) {
  53556. if (this._events[index].frame === frame) {
  53557. this._events.splice(index, 1);
  53558. index--;
  53559. }
  53560. }
  53561. };
  53562. /**
  53563. * Retrieves all the events from the animation
  53564. * @returns Events from the animation
  53565. */
  53566. Animation.prototype.getEvents = function () {
  53567. return this._events;
  53568. };
  53569. /**
  53570. * Creates an animation range
  53571. * @param name Name of the animation range
  53572. * @param from Starting frame of the animation range
  53573. * @param to Ending frame of the animation
  53574. */
  53575. Animation.prototype.createRange = function (name, from, to) {
  53576. // check name not already in use; could happen for bones after serialized
  53577. if (!this._ranges[name]) {
  53578. this._ranges[name] = new AnimationRange(name, from, to);
  53579. }
  53580. };
  53581. /**
  53582. * Deletes an animation range by name
  53583. * @param name Name of the animation range to delete
  53584. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  53585. */
  53586. Animation.prototype.deleteRange = function (name, deleteFrames) {
  53587. if (deleteFrames === void 0) { deleteFrames = true; }
  53588. var range = this._ranges[name];
  53589. if (!range) {
  53590. return;
  53591. }
  53592. if (deleteFrames) {
  53593. var from = range.from;
  53594. var to = range.to;
  53595. // this loop MUST go high to low for multiple splices to work
  53596. for (var key = this._keys.length - 1; key >= 0; key--) {
  53597. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  53598. this._keys.splice(key, 1);
  53599. }
  53600. }
  53601. }
  53602. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  53603. };
  53604. /**
  53605. * Gets the animation range by name, or null if not defined
  53606. * @param name Name of the animation range
  53607. * @returns Nullable animation range
  53608. */
  53609. Animation.prototype.getRange = function (name) {
  53610. return this._ranges[name];
  53611. };
  53612. /**
  53613. * Gets the key frames from the animation
  53614. * @returns The key frames of the animation
  53615. */
  53616. Animation.prototype.getKeys = function () {
  53617. return this._keys;
  53618. };
  53619. /**
  53620. * Gets the highest frame rate of the animation
  53621. * @returns Highest frame rate of the animation
  53622. */
  53623. Animation.prototype.getHighestFrame = function () {
  53624. var ret = 0;
  53625. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  53626. if (ret < this._keys[key].frame) {
  53627. ret = this._keys[key].frame;
  53628. }
  53629. }
  53630. return ret;
  53631. };
  53632. /**
  53633. * Gets the easing function of the animation
  53634. * @returns Easing function of the animation
  53635. */
  53636. Animation.prototype.getEasingFunction = function () {
  53637. return this._easingFunction;
  53638. };
  53639. /**
  53640. * Sets the easing function of the animation
  53641. * @param easingFunction A custom mathematical formula for animation
  53642. */
  53643. Animation.prototype.setEasingFunction = function (easingFunction) {
  53644. this._easingFunction = easingFunction;
  53645. };
  53646. /**
  53647. * Interpolates a scalar linearly
  53648. * @param startValue Start value of the animation curve
  53649. * @param endValue End value of the animation curve
  53650. * @param gradient Scalar amount to interpolate
  53651. * @returns Interpolated scalar value
  53652. */
  53653. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  53654. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  53655. };
  53656. /**
  53657. * Interpolates a scalar cubically
  53658. * @param startValue Start value of the animation curve
  53659. * @param outTangent End tangent of the animation
  53660. * @param endValue End value of the animation curve
  53661. * @param inTangent Start tangent of the animation curve
  53662. * @param gradient Scalar amount to interpolate
  53663. * @returns Interpolated scalar value
  53664. */
  53665. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53666. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53667. };
  53668. /**
  53669. * Interpolates a quaternion using a spherical linear interpolation
  53670. * @param startValue Start value of the animation curve
  53671. * @param endValue End value of the animation curve
  53672. * @param gradient Scalar amount to interpolate
  53673. * @returns Interpolated quaternion value
  53674. */
  53675. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  53676. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  53677. };
  53678. /**
  53679. * Interpolates a quaternion cubically
  53680. * @param startValue Start value of the animation curve
  53681. * @param outTangent End tangent of the animation curve
  53682. * @param endValue End value of the animation curve
  53683. * @param inTangent Start tangent of the animation curve
  53684. * @param gradient Scalar amount to interpolate
  53685. * @returns Interpolated quaternion value
  53686. */
  53687. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53688. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  53689. };
  53690. /**
  53691. * Interpolates a Vector3 linearl
  53692. * @param startValue Start value of the animation curve
  53693. * @param endValue End value of the animation curve
  53694. * @param gradient Scalar amount to interpolate
  53695. * @returns Interpolated scalar value
  53696. */
  53697. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  53698. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  53699. };
  53700. /**
  53701. * Interpolates a Vector3 cubically
  53702. * @param startValue Start value of the animation curve
  53703. * @param outTangent End tangent of the animation
  53704. * @param endValue End value of the animation curve
  53705. * @param inTangent Start tangent of the animation curve
  53706. * @param gradient Scalar amount to interpolate
  53707. * @returns InterpolatedVector3 value
  53708. */
  53709. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53710. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53711. };
  53712. /**
  53713. * Interpolates a Vector2 linearly
  53714. * @param startValue Start value of the animation curve
  53715. * @param endValue End value of the animation curve
  53716. * @param gradient Scalar amount to interpolate
  53717. * @returns Interpolated Vector2 value
  53718. */
  53719. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  53720. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  53721. };
  53722. /**
  53723. * Interpolates a Vector2 cubically
  53724. * @param startValue Start value of the animation curve
  53725. * @param outTangent End tangent of the animation
  53726. * @param endValue End value of the animation curve
  53727. * @param inTangent Start tangent of the animation curve
  53728. * @param gradient Scalar amount to interpolate
  53729. * @returns Interpolated Vector2 value
  53730. */
  53731. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53732. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53733. };
  53734. /**
  53735. * Interpolates a size linearly
  53736. * @param startValue Start value of the animation curve
  53737. * @param endValue End value of the animation curve
  53738. * @param gradient Scalar amount to interpolate
  53739. * @returns Interpolated Size value
  53740. */
  53741. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  53742. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  53743. };
  53744. /**
  53745. * Interpolates a Color3 linearly
  53746. * @param startValue Start value of the animation curve
  53747. * @param endValue End value of the animation curve
  53748. * @param gradient Scalar amount to interpolate
  53749. * @returns Interpolated Color3 value
  53750. */
  53751. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  53752. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  53753. };
  53754. /**
  53755. * @hidden Internal use only
  53756. */
  53757. Animation.prototype._getKeyValue = function (value) {
  53758. if (typeof value === "function") {
  53759. return value();
  53760. }
  53761. return value;
  53762. };
  53763. /**
  53764. * @hidden Internal use only
  53765. */
  53766. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  53767. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  53768. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  53769. }
  53770. var keys = this.getKeys();
  53771. // Try to get a hash to find the right key
  53772. 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));
  53773. if (keys[startKeyIndex].frame >= currentFrame) {
  53774. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  53775. startKeyIndex--;
  53776. }
  53777. }
  53778. for (var key = startKeyIndex; key < keys.length; key++) {
  53779. var endKey = keys[key + 1];
  53780. if (endKey.frame >= currentFrame) {
  53781. var startKey = keys[key];
  53782. var startValue = this._getKeyValue(startKey.value);
  53783. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  53784. return startValue;
  53785. }
  53786. var endValue = this._getKeyValue(endKey.value);
  53787. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  53788. var frameDelta = endKey.frame - startKey.frame;
  53789. // gradient : percent of currentFrame between the frame inf and the frame sup
  53790. var gradient = (currentFrame - startKey.frame) / frameDelta;
  53791. // check for easingFunction and correction of gradient
  53792. var easingFunction = this.getEasingFunction();
  53793. if (easingFunction != null) {
  53794. gradient = easingFunction.ease(gradient);
  53795. }
  53796. switch (this.dataType) {
  53797. // Float
  53798. case Animation.ANIMATIONTYPE_FLOAT:
  53799. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  53800. switch (loopMode) {
  53801. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53802. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53803. return floatValue;
  53804. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53805. return offsetValue * repeatCount + floatValue;
  53806. }
  53807. break;
  53808. // Quaternion
  53809. case Animation.ANIMATIONTYPE_QUATERNION:
  53810. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  53811. switch (loopMode) {
  53812. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53813. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53814. return quatValue;
  53815. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53816. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  53817. }
  53818. return quatValue;
  53819. // Vector3
  53820. case Animation.ANIMATIONTYPE_VECTOR3:
  53821. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  53822. switch (loopMode) {
  53823. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53824. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53825. return vec3Value;
  53826. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53827. return vec3Value.add(offsetValue.scale(repeatCount));
  53828. }
  53829. // Vector2
  53830. case Animation.ANIMATIONTYPE_VECTOR2:
  53831. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  53832. switch (loopMode) {
  53833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53835. return vec2Value;
  53836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53837. return vec2Value.add(offsetValue.scale(repeatCount));
  53838. }
  53839. // Size
  53840. case Animation.ANIMATIONTYPE_SIZE:
  53841. switch (loopMode) {
  53842. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53843. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53844. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  53845. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53846. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53847. }
  53848. // Color3
  53849. case Animation.ANIMATIONTYPE_COLOR3:
  53850. switch (loopMode) {
  53851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53853. return this.color3InterpolateFunction(startValue, endValue, gradient);
  53854. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53855. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53856. }
  53857. // Matrix
  53858. case Animation.ANIMATIONTYPE_MATRIX:
  53859. switch (loopMode) {
  53860. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53861. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53862. if (Animation.AllowMatricesInterpolation) {
  53863. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  53864. }
  53865. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53866. return startValue;
  53867. }
  53868. default:
  53869. break;
  53870. }
  53871. break;
  53872. }
  53873. }
  53874. return this._getKeyValue(keys[keys.length - 1].value);
  53875. };
  53876. /**
  53877. * Defines the function to use to interpolate matrices
  53878. * @param startValue defines the start matrix
  53879. * @param endValue defines the end matrix
  53880. * @param gradient defines the gradient between both matrices
  53881. * @param result defines an optional target matrix where to store the interpolation
  53882. * @returns the interpolated matrix
  53883. */
  53884. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  53885. if (Animation.AllowMatrixDecomposeForInterpolation) {
  53886. if (result) {
  53887. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  53888. return result;
  53889. }
  53890. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  53891. }
  53892. if (result) {
  53893. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  53894. return result;
  53895. }
  53896. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  53897. };
  53898. /**
  53899. * Makes a copy of the animation
  53900. * @returns Cloned animation
  53901. */
  53902. Animation.prototype.clone = function () {
  53903. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  53904. clone.enableBlending = this.enableBlending;
  53905. clone.blendingSpeed = this.blendingSpeed;
  53906. if (this._keys) {
  53907. clone.setKeys(this._keys);
  53908. }
  53909. if (this._ranges) {
  53910. clone._ranges = {};
  53911. for (var name in this._ranges) {
  53912. var range = this._ranges[name];
  53913. if (!range) {
  53914. continue;
  53915. }
  53916. clone._ranges[name] = range.clone();
  53917. }
  53918. }
  53919. return clone;
  53920. };
  53921. /**
  53922. * Sets the key frames of the animation
  53923. * @param values The animation key frames to set
  53924. */
  53925. Animation.prototype.setKeys = function (values) {
  53926. this._keys = values.slice(0);
  53927. };
  53928. /**
  53929. * Serializes the animation to an object
  53930. * @returns Serialized object
  53931. */
  53932. Animation.prototype.serialize = function () {
  53933. var serializationObject = {};
  53934. serializationObject.name = this.name;
  53935. serializationObject.property = this.targetProperty;
  53936. serializationObject.framePerSecond = this.framePerSecond;
  53937. serializationObject.dataType = this.dataType;
  53938. serializationObject.loopBehavior = this.loopMode;
  53939. serializationObject.enableBlending = this.enableBlending;
  53940. serializationObject.blendingSpeed = this.blendingSpeed;
  53941. var dataType = this.dataType;
  53942. serializationObject.keys = [];
  53943. var keys = this.getKeys();
  53944. for (var index = 0; index < keys.length; index++) {
  53945. var animationKey = keys[index];
  53946. var key = {};
  53947. key.frame = animationKey.frame;
  53948. switch (dataType) {
  53949. case Animation.ANIMATIONTYPE_FLOAT:
  53950. key.values = [animationKey.value];
  53951. break;
  53952. case Animation.ANIMATIONTYPE_QUATERNION:
  53953. case Animation.ANIMATIONTYPE_MATRIX:
  53954. case Animation.ANIMATIONTYPE_VECTOR3:
  53955. case Animation.ANIMATIONTYPE_COLOR3:
  53956. key.values = animationKey.value.asArray();
  53957. break;
  53958. }
  53959. serializationObject.keys.push(key);
  53960. }
  53961. serializationObject.ranges = [];
  53962. for (var name in this._ranges) {
  53963. var source = this._ranges[name];
  53964. if (!source) {
  53965. continue;
  53966. }
  53967. var range = {};
  53968. range.name = name;
  53969. range.from = source.from;
  53970. range.to = source.to;
  53971. serializationObject.ranges.push(range);
  53972. }
  53973. return serializationObject;
  53974. };
  53975. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  53976. /**
  53977. * Get the float animation type
  53978. */
  53979. get: function () {
  53980. return Animation._ANIMATIONTYPE_FLOAT;
  53981. },
  53982. enumerable: true,
  53983. configurable: true
  53984. });
  53985. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  53986. /**
  53987. * Get the Vector3 animation type
  53988. */
  53989. get: function () {
  53990. return Animation._ANIMATIONTYPE_VECTOR3;
  53991. },
  53992. enumerable: true,
  53993. configurable: true
  53994. });
  53995. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  53996. /**
  53997. * Get the Vector2 animation type
  53998. */
  53999. get: function () {
  54000. return Animation._ANIMATIONTYPE_VECTOR2;
  54001. },
  54002. enumerable: true,
  54003. configurable: true
  54004. });
  54005. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54006. /**
  54007. * Get the Size animation type
  54008. */
  54009. get: function () {
  54010. return Animation._ANIMATIONTYPE_SIZE;
  54011. },
  54012. enumerable: true,
  54013. configurable: true
  54014. });
  54015. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54016. /**
  54017. * Get the Quaternion animation type
  54018. */
  54019. get: function () {
  54020. return Animation._ANIMATIONTYPE_QUATERNION;
  54021. },
  54022. enumerable: true,
  54023. configurable: true
  54024. });
  54025. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54026. /**
  54027. * Get the Matrix animation type
  54028. */
  54029. get: function () {
  54030. return Animation._ANIMATIONTYPE_MATRIX;
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54036. /**
  54037. * Get the Color3 animation type
  54038. */
  54039. get: function () {
  54040. return Animation._ANIMATIONTYPE_COLOR3;
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54046. /**
  54047. * Get the Relative Loop Mode
  54048. */
  54049. get: function () {
  54050. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54051. },
  54052. enumerable: true,
  54053. configurable: true
  54054. });
  54055. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54056. /**
  54057. * Get the Cycle Loop Mode
  54058. */
  54059. get: function () {
  54060. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54061. },
  54062. enumerable: true,
  54063. configurable: true
  54064. });
  54065. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54066. /**
  54067. * Get the Constant Loop Mode
  54068. */
  54069. get: function () {
  54070. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54071. },
  54072. enumerable: true,
  54073. configurable: true
  54074. });
  54075. /** @hidden */
  54076. Animation._UniversalLerp = function (left, right, amount) {
  54077. var constructor = left.constructor;
  54078. if (constructor.Lerp) { // Lerp supported
  54079. return constructor.Lerp(left, right, amount);
  54080. }
  54081. else if (constructor.Slerp) { // Slerp supported
  54082. return constructor.Slerp(left, right, amount);
  54083. }
  54084. else if (left.toFixed) { // Number
  54085. return left * (1.0 - amount) + amount * right;
  54086. }
  54087. else { // Blending not supported
  54088. return right;
  54089. }
  54090. };
  54091. /**
  54092. * Parses an animation object and creates an animation
  54093. * @param parsedAnimation Parsed animation object
  54094. * @returns Animation object
  54095. */
  54096. Animation.Parse = function (parsedAnimation) {
  54097. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54098. var dataType = parsedAnimation.dataType;
  54099. var keys = [];
  54100. var data;
  54101. var index;
  54102. if (parsedAnimation.enableBlending) {
  54103. animation.enableBlending = parsedAnimation.enableBlending;
  54104. }
  54105. if (parsedAnimation.blendingSpeed) {
  54106. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54107. }
  54108. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54109. var key = parsedAnimation.keys[index];
  54110. var inTangent;
  54111. var outTangent;
  54112. switch (dataType) {
  54113. case Animation.ANIMATIONTYPE_FLOAT:
  54114. data = key.values[0];
  54115. if (key.values.length >= 1) {
  54116. inTangent = key.values[1];
  54117. }
  54118. if (key.values.length >= 2) {
  54119. outTangent = key.values[2];
  54120. }
  54121. break;
  54122. case Animation.ANIMATIONTYPE_QUATERNION:
  54123. data = BABYLON.Quaternion.FromArray(key.values);
  54124. if (key.values.length >= 8) {
  54125. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54126. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54127. inTangent = _inTangent;
  54128. }
  54129. }
  54130. if (key.values.length >= 12) {
  54131. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54132. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54133. outTangent = _outTangent;
  54134. }
  54135. }
  54136. break;
  54137. case Animation.ANIMATIONTYPE_MATRIX:
  54138. data = BABYLON.Matrix.FromArray(key.values);
  54139. break;
  54140. case Animation.ANIMATIONTYPE_COLOR3:
  54141. data = BABYLON.Color3.FromArray(key.values);
  54142. break;
  54143. case Animation.ANIMATIONTYPE_VECTOR3:
  54144. default:
  54145. data = BABYLON.Vector3.FromArray(key.values);
  54146. break;
  54147. }
  54148. var keyData = {};
  54149. keyData.frame = key.frame;
  54150. keyData.value = data;
  54151. if (inTangent != undefined) {
  54152. keyData.inTangent = inTangent;
  54153. }
  54154. if (outTangent != undefined) {
  54155. keyData.outTangent = outTangent;
  54156. }
  54157. keys.push(keyData);
  54158. }
  54159. animation.setKeys(keys);
  54160. if (parsedAnimation.ranges) {
  54161. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54162. data = parsedAnimation.ranges[index];
  54163. animation.createRange(data.name, data.from, data.to);
  54164. }
  54165. }
  54166. return animation;
  54167. };
  54168. /**
  54169. * Appends the serialized animations from the source animations
  54170. * @param source Source containing the animations
  54171. * @param destination Target to store the animations
  54172. */
  54173. Animation.AppendSerializedAnimations = function (source, destination) {
  54174. if (source.animations) {
  54175. destination.animations = [];
  54176. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54177. var animation = source.animations[animationIndex];
  54178. destination.animations.push(animation.serialize());
  54179. }
  54180. }
  54181. };
  54182. /**
  54183. * Use matrix interpolation instead of using direct key value when animating matrices
  54184. */
  54185. Animation.AllowMatricesInterpolation = false;
  54186. /**
  54187. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54188. */
  54189. Animation.AllowMatrixDecomposeForInterpolation = true;
  54190. // Statics
  54191. /**
  54192. * Float animation type
  54193. */
  54194. Animation._ANIMATIONTYPE_FLOAT = 0;
  54195. /**
  54196. * Vector3 animation type
  54197. */
  54198. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54199. /**
  54200. * Quaternion animation type
  54201. */
  54202. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54203. /**
  54204. * Matrix animation type
  54205. */
  54206. Animation._ANIMATIONTYPE_MATRIX = 3;
  54207. /**
  54208. * Color3 animation type
  54209. */
  54210. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54211. /**
  54212. * Vector2 animation type
  54213. */
  54214. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54215. /**
  54216. * Size animation type
  54217. */
  54218. Animation._ANIMATIONTYPE_SIZE = 6;
  54219. /**
  54220. * Relative Loop Mode
  54221. */
  54222. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54223. /**
  54224. * Cycle Loop Mode
  54225. */
  54226. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54227. /**
  54228. * Constant Loop Mode
  54229. */
  54230. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54231. return Animation;
  54232. }());
  54233. BABYLON.Animation = Animation;
  54234. })(BABYLON || (BABYLON = {}));
  54235. //# sourceMappingURL=babylon.animation.js.map
  54236. var BABYLON;
  54237. (function (BABYLON) {
  54238. /**
  54239. * This class defines the direct association between an animation and a target
  54240. */
  54241. var TargetedAnimation = /** @class */ (function () {
  54242. function TargetedAnimation() {
  54243. }
  54244. return TargetedAnimation;
  54245. }());
  54246. BABYLON.TargetedAnimation = TargetedAnimation;
  54247. /**
  54248. * Use this class to create coordinated animations on multiple targets
  54249. */
  54250. var AnimationGroup = /** @class */ (function () {
  54251. /**
  54252. * Instantiates a new Animation Group.
  54253. * This helps managing several animations at once.
  54254. * @see http://doc.babylonjs.com/how_to/group
  54255. * @param name Defines the name of the group
  54256. * @param scene Defines the scene the group belongs to
  54257. */
  54258. function AnimationGroup(
  54259. /** The name of the animation group */
  54260. name, scene) {
  54261. if (scene === void 0) { scene = null; }
  54262. this.name = name;
  54263. this._targetedAnimations = new Array();
  54264. this._animatables = new Array();
  54265. this._from = Number.MAX_VALUE;
  54266. this._to = -Number.MAX_VALUE;
  54267. this._speedRatio = 1;
  54268. /**
  54269. * This observable will notify when one animation have ended.
  54270. */
  54271. this.onAnimationEndObservable = new BABYLON.Observable();
  54272. /**
  54273. * This observable will notify when all animations have ended.
  54274. */
  54275. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54276. /**
  54277. * This observable will notify when all animations have paused.
  54278. */
  54279. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54280. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54281. this._scene.animationGroups.push(this);
  54282. }
  54283. Object.defineProperty(AnimationGroup.prototype, "from", {
  54284. /**
  54285. * Gets the first frame
  54286. */
  54287. get: function () {
  54288. return this._from;
  54289. },
  54290. enumerable: true,
  54291. configurable: true
  54292. });
  54293. Object.defineProperty(AnimationGroup.prototype, "to", {
  54294. /**
  54295. * Gets the last frame
  54296. */
  54297. get: function () {
  54298. return this._to;
  54299. },
  54300. enumerable: true,
  54301. configurable: true
  54302. });
  54303. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54304. /**
  54305. * Define if the animations are started
  54306. */
  54307. get: function () {
  54308. return this._isStarted;
  54309. },
  54310. enumerable: true,
  54311. configurable: true
  54312. });
  54313. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54314. /**
  54315. * Gets or sets the speed ratio to use for all animations
  54316. */
  54317. get: function () {
  54318. return this._speedRatio;
  54319. },
  54320. /**
  54321. * Gets or sets the speed ratio to use for all animations
  54322. */
  54323. set: function (value) {
  54324. if (this._speedRatio === value) {
  54325. return;
  54326. }
  54327. this._speedRatio = value;
  54328. for (var index = 0; index < this._animatables.length; index++) {
  54329. var animatable = this._animatables[index];
  54330. animatable.speedRatio = this._speedRatio;
  54331. }
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54337. /**
  54338. * Gets the targeted animations for this animation group
  54339. */
  54340. get: function () {
  54341. return this._targetedAnimations;
  54342. },
  54343. enumerable: true,
  54344. configurable: true
  54345. });
  54346. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54347. /**
  54348. * returning the list of animatables controlled by this animation group.
  54349. */
  54350. get: function () {
  54351. return this._animatables;
  54352. },
  54353. enumerable: true,
  54354. configurable: true
  54355. });
  54356. /**
  54357. * Add an animation (with its target) in the group
  54358. * @param animation defines the animation we want to add
  54359. * @param target defines the target of the animation
  54360. * @returns the TargetedAnimation object
  54361. */
  54362. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54363. var targetedAnimation = {
  54364. animation: animation,
  54365. target: target
  54366. };
  54367. var keys = animation.getKeys();
  54368. if (this._from > keys[0].frame) {
  54369. this._from = keys[0].frame;
  54370. }
  54371. if (this._to < keys[keys.length - 1].frame) {
  54372. this._to = keys[keys.length - 1].frame;
  54373. }
  54374. this._targetedAnimations.push(targetedAnimation);
  54375. return targetedAnimation;
  54376. };
  54377. /**
  54378. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54379. * It can add constant keys at begin or end
  54380. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54381. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54382. * @returns the animation group
  54383. */
  54384. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54385. if (beginFrame === void 0) { beginFrame = null; }
  54386. if (endFrame === void 0) { endFrame = null; }
  54387. if (beginFrame == null) {
  54388. beginFrame = this._from;
  54389. }
  54390. if (endFrame == null) {
  54391. endFrame = this._to;
  54392. }
  54393. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54394. var targetedAnimation = this._targetedAnimations[index];
  54395. var keys = targetedAnimation.animation.getKeys();
  54396. var startKey = keys[0];
  54397. var endKey = keys[keys.length - 1];
  54398. if (startKey.frame > beginFrame) {
  54399. var newKey = {
  54400. frame: beginFrame,
  54401. value: startKey.value,
  54402. inTangent: startKey.inTangent,
  54403. outTangent: startKey.outTangent,
  54404. interpolation: startKey.interpolation
  54405. };
  54406. keys.splice(0, 0, newKey);
  54407. }
  54408. if (endKey.frame < endFrame) {
  54409. var newKey = {
  54410. frame: endFrame,
  54411. value: endKey.value,
  54412. inTangent: endKey.outTangent,
  54413. outTangent: endKey.outTangent,
  54414. interpolation: endKey.interpolation
  54415. };
  54416. keys.push(newKey);
  54417. }
  54418. }
  54419. this._from = beginFrame;
  54420. this._to = endFrame;
  54421. return this;
  54422. };
  54423. /**
  54424. * Start all animations on given targets
  54425. * @param loop defines if animations must loop
  54426. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54427. * @param from defines the from key (optional)
  54428. * @param to defines the to key (optional)
  54429. * @returns the current animation group
  54430. */
  54431. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54432. var _this = this;
  54433. if (loop === void 0) { loop = false; }
  54434. if (speedRatio === void 0) { speedRatio = 1; }
  54435. if (this._isStarted || this._targetedAnimations.length === 0) {
  54436. return this;
  54437. }
  54438. var _loop_1 = function (targetedAnimation) {
  54439. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54440. animatable.onAnimationEnd = function () {
  54441. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54442. _this._checkAnimationGroupEnded(animatable);
  54443. };
  54444. this_1._animatables.push(animatable);
  54445. };
  54446. var this_1 = this;
  54447. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54448. var targetedAnimation = _a[_i];
  54449. _loop_1(targetedAnimation);
  54450. }
  54451. this._speedRatio = speedRatio;
  54452. this._isStarted = true;
  54453. return this;
  54454. };
  54455. /**
  54456. * Pause all animations
  54457. * @returns the animation group
  54458. */
  54459. AnimationGroup.prototype.pause = function () {
  54460. if (!this._isStarted) {
  54461. return this;
  54462. }
  54463. for (var index = 0; index < this._animatables.length; index++) {
  54464. var animatable = this._animatables[index];
  54465. animatable.pause();
  54466. }
  54467. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54468. return this;
  54469. };
  54470. /**
  54471. * Play all animations to initial state
  54472. * This function will start() the animations if they were not started or will restart() them if they were paused
  54473. * @param loop defines if animations must loop
  54474. * @returns the animation group
  54475. */
  54476. AnimationGroup.prototype.play = function (loop) {
  54477. // only if all animatables are ready and exist
  54478. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54479. if (loop !== undefined) {
  54480. for (var index = 0; index < this._animatables.length; index++) {
  54481. var animatable = this._animatables[index];
  54482. animatable.loopAnimation = loop;
  54483. }
  54484. }
  54485. this.restart();
  54486. }
  54487. else {
  54488. this.stop();
  54489. this.start(loop, this._speedRatio);
  54490. }
  54491. return this;
  54492. };
  54493. /**
  54494. * Reset all animations to initial state
  54495. * @returns the animation group
  54496. */
  54497. AnimationGroup.prototype.reset = function () {
  54498. if (!this._isStarted) {
  54499. return this;
  54500. }
  54501. for (var index = 0; index < this._animatables.length; index++) {
  54502. var animatable = this._animatables[index];
  54503. animatable.reset();
  54504. }
  54505. return this;
  54506. };
  54507. /**
  54508. * Restart animations from key 0
  54509. * @returns the animation group
  54510. */
  54511. AnimationGroup.prototype.restart = function () {
  54512. if (!this._isStarted) {
  54513. return this;
  54514. }
  54515. for (var index = 0; index < this._animatables.length; index++) {
  54516. var animatable = this._animatables[index];
  54517. animatable.restart();
  54518. }
  54519. return this;
  54520. };
  54521. /**
  54522. * Stop all animations
  54523. * @returns the animation group
  54524. */
  54525. AnimationGroup.prototype.stop = function () {
  54526. if (!this._isStarted) {
  54527. return this;
  54528. }
  54529. var list = this._animatables.slice();
  54530. for (var index = 0; index < list.length; index++) {
  54531. list[index].stop();
  54532. }
  54533. this._isStarted = false;
  54534. return this;
  54535. };
  54536. /**
  54537. * Set animation weight for all animatables
  54538. * @param weight defines the weight to use
  54539. * @return the animationGroup
  54540. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54541. */
  54542. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54543. for (var index = 0; index < this._animatables.length; index++) {
  54544. var animatable = this._animatables[index];
  54545. animatable.weight = weight;
  54546. }
  54547. return this;
  54548. };
  54549. /**
  54550. * Synchronize and normalize all animatables with a source animatable
  54551. * @param root defines the root animatable to synchronize with
  54552. * @return the animationGroup
  54553. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54554. */
  54555. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54556. for (var index = 0; index < this._animatables.length; index++) {
  54557. var animatable = this._animatables[index];
  54558. animatable.syncWith(root);
  54559. }
  54560. return this;
  54561. };
  54562. /**
  54563. * Goes to a specific frame in this animation group
  54564. * @param frame the frame number to go to
  54565. * @return the animationGroup
  54566. */
  54567. AnimationGroup.prototype.goToFrame = function (frame) {
  54568. if (!this._isStarted) {
  54569. return this;
  54570. }
  54571. for (var index = 0; index < this._animatables.length; index++) {
  54572. var animatable = this._animatables[index];
  54573. animatable.goToFrame(frame);
  54574. }
  54575. return this;
  54576. };
  54577. /**
  54578. * Dispose all associated resources
  54579. */
  54580. AnimationGroup.prototype.dispose = function () {
  54581. this._targetedAnimations = [];
  54582. this._animatables = [];
  54583. var index = this._scene.animationGroups.indexOf(this);
  54584. if (index > -1) {
  54585. this._scene.animationGroups.splice(index, 1);
  54586. }
  54587. };
  54588. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  54589. // animatable should be taken out of the array
  54590. var idx = this._animatables.indexOf(animatable);
  54591. if (idx > -1) {
  54592. this._animatables.splice(idx, 1);
  54593. }
  54594. // all animatables were removed? animation group ended!
  54595. if (this._animatables.length === 0) {
  54596. this._isStarted = false;
  54597. this.onAnimationGroupEndObservable.notifyObservers(this);
  54598. }
  54599. };
  54600. // Statics
  54601. /**
  54602. * Returns a new AnimationGroup object parsed from the source provided.
  54603. * @param parsedAnimationGroup defines the source
  54604. * @param scene defines the scene that will receive the animationGroup
  54605. * @returns a new AnimationGroup
  54606. */
  54607. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  54608. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  54609. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  54610. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  54611. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  54612. var id = targetedAnimation.targetId;
  54613. var targetNode = scene.getNodeByID(id);
  54614. if (targetNode != null) {
  54615. animationGroup.addTargetedAnimation(animation, targetNode);
  54616. }
  54617. }
  54618. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  54619. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  54620. }
  54621. return animationGroup;
  54622. };
  54623. /**
  54624. * Returns the string "AnimationGroup"
  54625. * @returns "AnimationGroup"
  54626. */
  54627. AnimationGroup.prototype.getClassName = function () {
  54628. return "AnimationGroup";
  54629. };
  54630. /**
  54631. * Creates a detailled string about the object
  54632. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  54633. * @returns a string representing the object
  54634. */
  54635. AnimationGroup.prototype.toString = function (fullDetails) {
  54636. var ret = "Name: " + this.name;
  54637. ret += ", type: " + this.getClassName();
  54638. if (fullDetails) {
  54639. ret += ", from: " + this._from;
  54640. ret += ", to: " + this._to;
  54641. ret += ", isStarted: " + this._isStarted;
  54642. ret += ", speedRatio: " + this._speedRatio;
  54643. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  54644. ret += ", animatables length: " + this._animatables;
  54645. }
  54646. return ret;
  54647. };
  54648. return AnimationGroup;
  54649. }());
  54650. BABYLON.AnimationGroup = AnimationGroup;
  54651. })(BABYLON || (BABYLON = {}));
  54652. //# sourceMappingURL=babylon.animationGroup.js.map
  54653. var BABYLON;
  54654. (function (BABYLON) {
  54655. // Static values to help the garbage collector
  54656. // Quaternion
  54657. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  54658. // Vector3
  54659. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  54660. // Vector2
  54661. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  54662. // Size
  54663. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  54664. // Color3
  54665. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  54666. /**
  54667. * Defines a runtime animation
  54668. */
  54669. var RuntimeAnimation = /** @class */ (function () {
  54670. /**
  54671. * Create a new RuntimeAnimation object
  54672. * @param target defines the target of the animation
  54673. * @param animation defines the source animation object
  54674. * @param scene defines the hosting scene
  54675. * @param host defines the initiating Animatable
  54676. */
  54677. function RuntimeAnimation(target, animation, scene, host) {
  54678. var _this = this;
  54679. this._events = new Array();
  54680. /**
  54681. * The current frame of the runtime animation
  54682. */
  54683. this._currentFrame = 0;
  54684. /**
  54685. * The original value of the runtime animation
  54686. */
  54687. this._originalValue = new Array();
  54688. /**
  54689. * The offsets cache of the runtime animation
  54690. */
  54691. this._offsetsCache = {};
  54692. /**
  54693. * The high limits cache of the runtime animation
  54694. */
  54695. this._highLimitsCache = {};
  54696. /**
  54697. * Specifies if the runtime animation has been stopped
  54698. */
  54699. this._stopped = false;
  54700. /**
  54701. * The blending factor of the runtime animation
  54702. */
  54703. this._blendingFactor = 0;
  54704. /**
  54705. * The target path of the runtime animation
  54706. */
  54707. this._targetPath = "";
  54708. /**
  54709. * The weight of the runtime animation
  54710. */
  54711. this._weight = 1.0;
  54712. /**
  54713. * The ratio offset of the runtime animation
  54714. */
  54715. this._ratioOffset = 0;
  54716. /**
  54717. * The previous delay of the runtime animation
  54718. */
  54719. this._previousDelay = 0;
  54720. /**
  54721. * The previous ratio of the runtime animation
  54722. */
  54723. this._previousRatio = 0;
  54724. this._animation = animation;
  54725. this._target = target;
  54726. this._scene = scene;
  54727. this._host = host;
  54728. animation._runtimeAnimations.push(this);
  54729. // Cloning events locally
  54730. var events = animation.getEvents();
  54731. if (events && events.length > 0) {
  54732. events.forEach(function (e) {
  54733. _this._events.push(e._clone());
  54734. });
  54735. }
  54736. }
  54737. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  54738. /**
  54739. * Gets the current frame of the runtime animation
  54740. */
  54741. get: function () {
  54742. return this._currentFrame;
  54743. },
  54744. enumerable: true,
  54745. configurable: true
  54746. });
  54747. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  54748. /**
  54749. * Gets the weight of the runtime animation
  54750. */
  54751. get: function () {
  54752. return this._weight;
  54753. },
  54754. enumerable: true,
  54755. configurable: true
  54756. });
  54757. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  54758. /**
  54759. * Gets the current value of the runtime animation
  54760. */
  54761. get: function () {
  54762. return this._currentValue;
  54763. },
  54764. enumerable: true,
  54765. configurable: true
  54766. });
  54767. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  54768. /**
  54769. * Gets the target path of the runtime animation
  54770. */
  54771. get: function () {
  54772. return this._targetPath;
  54773. },
  54774. enumerable: true,
  54775. configurable: true
  54776. });
  54777. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  54778. /**
  54779. * Gets the actual target of the runtime animation
  54780. */
  54781. get: function () {
  54782. return this._activeTarget;
  54783. },
  54784. enumerable: true,
  54785. configurable: true
  54786. });
  54787. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  54788. /**
  54789. * Gets the animation from the runtime animation
  54790. */
  54791. get: function () {
  54792. return this._animation;
  54793. },
  54794. enumerable: true,
  54795. configurable: true
  54796. });
  54797. /**
  54798. * Resets the runtime animation to the beginning
  54799. * @param restoreOriginal defines whether to restore the target property to the original value
  54800. */
  54801. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  54802. if (restoreOriginal === void 0) { restoreOriginal = false; }
  54803. if (restoreOriginal) {
  54804. if (this._target instanceof Array) {
  54805. var index = 0;
  54806. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54807. var target = _a[_i];
  54808. if (this._originalValue[index] !== undefined) {
  54809. this._setValue(target, this._originalValue[index], -1);
  54810. }
  54811. index++;
  54812. }
  54813. }
  54814. else {
  54815. if (this._originalValue[0] !== undefined) {
  54816. this._setValue(this._target, this._originalValue[0], -1);
  54817. }
  54818. }
  54819. }
  54820. this._offsetsCache = {};
  54821. this._highLimitsCache = {};
  54822. this._currentFrame = 0;
  54823. this._blendingFactor = 0;
  54824. this._originalValue = new Array();
  54825. // Events
  54826. for (var index = 0; index < this._events.length; index++) {
  54827. this._events[index].isDone = false;
  54828. }
  54829. };
  54830. /**
  54831. * Specifies if the runtime animation is stopped
  54832. * @returns Boolean specifying if the runtime animation is stopped
  54833. */
  54834. RuntimeAnimation.prototype.isStopped = function () {
  54835. return this._stopped;
  54836. };
  54837. /**
  54838. * Disposes of the runtime animation
  54839. */
  54840. RuntimeAnimation.prototype.dispose = function () {
  54841. var index = this._animation.runtimeAnimations.indexOf(this);
  54842. if (index > -1) {
  54843. this._animation.runtimeAnimations.splice(index, 1);
  54844. }
  54845. };
  54846. /**
  54847. * Interpolates the animation from the current frame
  54848. * @param currentFrame The frame to interpolate the animation to
  54849. * @param repeatCount The number of times that the animation should loop
  54850. * @param loopMode The type of looping mode to use
  54851. * @param offsetValue Animation offset value
  54852. * @param highLimitValue The high limit value
  54853. * @returns The interpolated value
  54854. */
  54855. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  54856. this._currentFrame = currentFrame;
  54857. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  54858. this._workValue = BABYLON.Matrix.Zero();
  54859. }
  54860. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  54861. };
  54862. /**
  54863. * Apply the interpolated value to the target
  54864. * @param currentValue defines the value computed by the animation
  54865. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  54866. */
  54867. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  54868. if (weight === void 0) { weight = 1.0; }
  54869. if (this._target instanceof Array) {
  54870. var index = 0;
  54871. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54872. var target = _a[_i];
  54873. this._setValue(target, currentValue, weight, index);
  54874. index++;
  54875. }
  54876. }
  54877. else {
  54878. this._setValue(this._target, currentValue, weight);
  54879. }
  54880. };
  54881. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  54882. if (targetIndex === void 0) { targetIndex = 0; }
  54883. // Set value
  54884. var path;
  54885. var destination;
  54886. var targetPropertyPath = this._animation.targetPropertyPath;
  54887. if (targetPropertyPath.length > 1) {
  54888. var property = target[targetPropertyPath[0]];
  54889. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  54890. property = property[targetPropertyPath[index]];
  54891. }
  54892. path = targetPropertyPath[targetPropertyPath.length - 1];
  54893. destination = property;
  54894. }
  54895. else {
  54896. path = targetPropertyPath[0];
  54897. destination = target;
  54898. }
  54899. this._targetPath = path;
  54900. this._activeTarget = destination;
  54901. this._weight = weight;
  54902. if (this._originalValue[targetIndex] === undefined) {
  54903. var originalValue = void 0;
  54904. if (destination.getRestPose && path === "_matrix") { // For bones
  54905. originalValue = destination.getRestPose();
  54906. }
  54907. else {
  54908. originalValue = destination[path];
  54909. }
  54910. if (originalValue && originalValue.clone) {
  54911. this._originalValue[targetIndex] = originalValue.clone();
  54912. }
  54913. else {
  54914. this._originalValue[targetIndex] = originalValue;
  54915. }
  54916. }
  54917. // Blending
  54918. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  54919. if (enableBlending && this._blendingFactor <= 1.0) {
  54920. if (!this._originalBlendValue) {
  54921. var originalValue = destination[path];
  54922. if (originalValue.clone) {
  54923. this._originalBlendValue = originalValue.clone();
  54924. }
  54925. else {
  54926. this._originalBlendValue = originalValue;
  54927. }
  54928. }
  54929. if (this._originalBlendValue.m) { // Matrix
  54930. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  54931. if (this._currentValue) {
  54932. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54933. }
  54934. else {
  54935. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54936. }
  54937. }
  54938. else {
  54939. if (this._currentValue) {
  54940. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54941. }
  54942. else {
  54943. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54944. }
  54945. }
  54946. }
  54947. else {
  54948. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54949. }
  54950. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  54951. this._blendingFactor += blendingSpeed;
  54952. }
  54953. else {
  54954. this._currentValue = currentValue;
  54955. }
  54956. if (weight !== -1.0) {
  54957. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  54958. }
  54959. else {
  54960. destination[path] = this._currentValue;
  54961. }
  54962. if (target.markAsDirty) {
  54963. target.markAsDirty(this._animation.targetProperty);
  54964. }
  54965. };
  54966. /**
  54967. * Gets the loop pmode of the runtime animation
  54968. * @returns Loop Mode
  54969. */
  54970. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  54971. if (this._target && this._target.animationPropertiesOverride) {
  54972. return this._target.animationPropertiesOverride.loopMode;
  54973. }
  54974. return this._animation.loopMode;
  54975. };
  54976. /**
  54977. * Move the current animation to a given frame
  54978. * @param frame defines the frame to move to
  54979. */
  54980. RuntimeAnimation.prototype.goToFrame = function (frame) {
  54981. var keys = this._animation.getKeys();
  54982. if (frame < keys[0].frame) {
  54983. frame = keys[0].frame;
  54984. }
  54985. else if (frame > keys[keys.length - 1].frame) {
  54986. frame = keys[keys.length - 1].frame;
  54987. }
  54988. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  54989. this.setValue(currentValue, -1);
  54990. };
  54991. /**
  54992. * @hidden Internal use only
  54993. */
  54994. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  54995. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  54996. this._ratioOffset = this._previousRatio - newRatio;
  54997. };
  54998. /**
  54999. * Execute the current animation
  55000. * @param delay defines the delay to add to the current frame
  55001. * @param from defines the lower bound of the animation range
  55002. * @param to defines the upper bound of the animation range
  55003. * @param loop defines if the current animation must loop
  55004. * @param speedRatio defines the current speed ratio
  55005. * @param weight defines the weight of the animation (default is -1 so no weight)
  55006. * @returns a boolean indicating if the animation is running
  55007. */
  55008. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  55009. if (weight === void 0) { weight = -1.0; }
  55010. var targetPropertyPath = this._animation.targetPropertyPath;
  55011. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55012. this._stopped = true;
  55013. return false;
  55014. }
  55015. var returnValue = true;
  55016. var keys = this._animation.getKeys();
  55017. // Adding a start key at frame 0 if missing
  55018. if (keys[0].frame !== 0) {
  55019. var newKey = { frame: 0, value: keys[0].value };
  55020. keys.splice(0, 0, newKey);
  55021. }
  55022. // Adding a duplicate key when there is only one key at frame zero
  55023. else if (keys.length === 1) {
  55024. var newKey = { frame: 0.001, value: keys[0].value };
  55025. keys.push(newKey);
  55026. }
  55027. // Check limits
  55028. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55029. from = keys[0].frame;
  55030. }
  55031. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55032. to = keys[keys.length - 1].frame;
  55033. }
  55034. //to and from cannot be the same key
  55035. if (from === to) {
  55036. if (from > keys[0].frame) {
  55037. from--;
  55038. }
  55039. else if (to < keys[keys.length - 1].frame) {
  55040. to++;
  55041. }
  55042. }
  55043. // Compute ratio
  55044. var range = to - from;
  55045. var offsetValue;
  55046. // ratio represents the frame delta between from and to
  55047. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55048. var highLimitValue = 0;
  55049. this._previousDelay = delay;
  55050. this._previousRatio = ratio;
  55051. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55052. returnValue = false;
  55053. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55054. }
  55055. else {
  55056. // Get max value if required
  55057. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55058. var keyOffset = to.toString() + from.toString();
  55059. if (!this._offsetsCache[keyOffset]) {
  55060. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55061. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55062. switch (this._animation.dataType) {
  55063. // Float
  55064. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55065. this._offsetsCache[keyOffset] = toValue - fromValue;
  55066. break;
  55067. // Quaternion
  55068. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55069. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55070. break;
  55071. // Vector3
  55072. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55073. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55074. // Vector2
  55075. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55076. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55077. // Size
  55078. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55079. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55080. // Color3
  55081. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55082. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55083. default:
  55084. break;
  55085. }
  55086. this._highLimitsCache[keyOffset] = toValue;
  55087. }
  55088. highLimitValue = this._highLimitsCache[keyOffset];
  55089. offsetValue = this._offsetsCache[keyOffset];
  55090. }
  55091. }
  55092. if (offsetValue === undefined) {
  55093. switch (this._animation.dataType) {
  55094. // Float
  55095. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55096. offsetValue = 0;
  55097. break;
  55098. // Quaternion
  55099. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55100. offsetValue = _staticOffsetValueQuaternion;
  55101. break;
  55102. // Vector3
  55103. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55104. offsetValue = _staticOffsetValueVector3;
  55105. break;
  55106. // Vector2
  55107. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55108. offsetValue = _staticOffsetValueVector2;
  55109. break;
  55110. // Size
  55111. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55112. offsetValue = _staticOffsetValueSize;
  55113. break;
  55114. // Color3
  55115. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55116. offsetValue = _staticOffsetValueColor3;
  55117. }
  55118. }
  55119. // Compute value
  55120. var repeatCount = (ratio / range) >> 0;
  55121. var currentFrame = returnValue ? from + ratio % range : to;
  55122. // Need to normalize?
  55123. if (this._host && this._host.syncRoot) {
  55124. var syncRoot = this._host.syncRoot;
  55125. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55126. currentFrame = from + (to - from) * hostNormalizedFrame;
  55127. }
  55128. // Reset events if looping
  55129. var events = this._events;
  55130. if (range > 0 && this.currentFrame > currentFrame ||
  55131. range < 0 && this.currentFrame < currentFrame) {
  55132. // Need to reset animation events
  55133. for (var index = 0; index < events.length; index++) {
  55134. if (!events[index].onlyOnce) {
  55135. // reset event, the animation is looping
  55136. events[index].isDone = false;
  55137. }
  55138. }
  55139. }
  55140. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55141. // Set value
  55142. this.setValue(currentValue, weight);
  55143. // Check events
  55144. for (var index = 0; index < events.length; index++) {
  55145. // Make sure current frame has passed event frame and that event frame is within the current range
  55146. // Also, handle both forward and reverse animations
  55147. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55148. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55149. var event = events[index];
  55150. if (!event.isDone) {
  55151. // If event should be done only once, remove it.
  55152. if (event.onlyOnce) {
  55153. events.splice(index, 1);
  55154. index--;
  55155. }
  55156. event.isDone = true;
  55157. event.action(currentFrame);
  55158. } // Don't do anything if the event has already be done.
  55159. }
  55160. }
  55161. if (!returnValue) {
  55162. this._stopped = true;
  55163. }
  55164. return returnValue;
  55165. };
  55166. return RuntimeAnimation;
  55167. }());
  55168. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55169. })(BABYLON || (BABYLON = {}));
  55170. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55171. var BABYLON;
  55172. (function (BABYLON) {
  55173. /**
  55174. * Class used to store an actual running animation
  55175. */
  55176. var Animatable = /** @class */ (function () {
  55177. /**
  55178. * Creates a new Animatable
  55179. * @param scene defines the hosting scene
  55180. * @param target defines the target object
  55181. * @param fromFrame defines the starting frame number (default is 0)
  55182. * @param toFrame defines the ending frame number (default is 100)
  55183. * @param loopAnimation defines if the animation must loop (default is false)
  55184. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55185. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55186. * @param animations defines a group of animation to add to the new Animatable
  55187. */
  55188. function Animatable(scene,
  55189. /** defines the target object */
  55190. target,
  55191. /** defines the starting frame number (default is 0) */
  55192. fromFrame,
  55193. /** defines the ending frame number (default is 100) */
  55194. toFrame,
  55195. /** defines if the animation must loop (default is false) */
  55196. loopAnimation, speedRatio,
  55197. /** defines a callback to call when animation ends if it is not looping */
  55198. onAnimationEnd, animations) {
  55199. if (fromFrame === void 0) { fromFrame = 0; }
  55200. if (toFrame === void 0) { toFrame = 100; }
  55201. if (loopAnimation === void 0) { loopAnimation = false; }
  55202. if (speedRatio === void 0) { speedRatio = 1.0; }
  55203. this.target = target;
  55204. this.fromFrame = fromFrame;
  55205. this.toFrame = toFrame;
  55206. this.loopAnimation = loopAnimation;
  55207. this.onAnimationEnd = onAnimationEnd;
  55208. this._localDelayOffset = null;
  55209. this._pausedDelay = null;
  55210. this._runtimeAnimations = new Array();
  55211. this._paused = false;
  55212. this._speedRatio = 1;
  55213. this._weight = -1.0;
  55214. /**
  55215. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55216. * This will only apply for non looping animation (default is true)
  55217. */
  55218. this.disposeOnEnd = true;
  55219. /**
  55220. * Gets a boolean indicating if the animation has started
  55221. */
  55222. this.animationStarted = false;
  55223. /**
  55224. * Observer raised when the animation ends
  55225. */
  55226. this.onAnimationEndObservable = new BABYLON.Observable();
  55227. this._scene = scene;
  55228. if (animations) {
  55229. this.appendAnimations(target, animations);
  55230. }
  55231. this._speedRatio = speedRatio;
  55232. scene._activeAnimatables.push(this);
  55233. }
  55234. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55235. /**
  55236. * Gets the root Animatable used to synchronize and normalize animations
  55237. */
  55238. get: function () {
  55239. return this._syncRoot;
  55240. },
  55241. enumerable: true,
  55242. configurable: true
  55243. });
  55244. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55245. /**
  55246. * Gets the current frame of the first RuntimeAnimation
  55247. * Used to synchronize Animatables
  55248. */
  55249. get: function () {
  55250. if (this._runtimeAnimations.length === 0) {
  55251. return 0;
  55252. }
  55253. return this._runtimeAnimations[0].currentFrame;
  55254. },
  55255. enumerable: true,
  55256. configurable: true
  55257. });
  55258. Object.defineProperty(Animatable.prototype, "weight", {
  55259. /**
  55260. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55261. */
  55262. get: function () {
  55263. return this._weight;
  55264. },
  55265. set: function (value) {
  55266. if (value === -1) { // -1 is ok and means no weight
  55267. this._weight = -1;
  55268. return;
  55269. }
  55270. // Else weight must be in [0, 1] range
  55271. this._weight = Math.min(Math.max(value, 0), 1.0);
  55272. },
  55273. enumerable: true,
  55274. configurable: true
  55275. });
  55276. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55277. /**
  55278. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55279. */
  55280. get: function () {
  55281. return this._speedRatio;
  55282. },
  55283. set: function (value) {
  55284. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55285. var animation = this._runtimeAnimations[index];
  55286. animation._prepareForSpeedRatioChange(value);
  55287. }
  55288. this._speedRatio = value;
  55289. },
  55290. enumerable: true,
  55291. configurable: true
  55292. });
  55293. // Methods
  55294. /**
  55295. * Synchronize and normalize current Animatable with a source Animatable
  55296. * This is useful when using animation weights and when animations are not of the same length
  55297. * @param root defines the root Animatable to synchronize with
  55298. * @returns the current Animatable
  55299. */
  55300. Animatable.prototype.syncWith = function (root) {
  55301. this._syncRoot = root;
  55302. if (root) {
  55303. // Make sure this animatable will animate after the root
  55304. var index = this._scene._activeAnimatables.indexOf(this);
  55305. if (index > -1) {
  55306. this._scene._activeAnimatables.splice(index, 1);
  55307. this._scene._activeAnimatables.push(this);
  55308. }
  55309. }
  55310. return this;
  55311. };
  55312. /**
  55313. * Gets the list of runtime animations
  55314. * @returns an array of RuntimeAnimation
  55315. */
  55316. Animatable.prototype.getAnimations = function () {
  55317. return this._runtimeAnimations;
  55318. };
  55319. /**
  55320. * Adds more animations to the current animatable
  55321. * @param target defines the target of the animations
  55322. * @param animations defines the new animations to add
  55323. */
  55324. Animatable.prototype.appendAnimations = function (target, animations) {
  55325. for (var index = 0; index < animations.length; index++) {
  55326. var animation = animations[index];
  55327. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55328. }
  55329. };
  55330. /**
  55331. * Gets the source animation for a specific property
  55332. * @param property defines the propertyu to look for
  55333. * @returns null or the source animation for the given property
  55334. */
  55335. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55336. var runtimeAnimations = this._runtimeAnimations;
  55337. for (var index = 0; index < runtimeAnimations.length; index++) {
  55338. if (runtimeAnimations[index].animation.targetProperty === property) {
  55339. return runtimeAnimations[index].animation;
  55340. }
  55341. }
  55342. return null;
  55343. };
  55344. /**
  55345. * Gets the runtime animation for a specific property
  55346. * @param property defines the propertyu to look for
  55347. * @returns null or the runtime animation for the given property
  55348. */
  55349. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55350. var runtimeAnimations = this._runtimeAnimations;
  55351. for (var index = 0; index < runtimeAnimations.length; index++) {
  55352. if (runtimeAnimations[index].animation.targetProperty === property) {
  55353. return runtimeAnimations[index];
  55354. }
  55355. }
  55356. return null;
  55357. };
  55358. /**
  55359. * Resets the animatable to its original state
  55360. */
  55361. Animatable.prototype.reset = function () {
  55362. var runtimeAnimations = this._runtimeAnimations;
  55363. for (var index = 0; index < runtimeAnimations.length; index++) {
  55364. runtimeAnimations[index].reset(true);
  55365. }
  55366. this._localDelayOffset = null;
  55367. this._pausedDelay = null;
  55368. };
  55369. /**
  55370. * Allows the animatable to blend with current running animations
  55371. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55372. * @param blendingSpeed defines the blending speed to use
  55373. */
  55374. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55375. var runtimeAnimations = this._runtimeAnimations;
  55376. for (var index = 0; index < runtimeAnimations.length; index++) {
  55377. runtimeAnimations[index].animation.enableBlending = true;
  55378. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55379. }
  55380. };
  55381. /**
  55382. * Disable animation blending
  55383. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55384. */
  55385. Animatable.prototype.disableBlending = function () {
  55386. var runtimeAnimations = this._runtimeAnimations;
  55387. for (var index = 0; index < runtimeAnimations.length; index++) {
  55388. runtimeAnimations[index].animation.enableBlending = false;
  55389. }
  55390. };
  55391. /**
  55392. * Jump directly to a given frame
  55393. * @param frame defines the frame to jump to
  55394. */
  55395. Animatable.prototype.goToFrame = function (frame) {
  55396. var runtimeAnimations = this._runtimeAnimations;
  55397. if (runtimeAnimations[0]) {
  55398. var fps = runtimeAnimations[0].animation.framePerSecond;
  55399. var currentFrame = runtimeAnimations[0].currentFrame;
  55400. var adjustTime = frame - currentFrame;
  55401. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55402. if (this._localDelayOffset === null) {
  55403. this._localDelayOffset = 0;
  55404. }
  55405. this._localDelayOffset -= delay;
  55406. }
  55407. for (var index = 0; index < runtimeAnimations.length; index++) {
  55408. runtimeAnimations[index].goToFrame(frame);
  55409. }
  55410. };
  55411. /**
  55412. * Pause the animation
  55413. */
  55414. Animatable.prototype.pause = function () {
  55415. if (this._paused) {
  55416. return;
  55417. }
  55418. this._paused = true;
  55419. };
  55420. /**
  55421. * Restart the animation
  55422. */
  55423. Animatable.prototype.restart = function () {
  55424. this._paused = false;
  55425. };
  55426. Animatable.prototype._raiseOnAnimationEnd = function () {
  55427. if (this.onAnimationEnd) {
  55428. this.onAnimationEnd();
  55429. }
  55430. this.onAnimationEndObservable.notifyObservers(this);
  55431. };
  55432. /**
  55433. * Stop and delete the current animation
  55434. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55435. * @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)
  55436. */
  55437. Animatable.prototype.stop = function (animationName, targetMask) {
  55438. if (animationName || targetMask) {
  55439. var idx = this._scene._activeAnimatables.indexOf(this);
  55440. if (idx > -1) {
  55441. var runtimeAnimations = this._runtimeAnimations;
  55442. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55443. var runtimeAnimation = runtimeAnimations[index];
  55444. if (animationName && runtimeAnimation.animation.name != animationName) {
  55445. continue;
  55446. }
  55447. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55448. continue;
  55449. }
  55450. runtimeAnimation.dispose();
  55451. runtimeAnimations.splice(index, 1);
  55452. }
  55453. if (runtimeAnimations.length == 0) {
  55454. this._scene._activeAnimatables.splice(idx, 1);
  55455. this._raiseOnAnimationEnd();
  55456. }
  55457. }
  55458. }
  55459. else {
  55460. var index = this._scene._activeAnimatables.indexOf(this);
  55461. if (index > -1) {
  55462. this._scene._activeAnimatables.splice(index, 1);
  55463. var runtimeAnimations = this._runtimeAnimations;
  55464. for (var index = 0; index < runtimeAnimations.length; index++) {
  55465. runtimeAnimations[index].dispose();
  55466. }
  55467. this._raiseOnAnimationEnd();
  55468. }
  55469. }
  55470. };
  55471. /**
  55472. * Wait asynchronously for the animation to end
  55473. * @returns a promise which will be fullfilled when the animation ends
  55474. */
  55475. Animatable.prototype.waitAsync = function () {
  55476. var _this = this;
  55477. return new Promise(function (resolve, reject) {
  55478. _this.onAnimationEndObservable.add(function () {
  55479. resolve(_this);
  55480. }, undefined, undefined, _this, true);
  55481. });
  55482. };
  55483. /** @hidden */
  55484. Animatable.prototype._animate = function (delay) {
  55485. if (this._paused) {
  55486. this.animationStarted = false;
  55487. if (this._pausedDelay === null) {
  55488. this._pausedDelay = delay;
  55489. }
  55490. return true;
  55491. }
  55492. if (this._localDelayOffset === null) {
  55493. this._localDelayOffset = delay;
  55494. this._pausedDelay = null;
  55495. }
  55496. else if (this._pausedDelay !== null) {
  55497. this._localDelayOffset += delay - this._pausedDelay;
  55498. this._pausedDelay = null;
  55499. }
  55500. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55501. return true;
  55502. }
  55503. // Animating
  55504. var running = false;
  55505. var runtimeAnimations = this._runtimeAnimations;
  55506. var index;
  55507. for (index = 0; index < runtimeAnimations.length; index++) {
  55508. var animation = runtimeAnimations[index];
  55509. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55510. running = running || isRunning;
  55511. }
  55512. this.animationStarted = running;
  55513. if (!running) {
  55514. if (this.disposeOnEnd) {
  55515. // Remove from active animatables
  55516. index = this._scene._activeAnimatables.indexOf(this);
  55517. this._scene._activeAnimatables.splice(index, 1);
  55518. // Dispose all runtime animations
  55519. for (index = 0; index < runtimeAnimations.length; index++) {
  55520. runtimeAnimations[index].dispose();
  55521. }
  55522. }
  55523. this._raiseOnAnimationEnd();
  55524. if (this.disposeOnEnd) {
  55525. this.onAnimationEnd = null;
  55526. this.onAnimationEndObservable.clear();
  55527. }
  55528. }
  55529. return running;
  55530. };
  55531. return Animatable;
  55532. }());
  55533. BABYLON.Animatable = Animatable;
  55534. })(BABYLON || (BABYLON = {}));
  55535. //# sourceMappingURL=babylon.animatable.js.map
  55536. var BABYLON;
  55537. (function (BABYLON) {
  55538. /**
  55539. * Base class used for every default easing function.
  55540. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55541. */
  55542. var EasingFunction = /** @class */ (function () {
  55543. function EasingFunction() {
  55544. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55545. }
  55546. /**
  55547. * Sets the easing mode of the current function.
  55548. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55549. */
  55550. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55551. var n = Math.min(Math.max(easingMode, 0), 2);
  55552. this._easingMode = n;
  55553. };
  55554. /**
  55555. * Gets the current easing mode.
  55556. * @returns the easing mode
  55557. */
  55558. EasingFunction.prototype.getEasingMode = function () {
  55559. return this._easingMode;
  55560. };
  55561. /**
  55562. * @hidden
  55563. */
  55564. EasingFunction.prototype.easeInCore = function (gradient) {
  55565. throw new Error('You must implement this method');
  55566. };
  55567. /**
  55568. * Given an input gradient between 0 and 1, this returns the corrseponding value
  55569. * of the easing function.
  55570. * @param gradient Defines the value between 0 and 1 we want the easing value for
  55571. * @returns the corresponding value on the curve defined by the easing function
  55572. */
  55573. EasingFunction.prototype.ease = function (gradient) {
  55574. switch (this._easingMode) {
  55575. case EasingFunction.EASINGMODE_EASEIN:
  55576. return this.easeInCore(gradient);
  55577. case EasingFunction.EASINGMODE_EASEOUT:
  55578. return (1 - this.easeInCore(1 - gradient));
  55579. }
  55580. if (gradient >= 0.5) {
  55581. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  55582. }
  55583. return (this.easeInCore(gradient * 2) * 0.5);
  55584. };
  55585. /**
  55586. * Interpolation follows the mathematical formula associated with the easing function.
  55587. */
  55588. EasingFunction.EASINGMODE_EASEIN = 0;
  55589. /**
  55590. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  55591. */
  55592. EasingFunction.EASINGMODE_EASEOUT = 1;
  55593. /**
  55594. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  55595. */
  55596. EasingFunction.EASINGMODE_EASEINOUT = 2;
  55597. return EasingFunction;
  55598. }());
  55599. BABYLON.EasingFunction = EasingFunction;
  55600. /**
  55601. * Easing function with a circle shape (see link below).
  55602. * @see https://easings.net/#easeInCirc
  55603. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55604. */
  55605. var CircleEase = /** @class */ (function (_super) {
  55606. __extends(CircleEase, _super);
  55607. function CircleEase() {
  55608. return _super !== null && _super.apply(this, arguments) || this;
  55609. }
  55610. /** @hidden */
  55611. CircleEase.prototype.easeInCore = function (gradient) {
  55612. gradient = Math.max(0, Math.min(1, gradient));
  55613. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  55614. };
  55615. return CircleEase;
  55616. }(EasingFunction));
  55617. BABYLON.CircleEase = CircleEase;
  55618. /**
  55619. * Easing function with a ease back shape (see link below).
  55620. * @see https://easings.net/#easeInBack
  55621. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55622. */
  55623. var BackEase = /** @class */ (function (_super) {
  55624. __extends(BackEase, _super);
  55625. /**
  55626. * Instantiates a back ease easing
  55627. * @see https://easings.net/#easeInBack
  55628. * @param amplitude Defines the amplitude of the function
  55629. */
  55630. function BackEase(
  55631. /** Defines the amplitude of the function */
  55632. amplitude) {
  55633. if (amplitude === void 0) { amplitude = 1; }
  55634. var _this = _super.call(this) || this;
  55635. _this.amplitude = amplitude;
  55636. return _this;
  55637. }
  55638. /** @hidden */
  55639. BackEase.prototype.easeInCore = function (gradient) {
  55640. var num = Math.max(0, this.amplitude);
  55641. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  55642. };
  55643. return BackEase;
  55644. }(EasingFunction));
  55645. BABYLON.BackEase = BackEase;
  55646. /**
  55647. * Easing function with a bouncing shape (see link below).
  55648. * @see https://easings.net/#easeInBounce
  55649. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55650. */
  55651. var BounceEase = /** @class */ (function (_super) {
  55652. __extends(BounceEase, _super);
  55653. /**
  55654. * Instantiates a bounce easing
  55655. * @see https://easings.net/#easeInBounce
  55656. * @param bounces Defines the number of bounces
  55657. * @param bounciness Defines the amplitude of the bounce
  55658. */
  55659. function BounceEase(
  55660. /** Defines the number of bounces */
  55661. bounces,
  55662. /** Defines the amplitude of the bounce */
  55663. bounciness) {
  55664. if (bounces === void 0) { bounces = 3; }
  55665. if (bounciness === void 0) { bounciness = 2; }
  55666. var _this = _super.call(this) || this;
  55667. _this.bounces = bounces;
  55668. _this.bounciness = bounciness;
  55669. return _this;
  55670. }
  55671. /** @hidden */
  55672. BounceEase.prototype.easeInCore = function (gradient) {
  55673. var y = Math.max(0.0, this.bounces);
  55674. var bounciness = this.bounciness;
  55675. if (bounciness <= 1.0) {
  55676. bounciness = 1.001;
  55677. }
  55678. var num9 = Math.pow(bounciness, y);
  55679. var num5 = 1.0 - bounciness;
  55680. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  55681. var num15 = gradient * num4;
  55682. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  55683. var num3 = Math.floor(num65);
  55684. var num13 = num3 + 1.0;
  55685. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  55686. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  55687. var num7 = (num8 + num12) * 0.5;
  55688. var num6 = gradient - num7;
  55689. var num2 = num7 - num8;
  55690. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  55691. };
  55692. return BounceEase;
  55693. }(EasingFunction));
  55694. BABYLON.BounceEase = BounceEase;
  55695. /**
  55696. * Easing function with a power of 3 shape (see link below).
  55697. * @see https://easings.net/#easeInCubic
  55698. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55699. */
  55700. var CubicEase = /** @class */ (function (_super) {
  55701. __extends(CubicEase, _super);
  55702. function CubicEase() {
  55703. return _super !== null && _super.apply(this, arguments) || this;
  55704. }
  55705. /** @hidden */
  55706. CubicEase.prototype.easeInCore = function (gradient) {
  55707. return (gradient * gradient * gradient);
  55708. };
  55709. return CubicEase;
  55710. }(EasingFunction));
  55711. BABYLON.CubicEase = CubicEase;
  55712. /**
  55713. * Easing function with an elastic shape (see link below).
  55714. * @see https://easings.net/#easeInElastic
  55715. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55716. */
  55717. var ElasticEase = /** @class */ (function (_super) {
  55718. __extends(ElasticEase, _super);
  55719. /**
  55720. * Instantiates an elastic easing function
  55721. * @see https://easings.net/#easeInElastic
  55722. * @param oscillations Defines the number of oscillations
  55723. * @param springiness Defines the amplitude of the oscillations
  55724. */
  55725. function ElasticEase(
  55726. /** Defines the number of oscillations*/
  55727. oscillations,
  55728. /** Defines the amplitude of the oscillations*/
  55729. springiness) {
  55730. if (oscillations === void 0) { oscillations = 3; }
  55731. if (springiness === void 0) { springiness = 3; }
  55732. var _this = _super.call(this) || this;
  55733. _this.oscillations = oscillations;
  55734. _this.springiness = springiness;
  55735. return _this;
  55736. }
  55737. /** @hidden */
  55738. ElasticEase.prototype.easeInCore = function (gradient) {
  55739. var num2;
  55740. var num3 = Math.max(0.0, this.oscillations);
  55741. var num = Math.max(0.0, this.springiness);
  55742. if (num == 0) {
  55743. num2 = gradient;
  55744. }
  55745. else {
  55746. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  55747. }
  55748. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  55749. };
  55750. return ElasticEase;
  55751. }(EasingFunction));
  55752. BABYLON.ElasticEase = ElasticEase;
  55753. /**
  55754. * Easing function with an exponential shape (see link below).
  55755. * @see https://easings.net/#easeInExpo
  55756. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55757. */
  55758. var ExponentialEase = /** @class */ (function (_super) {
  55759. __extends(ExponentialEase, _super);
  55760. /**
  55761. * Instantiates an exponential easing function
  55762. * @see https://easings.net/#easeInExpo
  55763. * @param exponent Defines the exponent of the function
  55764. */
  55765. function ExponentialEase(
  55766. /** Defines the exponent of the function */
  55767. exponent) {
  55768. if (exponent === void 0) { exponent = 2; }
  55769. var _this = _super.call(this) || this;
  55770. _this.exponent = exponent;
  55771. return _this;
  55772. }
  55773. /** @hidden */
  55774. ExponentialEase.prototype.easeInCore = function (gradient) {
  55775. if (this.exponent <= 0) {
  55776. return gradient;
  55777. }
  55778. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  55779. };
  55780. return ExponentialEase;
  55781. }(EasingFunction));
  55782. BABYLON.ExponentialEase = ExponentialEase;
  55783. /**
  55784. * Easing function with a power shape (see link below).
  55785. * @see https://easings.net/#easeInQuad
  55786. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55787. */
  55788. var PowerEase = /** @class */ (function (_super) {
  55789. __extends(PowerEase, _super);
  55790. /**
  55791. * Instantiates an power base easing function
  55792. * @see https://easings.net/#easeInQuad
  55793. * @param power Defines the power of the function
  55794. */
  55795. function PowerEase(
  55796. /** Defines the power of the function */
  55797. power) {
  55798. if (power === void 0) { power = 2; }
  55799. var _this = _super.call(this) || this;
  55800. _this.power = power;
  55801. return _this;
  55802. }
  55803. /** @hidden */
  55804. PowerEase.prototype.easeInCore = function (gradient) {
  55805. var y = Math.max(0.0, this.power);
  55806. return Math.pow(gradient, y);
  55807. };
  55808. return PowerEase;
  55809. }(EasingFunction));
  55810. BABYLON.PowerEase = PowerEase;
  55811. /**
  55812. * Easing function with a power of 2 shape (see link below).
  55813. * @see https://easings.net/#easeInQuad
  55814. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55815. */
  55816. var QuadraticEase = /** @class */ (function (_super) {
  55817. __extends(QuadraticEase, _super);
  55818. function QuadraticEase() {
  55819. return _super !== null && _super.apply(this, arguments) || this;
  55820. }
  55821. /** @hidden */
  55822. QuadraticEase.prototype.easeInCore = function (gradient) {
  55823. return (gradient * gradient);
  55824. };
  55825. return QuadraticEase;
  55826. }(EasingFunction));
  55827. BABYLON.QuadraticEase = QuadraticEase;
  55828. /**
  55829. * Easing function with a power of 4 shape (see link below).
  55830. * @see https://easings.net/#easeInQuart
  55831. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55832. */
  55833. var QuarticEase = /** @class */ (function (_super) {
  55834. __extends(QuarticEase, _super);
  55835. function QuarticEase() {
  55836. return _super !== null && _super.apply(this, arguments) || this;
  55837. }
  55838. /** @hidden */
  55839. QuarticEase.prototype.easeInCore = function (gradient) {
  55840. return (gradient * gradient * gradient * gradient);
  55841. };
  55842. return QuarticEase;
  55843. }(EasingFunction));
  55844. BABYLON.QuarticEase = QuarticEase;
  55845. /**
  55846. * Easing function with a power of 5 shape (see link below).
  55847. * @see https://easings.net/#easeInQuint
  55848. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55849. */
  55850. var QuinticEase = /** @class */ (function (_super) {
  55851. __extends(QuinticEase, _super);
  55852. function QuinticEase() {
  55853. return _super !== null && _super.apply(this, arguments) || this;
  55854. }
  55855. /** @hidden */
  55856. QuinticEase.prototype.easeInCore = function (gradient) {
  55857. return (gradient * gradient * gradient * gradient * gradient);
  55858. };
  55859. return QuinticEase;
  55860. }(EasingFunction));
  55861. BABYLON.QuinticEase = QuinticEase;
  55862. /**
  55863. * Easing function with a sin shape (see link below).
  55864. * @see https://easings.net/#easeInSine
  55865. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55866. */
  55867. var SineEase = /** @class */ (function (_super) {
  55868. __extends(SineEase, _super);
  55869. function SineEase() {
  55870. return _super !== null && _super.apply(this, arguments) || this;
  55871. }
  55872. /** @hidden */
  55873. SineEase.prototype.easeInCore = function (gradient) {
  55874. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  55875. };
  55876. return SineEase;
  55877. }(EasingFunction));
  55878. BABYLON.SineEase = SineEase;
  55879. /**
  55880. * Easing function with a bezier shape (see link below).
  55881. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55882. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55883. */
  55884. var BezierCurveEase = /** @class */ (function (_super) {
  55885. __extends(BezierCurveEase, _super);
  55886. /**
  55887. * Instantiates a bezier function
  55888. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55889. * @param x1 Defines the x component of the start tangent in the bezier curve
  55890. * @param y1 Defines the y component of the start tangent in the bezier curve
  55891. * @param x2 Defines the x component of the end tangent in the bezier curve
  55892. * @param y2 Defines the y component of the end tangent in the bezier curve
  55893. */
  55894. function BezierCurveEase(
  55895. /** Defines the x component of the start tangent in the bezier curve */
  55896. x1,
  55897. /** Defines the y component of the start tangent in the bezier curve */
  55898. y1,
  55899. /** Defines the x component of the end tangent in the bezier curve */
  55900. x2,
  55901. /** Defines the y component of the end tangent in the bezier curve */
  55902. y2) {
  55903. if (x1 === void 0) { x1 = 0; }
  55904. if (y1 === void 0) { y1 = 0; }
  55905. if (x2 === void 0) { x2 = 1; }
  55906. if (y2 === void 0) { y2 = 1; }
  55907. var _this = _super.call(this) || this;
  55908. _this.x1 = x1;
  55909. _this.y1 = y1;
  55910. _this.x2 = x2;
  55911. _this.y2 = y2;
  55912. return _this;
  55913. }
  55914. /** @hidden */
  55915. BezierCurveEase.prototype.easeInCore = function (gradient) {
  55916. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  55917. };
  55918. return BezierCurveEase;
  55919. }(EasingFunction));
  55920. BABYLON.BezierCurveEase = BezierCurveEase;
  55921. })(BABYLON || (BABYLON = {}));
  55922. //# sourceMappingURL=babylon.easing.js.map
  55923. var BABYLON;
  55924. (function (BABYLON) {
  55925. /**
  55926. * A Condition applied to an Action
  55927. */
  55928. var Condition = /** @class */ (function () {
  55929. /**
  55930. * Creates a new Condition
  55931. * @param actionManager the manager of the action the condition is applied to
  55932. */
  55933. function Condition(actionManager) {
  55934. this._actionManager = actionManager;
  55935. }
  55936. /**
  55937. * Check if the current condition is valid
  55938. * @returns a boolean
  55939. */
  55940. Condition.prototype.isValid = function () {
  55941. return true;
  55942. };
  55943. /**
  55944. * Internal only
  55945. * @hidden
  55946. */
  55947. Condition.prototype._getProperty = function (propertyPath) {
  55948. return this._actionManager._getProperty(propertyPath);
  55949. };
  55950. /**
  55951. * Internal only
  55952. * @hidden
  55953. */
  55954. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  55955. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55956. };
  55957. /**
  55958. * Serialize placeholder for child classes
  55959. * @returns the serialized object
  55960. */
  55961. Condition.prototype.serialize = function () {
  55962. };
  55963. /**
  55964. * Internal only
  55965. * @hidden
  55966. */
  55967. Condition.prototype._serialize = function (serializedCondition) {
  55968. return {
  55969. type: 2,
  55970. children: [],
  55971. name: serializedCondition.name,
  55972. properties: serializedCondition.properties
  55973. };
  55974. };
  55975. return Condition;
  55976. }());
  55977. BABYLON.Condition = Condition;
  55978. /**
  55979. * Defines specific conditional operators as extensions of Condition
  55980. */
  55981. var ValueCondition = /** @class */ (function (_super) {
  55982. __extends(ValueCondition, _super);
  55983. /**
  55984. * Creates a new ValueCondition
  55985. * @param actionManager manager for the action the condition applies to
  55986. * @param target for the action
  55987. * @param propertyPath path to specify the property of the target the conditional operator uses
  55988. * @param value the value compared by the conditional operator against the current value of the property
  55989. * @param operator the conditional operator, default ValueCondition.IsEqual
  55990. */
  55991. function ValueCondition(actionManager, target,
  55992. /** path to specify the property of the target the conditional operator uses */
  55993. propertyPath,
  55994. /** the value compared by the conditional operator against the current value of the property */
  55995. value,
  55996. /** the conditional operator, default ValueCondition.IsEqual */
  55997. operator) {
  55998. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  55999. var _this = _super.call(this, actionManager) || this;
  56000. _this.propertyPath = propertyPath;
  56001. _this.value = value;
  56002. _this.operator = operator;
  56003. _this._target = target;
  56004. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56005. _this._property = _this._getProperty(_this.propertyPath);
  56006. return _this;
  56007. }
  56008. Object.defineProperty(ValueCondition, "IsEqual", {
  56009. /**
  56010. * returns the number for IsEqual
  56011. */
  56012. get: function () {
  56013. return ValueCondition._IsEqual;
  56014. },
  56015. enumerable: true,
  56016. configurable: true
  56017. });
  56018. Object.defineProperty(ValueCondition, "IsDifferent", {
  56019. /**
  56020. * Returns the number for IsDifferent
  56021. */
  56022. get: function () {
  56023. return ValueCondition._IsDifferent;
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(ValueCondition, "IsGreater", {
  56029. /**
  56030. * Returns the number for IsGreater
  56031. */
  56032. get: function () {
  56033. return ValueCondition._IsGreater;
  56034. },
  56035. enumerable: true,
  56036. configurable: true
  56037. });
  56038. Object.defineProperty(ValueCondition, "IsLesser", {
  56039. /**
  56040. * Returns the number for IsLesser
  56041. */
  56042. get: function () {
  56043. return ValueCondition._IsLesser;
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. /**
  56049. * Compares the given value with the property value for the specified conditional operator
  56050. * @returns the result of the comparison
  56051. */
  56052. ValueCondition.prototype.isValid = function () {
  56053. switch (this.operator) {
  56054. case ValueCondition.IsGreater:
  56055. return this._effectiveTarget[this._property] > this.value;
  56056. case ValueCondition.IsLesser:
  56057. return this._effectiveTarget[this._property] < this.value;
  56058. case ValueCondition.IsEqual:
  56059. case ValueCondition.IsDifferent:
  56060. var check;
  56061. if (this.value.equals) {
  56062. check = this.value.equals(this._effectiveTarget[this._property]);
  56063. }
  56064. else {
  56065. check = this.value === this._effectiveTarget[this._property];
  56066. }
  56067. return this.operator === ValueCondition.IsEqual ? check : !check;
  56068. }
  56069. return false;
  56070. };
  56071. /**
  56072. * Serialize the ValueCondition into a JSON compatible object
  56073. * @returns serialization object
  56074. */
  56075. ValueCondition.prototype.serialize = function () {
  56076. return this._serialize({
  56077. name: "ValueCondition",
  56078. properties: [
  56079. BABYLON.Action._GetTargetProperty(this._target),
  56080. { name: "propertyPath", value: this.propertyPath },
  56081. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56082. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56083. ]
  56084. });
  56085. };
  56086. /**
  56087. * Gets the name of the conditional operator for the ValueCondition
  56088. * @param operator the conditional operator
  56089. * @returns the name
  56090. */
  56091. ValueCondition.GetOperatorName = function (operator) {
  56092. switch (operator) {
  56093. case ValueCondition._IsEqual: return "IsEqual";
  56094. case ValueCondition._IsDifferent: return "IsDifferent";
  56095. case ValueCondition._IsGreater: return "IsGreater";
  56096. case ValueCondition._IsLesser: return "IsLesser";
  56097. default: return "";
  56098. }
  56099. };
  56100. /**
  56101. * Internal only
  56102. * @hidden
  56103. */
  56104. ValueCondition._IsEqual = 0;
  56105. /**
  56106. * Internal only
  56107. * @hidden
  56108. */
  56109. ValueCondition._IsDifferent = 1;
  56110. /**
  56111. * Internal only
  56112. * @hidden
  56113. */
  56114. ValueCondition._IsGreater = 2;
  56115. /**
  56116. * Internal only
  56117. * @hidden
  56118. */
  56119. ValueCondition._IsLesser = 3;
  56120. return ValueCondition;
  56121. }(Condition));
  56122. BABYLON.ValueCondition = ValueCondition;
  56123. /**
  56124. * Defines a predicate condition as an extension of Condition
  56125. */
  56126. var PredicateCondition = /** @class */ (function (_super) {
  56127. __extends(PredicateCondition, _super);
  56128. /**
  56129. * Creates a new PredicateCondition
  56130. * @param actionManager manager for the action the condition applies to
  56131. * @param predicate defines the predicate function used to validate the condition
  56132. */
  56133. function PredicateCondition(actionManager,
  56134. /** defines the predicate function used to validate the condition */
  56135. predicate) {
  56136. var _this = _super.call(this, actionManager) || this;
  56137. _this.predicate = predicate;
  56138. return _this;
  56139. }
  56140. /**
  56141. * @returns the validity of the predicate condition
  56142. */
  56143. PredicateCondition.prototype.isValid = function () {
  56144. return this.predicate();
  56145. };
  56146. return PredicateCondition;
  56147. }(Condition));
  56148. BABYLON.PredicateCondition = PredicateCondition;
  56149. /**
  56150. * Defines a state condition as an extension of Condition
  56151. */
  56152. var StateCondition = /** @class */ (function (_super) {
  56153. __extends(StateCondition, _super);
  56154. /**
  56155. * Creates a new StateCondition
  56156. * @param actionManager manager for the action the condition applies to
  56157. * @param target of the condition
  56158. * @param value to compare with target state
  56159. */
  56160. function StateCondition(actionManager, target,
  56161. /** Value to compare with target state */
  56162. value) {
  56163. var _this = _super.call(this, actionManager) || this;
  56164. _this.value = value;
  56165. _this._target = target;
  56166. return _this;
  56167. }
  56168. /**
  56169. * Gets a boolean indicating if the current condition is met
  56170. * @returns the validity of the state
  56171. */
  56172. StateCondition.prototype.isValid = function () {
  56173. return this._target.state === this.value;
  56174. };
  56175. /**
  56176. * Serialize the StateCondition into a JSON compatible object
  56177. * @returns serialization object
  56178. */
  56179. StateCondition.prototype.serialize = function () {
  56180. return this._serialize({
  56181. name: "StateCondition",
  56182. properties: [
  56183. BABYLON.Action._GetTargetProperty(this._target),
  56184. { name: "value", value: this.value }
  56185. ]
  56186. });
  56187. };
  56188. return StateCondition;
  56189. }(Condition));
  56190. BABYLON.StateCondition = StateCondition;
  56191. })(BABYLON || (BABYLON = {}));
  56192. //# sourceMappingURL=babylon.condition.js.map
  56193. var BABYLON;
  56194. (function (BABYLON) {
  56195. /**
  56196. * The action to be carried out following a trigger
  56197. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56198. */
  56199. var Action = /** @class */ (function () {
  56200. /**
  56201. * Creates a new Action
  56202. * @param triggerOptions the trigger, with or without parameters, for the action
  56203. * @param condition an optional determinant of action
  56204. */
  56205. function Action(
  56206. /** the trigger, with or without parameters, for the action */
  56207. triggerOptions, condition) {
  56208. this.triggerOptions = triggerOptions;
  56209. /**
  56210. * An event triggered prior to action being executed.
  56211. */
  56212. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56213. if (triggerOptions.parameter) {
  56214. this.trigger = triggerOptions.trigger;
  56215. this._triggerParameter = triggerOptions.parameter;
  56216. }
  56217. else if (triggerOptions.trigger) {
  56218. this.trigger = triggerOptions.trigger;
  56219. }
  56220. else {
  56221. this.trigger = triggerOptions;
  56222. }
  56223. this._nextActiveAction = this;
  56224. this._condition = condition;
  56225. }
  56226. /**
  56227. * Internal only
  56228. * @hidden
  56229. */
  56230. Action.prototype._prepare = function () {
  56231. };
  56232. /**
  56233. * Gets the trigger parameters
  56234. * @returns the trigger parameters
  56235. */
  56236. Action.prototype.getTriggerParameter = function () {
  56237. return this._triggerParameter;
  56238. };
  56239. /**
  56240. * Internal only - executes current action event
  56241. * @hidden
  56242. */
  56243. Action.prototype._executeCurrent = function (evt) {
  56244. if (this._nextActiveAction._condition) {
  56245. var condition = this._nextActiveAction._condition;
  56246. var currentRenderId = this._actionManager.getScene().getRenderId();
  56247. // We cache the current evaluation for the current frame
  56248. if (condition._evaluationId === currentRenderId) {
  56249. if (!condition._currentResult) {
  56250. return;
  56251. }
  56252. }
  56253. else {
  56254. condition._evaluationId = currentRenderId;
  56255. if (!condition.isValid()) {
  56256. condition._currentResult = false;
  56257. return;
  56258. }
  56259. condition._currentResult = true;
  56260. }
  56261. }
  56262. this.onBeforeExecuteObservable.notifyObservers(this);
  56263. this._nextActiveAction.execute(evt);
  56264. this.skipToNextActiveAction();
  56265. };
  56266. /**
  56267. * Execute placeholder for child classes
  56268. * @param evt optional action event
  56269. */
  56270. Action.prototype.execute = function (evt) {
  56271. };
  56272. /**
  56273. * Skips to next active action
  56274. */
  56275. Action.prototype.skipToNextActiveAction = function () {
  56276. if (this._nextActiveAction._child) {
  56277. if (!this._nextActiveAction._child._actionManager) {
  56278. this._nextActiveAction._child._actionManager = this._actionManager;
  56279. }
  56280. this._nextActiveAction = this._nextActiveAction._child;
  56281. }
  56282. else {
  56283. this._nextActiveAction = this;
  56284. }
  56285. };
  56286. /**
  56287. * Adds action to chain of actions, may be a DoNothingAction
  56288. * @param action defines the next action to execute
  56289. * @returns The action passed in
  56290. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56291. */
  56292. Action.prototype.then = function (action) {
  56293. this._child = action;
  56294. action._actionManager = this._actionManager;
  56295. action._prepare();
  56296. return action;
  56297. };
  56298. /**
  56299. * Internal only
  56300. * @hidden
  56301. */
  56302. Action.prototype._getProperty = function (propertyPath) {
  56303. return this._actionManager._getProperty(propertyPath);
  56304. };
  56305. /**
  56306. * Internal only
  56307. * @hidden
  56308. */
  56309. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56310. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56311. };
  56312. /**
  56313. * Serialize placeholder for child classes
  56314. * @param parent of child
  56315. * @returns the serialized object
  56316. */
  56317. Action.prototype.serialize = function (parent) {
  56318. };
  56319. /**
  56320. * Internal only called by serialize
  56321. * @hidden
  56322. */
  56323. Action.prototype._serialize = function (serializedAction, parent) {
  56324. var serializationObject = {
  56325. type: 1,
  56326. children: [],
  56327. name: serializedAction.name,
  56328. properties: serializedAction.properties || []
  56329. };
  56330. // Serialize child
  56331. if (this._child) {
  56332. this._child.serialize(serializationObject);
  56333. }
  56334. // Check if "this" has a condition
  56335. if (this._condition) {
  56336. var serializedCondition = this._condition.serialize();
  56337. serializedCondition.children.push(serializationObject);
  56338. if (parent) {
  56339. parent.children.push(serializedCondition);
  56340. }
  56341. return serializedCondition;
  56342. }
  56343. if (parent) {
  56344. parent.children.push(serializationObject);
  56345. }
  56346. return serializationObject;
  56347. };
  56348. /**
  56349. * Internal only
  56350. * @hidden
  56351. */
  56352. Action._SerializeValueAsString = function (value) {
  56353. if (typeof value === "number") {
  56354. return value.toString();
  56355. }
  56356. if (typeof value === "boolean") {
  56357. return value ? "true" : "false";
  56358. }
  56359. if (value instanceof BABYLON.Vector2) {
  56360. return value.x + ", " + value.y;
  56361. }
  56362. if (value instanceof BABYLON.Vector3) {
  56363. return value.x + ", " + value.y + ", " + value.z;
  56364. }
  56365. if (value instanceof BABYLON.Color3) {
  56366. return value.r + ", " + value.g + ", " + value.b;
  56367. }
  56368. if (value instanceof BABYLON.Color4) {
  56369. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56370. }
  56371. return value; // string
  56372. };
  56373. /**
  56374. * Internal only
  56375. * @hidden
  56376. */
  56377. Action._GetTargetProperty = function (target) {
  56378. return {
  56379. name: "target",
  56380. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56381. : target instanceof BABYLON.Light ? "LightProperties"
  56382. : target instanceof BABYLON.Camera ? "CameraProperties"
  56383. : "SceneProperties",
  56384. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56385. };
  56386. };
  56387. return Action;
  56388. }());
  56389. BABYLON.Action = Action;
  56390. })(BABYLON || (BABYLON = {}));
  56391. //# sourceMappingURL=babylon.action.js.map
  56392. var BABYLON;
  56393. (function (BABYLON) {
  56394. /**
  56395. * ActionEvent is the event being sent when an action is triggered.
  56396. */
  56397. var ActionEvent = /** @class */ (function () {
  56398. /**
  56399. * Creates a new ActionEvent
  56400. * @param source The mesh or sprite that triggered the action
  56401. * @param pointerX The X mouse cursor position at the time of the event
  56402. * @param pointerY The Y mouse cursor position at the time of the event
  56403. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56404. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56405. * @param additionalData additional data for the event
  56406. */
  56407. function ActionEvent(
  56408. /** The mesh or sprite that triggered the action */
  56409. source,
  56410. /** The X mouse cursor position at the time of the event */
  56411. pointerX,
  56412. /** The Y mouse cursor position at the time of the event */
  56413. pointerY,
  56414. /** The mesh that is currently pointed at (can be null) */
  56415. meshUnderPointer,
  56416. /** the original (browser) event that triggered the ActionEvent */
  56417. sourceEvent,
  56418. /** additional data for the event */
  56419. additionalData) {
  56420. this.source = source;
  56421. this.pointerX = pointerX;
  56422. this.pointerY = pointerY;
  56423. this.meshUnderPointer = meshUnderPointer;
  56424. this.sourceEvent = sourceEvent;
  56425. this.additionalData = additionalData;
  56426. }
  56427. /**
  56428. * Helper function to auto-create an ActionEvent from a source mesh.
  56429. * @param source The source mesh that triggered the event
  56430. * @param evt The original (browser) event
  56431. * @param additionalData additional data for the event
  56432. * @returns the new ActionEvent
  56433. */
  56434. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56435. var scene = source.getScene();
  56436. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56437. };
  56438. /**
  56439. * Helper function to auto-create an ActionEvent from a source sprite
  56440. * @param source The source sprite that triggered the event
  56441. * @param scene Scene associated with the sprite
  56442. * @param evt The original (browser) event
  56443. * @param additionalData additional data for the event
  56444. * @returns the new ActionEvent
  56445. */
  56446. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56447. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56448. };
  56449. /**
  56450. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56451. * @param scene the scene where the event occurred
  56452. * @param evt The original (browser) event
  56453. * @returns the new ActionEvent
  56454. */
  56455. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56456. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56457. };
  56458. /**
  56459. * Helper function to auto-create an ActionEvent from a primitive
  56460. * @param prim defines the target primitive
  56461. * @param pointerPos defines the pointer position
  56462. * @param evt The original (browser) event
  56463. * @param additionalData additional data for the event
  56464. * @returns the new ActionEvent
  56465. */
  56466. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56467. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56468. };
  56469. return ActionEvent;
  56470. }());
  56471. BABYLON.ActionEvent = ActionEvent;
  56472. /**
  56473. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56474. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56475. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56476. */
  56477. var ActionManager = /** @class */ (function () {
  56478. /**
  56479. * Creates a new action manager
  56480. * @param scene defines the hosting scene
  56481. */
  56482. function ActionManager(scene) {
  56483. // Members
  56484. /** Gets the list of actions */
  56485. this.actions = new Array();
  56486. /** Gets the cursor to use when hovering items */
  56487. this.hoverCursor = '';
  56488. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56489. scene.actionManagers.push(this);
  56490. }
  56491. // Methods
  56492. /**
  56493. * Releases all associated resources
  56494. */
  56495. ActionManager.prototype.dispose = function () {
  56496. var index = this._scene.actionManagers.indexOf(this);
  56497. for (var i = 0; i < this.actions.length; i++) {
  56498. var action = this.actions[i];
  56499. ActionManager.Triggers[action.trigger]--;
  56500. if (ActionManager.Triggers[action.trigger] === 0) {
  56501. delete ActionManager.Triggers[action.trigger];
  56502. }
  56503. }
  56504. if (index > -1) {
  56505. this._scene.actionManagers.splice(index, 1);
  56506. }
  56507. };
  56508. /**
  56509. * Gets hosting scene
  56510. * @returns the hosting scene
  56511. */
  56512. ActionManager.prototype.getScene = function () {
  56513. return this._scene;
  56514. };
  56515. /**
  56516. * Does this action manager handles actions of any of the given triggers
  56517. * @param triggers defines the triggers to be tested
  56518. * @return a boolean indicating whether one (or more) of the triggers is handled
  56519. */
  56520. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56521. for (var index = 0; index < this.actions.length; index++) {
  56522. var action = this.actions[index];
  56523. if (triggers.indexOf(action.trigger) > -1) {
  56524. return true;
  56525. }
  56526. }
  56527. return false;
  56528. };
  56529. /**
  56530. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56531. * speed.
  56532. * @param triggerA defines the trigger to be tested
  56533. * @param triggerB defines the trigger to be tested
  56534. * @return a boolean indicating whether one (or more) of the triggers is handled
  56535. */
  56536. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56537. for (var index = 0; index < this.actions.length; index++) {
  56538. var action = this.actions[index];
  56539. if (triggerA == action.trigger || triggerB == action.trigger) {
  56540. return true;
  56541. }
  56542. }
  56543. return false;
  56544. };
  56545. /**
  56546. * Does this action manager handles actions of a given trigger
  56547. * @param trigger defines the trigger to be tested
  56548. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56549. * @return whether the trigger is handled
  56550. */
  56551. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56552. for (var index = 0; index < this.actions.length; index++) {
  56553. var action = this.actions[index];
  56554. if (action.trigger === trigger) {
  56555. if (parameterPredicate) {
  56556. if (parameterPredicate(action.getTriggerParameter())) {
  56557. return true;
  56558. }
  56559. }
  56560. else {
  56561. return true;
  56562. }
  56563. }
  56564. }
  56565. return false;
  56566. };
  56567. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  56568. /**
  56569. * Does this action manager has pointer triggers
  56570. */
  56571. get: function () {
  56572. for (var index = 0; index < this.actions.length; index++) {
  56573. var action = this.actions[index];
  56574. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  56575. return true;
  56576. }
  56577. }
  56578. return false;
  56579. },
  56580. enumerable: true,
  56581. configurable: true
  56582. });
  56583. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  56584. /**
  56585. * Does this action manager has pick triggers
  56586. */
  56587. get: function () {
  56588. for (var index = 0; index < this.actions.length; index++) {
  56589. var action = this.actions[index];
  56590. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  56591. return true;
  56592. }
  56593. }
  56594. return false;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. Object.defineProperty(ActionManager, "HasTriggers", {
  56600. /**
  56601. * Does exist one action manager with at least one trigger
  56602. **/
  56603. get: function () {
  56604. for (var t in ActionManager.Triggers) {
  56605. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56606. return true;
  56607. }
  56608. }
  56609. return false;
  56610. },
  56611. enumerable: true,
  56612. configurable: true
  56613. });
  56614. Object.defineProperty(ActionManager, "HasPickTriggers", {
  56615. /**
  56616. * Does exist one action manager with at least one pick trigger
  56617. **/
  56618. get: function () {
  56619. for (var t in ActionManager.Triggers) {
  56620. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56621. var t_int = parseInt(t);
  56622. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  56623. return true;
  56624. }
  56625. }
  56626. }
  56627. return false;
  56628. },
  56629. enumerable: true,
  56630. configurable: true
  56631. });
  56632. /**
  56633. * Does exist one action manager that handles actions of a given trigger
  56634. * @param trigger defines the trigger to be tested
  56635. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  56636. **/
  56637. ActionManager.HasSpecificTrigger = function (trigger) {
  56638. for (var t in ActionManager.Triggers) {
  56639. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56640. var t_int = parseInt(t);
  56641. if (t_int === trigger) {
  56642. return true;
  56643. }
  56644. }
  56645. }
  56646. return false;
  56647. };
  56648. /**
  56649. * Registers an action to this action manager
  56650. * @param action defines the action to be registered
  56651. * @return the action amended (prepared) after registration
  56652. */
  56653. ActionManager.prototype.registerAction = function (action) {
  56654. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  56655. if (this.getScene().actionManager !== this) {
  56656. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  56657. return null;
  56658. }
  56659. }
  56660. this.actions.push(action);
  56661. if (ActionManager.Triggers[action.trigger]) {
  56662. ActionManager.Triggers[action.trigger]++;
  56663. }
  56664. else {
  56665. ActionManager.Triggers[action.trigger] = 1;
  56666. }
  56667. action._actionManager = this;
  56668. action._prepare();
  56669. return action;
  56670. };
  56671. /**
  56672. * Unregisters an action to this action manager
  56673. * @param action defines the action to be unregistered
  56674. * @return a boolean indicating whether the action has been unregistered
  56675. */
  56676. ActionManager.prototype.unregisterAction = function (action) {
  56677. var index = this.actions.indexOf(action);
  56678. if (index !== -1) {
  56679. this.actions.splice(index, 1);
  56680. ActionManager.Triggers[action.trigger] -= 1;
  56681. if (ActionManager.Triggers[action.trigger] === 0) {
  56682. delete ActionManager.Triggers[action.trigger];
  56683. }
  56684. delete action._actionManager;
  56685. return true;
  56686. }
  56687. return false;
  56688. };
  56689. /**
  56690. * Process a specific trigger
  56691. * @param trigger defines the trigger to process
  56692. * @param evt defines the event details to be processed
  56693. */
  56694. ActionManager.prototype.processTrigger = function (trigger, evt) {
  56695. for (var index = 0; index < this.actions.length; index++) {
  56696. var action = this.actions[index];
  56697. if (action.trigger === trigger) {
  56698. if (evt) {
  56699. if (trigger === ActionManager.OnKeyUpTrigger
  56700. || trigger === ActionManager.OnKeyDownTrigger) {
  56701. var parameter = action.getTriggerParameter();
  56702. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  56703. if (!parameter.toLowerCase) {
  56704. continue;
  56705. }
  56706. var lowerCase = parameter.toLowerCase();
  56707. if (lowerCase !== evt.sourceEvent.key) {
  56708. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  56709. var actualkey = String.fromCharCode(unicode).toLowerCase();
  56710. if (actualkey !== lowerCase) {
  56711. continue;
  56712. }
  56713. }
  56714. }
  56715. }
  56716. }
  56717. action._executeCurrent(evt);
  56718. }
  56719. }
  56720. };
  56721. /** @hidden */
  56722. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  56723. var properties = propertyPath.split(".");
  56724. for (var index = 0; index < properties.length - 1; index++) {
  56725. target = target[properties[index]];
  56726. }
  56727. return target;
  56728. };
  56729. /** @hidden */
  56730. ActionManager.prototype._getProperty = function (propertyPath) {
  56731. var properties = propertyPath.split(".");
  56732. return properties[properties.length - 1];
  56733. };
  56734. /**
  56735. * Serialize this manager to a JSON object
  56736. * @param name defines the property name to store this manager
  56737. * @returns a JSON representation of this manager
  56738. */
  56739. ActionManager.prototype.serialize = function (name) {
  56740. var root = {
  56741. children: new Array(),
  56742. name: name,
  56743. type: 3,
  56744. properties: new Array() // Empty for root but required
  56745. };
  56746. for (var i = 0; i < this.actions.length; i++) {
  56747. var triggerObject = {
  56748. type: 0,
  56749. children: new Array(),
  56750. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  56751. properties: new Array()
  56752. };
  56753. var triggerOptions = this.actions[i].triggerOptions;
  56754. if (triggerOptions && typeof triggerOptions !== "number") {
  56755. if (triggerOptions.parameter instanceof BABYLON.Node) {
  56756. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  56757. }
  56758. else {
  56759. var parameter = {};
  56760. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  56761. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  56762. parameter._meshId = triggerOptions.parameter.mesh.id;
  56763. }
  56764. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  56765. }
  56766. }
  56767. // Serialize child action, recursively
  56768. this.actions[i].serialize(triggerObject);
  56769. // Add serialized trigger
  56770. root.children.push(triggerObject);
  56771. }
  56772. return root;
  56773. };
  56774. /**
  56775. * Creates a new ActionManager from a JSON data
  56776. * @param parsedActions defines the JSON data to read from
  56777. * @param object defines the hosting mesh
  56778. * @param scene defines the hosting scene
  56779. */
  56780. ActionManager.Parse = function (parsedActions, object, scene) {
  56781. var actionManager = new ActionManager(scene);
  56782. if (object === null) {
  56783. scene.actionManager = actionManager;
  56784. }
  56785. else {
  56786. object.actionManager = actionManager;
  56787. }
  56788. // instanciate a new object
  56789. var instanciate = function (name, params) {
  56790. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  56791. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  56792. newInstance.constructor.apply(newInstance, params);
  56793. return newInstance;
  56794. };
  56795. var parseParameter = function (name, value, target, propertyPath) {
  56796. if (propertyPath === null) {
  56797. // String, boolean or float
  56798. var floatValue = parseFloat(value);
  56799. if (value === "true" || value === "false") {
  56800. return value === "true";
  56801. }
  56802. else {
  56803. return isNaN(floatValue) ? value : floatValue;
  56804. }
  56805. }
  56806. var effectiveTarget = propertyPath.split(".");
  56807. var values = value.split(",");
  56808. // Get effective Target
  56809. for (var i = 0; i < effectiveTarget.length; i++) {
  56810. target = target[effectiveTarget[i]];
  56811. }
  56812. // Return appropriate value with its type
  56813. if (typeof (target) === "boolean") {
  56814. return values[0] === "true";
  56815. }
  56816. if (typeof (target) === "string") {
  56817. return values[0];
  56818. }
  56819. // Parameters with multiple values such as Vector3 etc.
  56820. var split = new Array();
  56821. for (var i = 0; i < values.length; i++) {
  56822. split.push(parseFloat(values[i]));
  56823. }
  56824. if (target instanceof BABYLON.Vector3) {
  56825. return BABYLON.Vector3.FromArray(split);
  56826. }
  56827. if (target instanceof BABYLON.Vector4) {
  56828. return BABYLON.Vector4.FromArray(split);
  56829. }
  56830. if (target instanceof BABYLON.Color3) {
  56831. return BABYLON.Color3.FromArray(split);
  56832. }
  56833. if (target instanceof BABYLON.Color4) {
  56834. return BABYLON.Color4.FromArray(split);
  56835. }
  56836. return parseFloat(values[0]);
  56837. };
  56838. // traverse graph per trigger
  56839. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  56840. if (combineArray === void 0) { combineArray = null; }
  56841. if (parsedAction.detached) {
  56842. return;
  56843. }
  56844. var parameters = new Array();
  56845. var target = null;
  56846. var propertyPath = null;
  56847. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  56848. // Parameters
  56849. if (parsedAction.type === 2) {
  56850. parameters.push(actionManager);
  56851. }
  56852. else {
  56853. parameters.push(trigger);
  56854. }
  56855. if (combine) {
  56856. var actions = new Array();
  56857. for (var j = 0; j < parsedAction.combine.length; j++) {
  56858. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  56859. }
  56860. parameters.push(actions);
  56861. }
  56862. else {
  56863. for (var i = 0; i < parsedAction.properties.length; i++) {
  56864. var value = parsedAction.properties[i].value;
  56865. var name = parsedAction.properties[i].name;
  56866. var targetType = parsedAction.properties[i].targetType;
  56867. if (name === "target") {
  56868. if (targetType !== null && targetType === "SceneProperties") {
  56869. value = target = scene;
  56870. }
  56871. else {
  56872. value = target = scene.getNodeByName(value);
  56873. }
  56874. }
  56875. else if (name === "parent") {
  56876. value = scene.getNodeByName(value);
  56877. }
  56878. else if (name === "sound") {
  56879. // Can not externalize to component, so only checks for the presence off the API.
  56880. if (scene.getSoundByName) {
  56881. value = scene.getSoundByName(value);
  56882. }
  56883. }
  56884. else if (name !== "propertyPath") {
  56885. if (parsedAction.type === 2 && name === "operator") {
  56886. value = BABYLON.ValueCondition[value];
  56887. }
  56888. else {
  56889. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  56890. }
  56891. }
  56892. else {
  56893. propertyPath = value;
  56894. }
  56895. parameters.push(value);
  56896. }
  56897. }
  56898. if (combineArray === null) {
  56899. parameters.push(condition);
  56900. }
  56901. else {
  56902. parameters.push(null);
  56903. }
  56904. // If interpolate value action
  56905. if (parsedAction.name === "InterpolateValueAction") {
  56906. var param = parameters[parameters.length - 2];
  56907. parameters[parameters.length - 1] = param;
  56908. parameters[parameters.length - 2] = condition;
  56909. }
  56910. // Action or condition(s) and not CombineAction
  56911. var newAction = instanciate(parsedAction.name, parameters);
  56912. if (newAction instanceof BABYLON.Condition && condition !== null) {
  56913. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  56914. if (action) {
  56915. action.then(nothing);
  56916. }
  56917. else {
  56918. actionManager.registerAction(nothing);
  56919. }
  56920. action = nothing;
  56921. }
  56922. if (combineArray === null) {
  56923. if (newAction instanceof BABYLON.Condition) {
  56924. condition = newAction;
  56925. newAction = action;
  56926. }
  56927. else {
  56928. condition = null;
  56929. if (action) {
  56930. action.then(newAction);
  56931. }
  56932. else {
  56933. actionManager.registerAction(newAction);
  56934. }
  56935. }
  56936. }
  56937. else {
  56938. combineArray.push(newAction);
  56939. }
  56940. for (var i = 0; i < parsedAction.children.length; i++) {
  56941. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  56942. }
  56943. };
  56944. // triggers
  56945. for (var i = 0; i < parsedActions.children.length; i++) {
  56946. var triggerParams;
  56947. var trigger = parsedActions.children[i];
  56948. if (trigger.properties.length > 0) {
  56949. var param = trigger.properties[0].value;
  56950. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  56951. if (value._meshId) {
  56952. value.mesh = scene.getMeshByID(value._meshId);
  56953. }
  56954. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  56955. }
  56956. else {
  56957. triggerParams = ActionManager[trigger.name];
  56958. }
  56959. for (var j = 0; j < trigger.children.length; j++) {
  56960. if (!trigger.detached) {
  56961. traverse(trigger.children[j], triggerParams, null, null);
  56962. }
  56963. }
  56964. }
  56965. };
  56966. /**
  56967. * Get a trigger name by index
  56968. * @param trigger defines the trigger index
  56969. * @returns a trigger name
  56970. */
  56971. ActionManager.GetTriggerName = function (trigger) {
  56972. switch (trigger) {
  56973. case 0: return "NothingTrigger";
  56974. case 1: return "OnPickTrigger";
  56975. case 2: return "OnLeftPickTrigger";
  56976. case 3: return "OnRightPickTrigger";
  56977. case 4: return "OnCenterPickTrigger";
  56978. case 5: return "OnPickDownTrigger";
  56979. case 6: return "OnPickUpTrigger";
  56980. case 7: return "OnLongPressTrigger";
  56981. case 8: return "OnPointerOverTrigger";
  56982. case 9: return "OnPointerOutTrigger";
  56983. case 10: return "OnEveryFrameTrigger";
  56984. case 11: return "OnIntersectionEnterTrigger";
  56985. case 12: return "OnIntersectionExitTrigger";
  56986. case 13: return "OnKeyDownTrigger";
  56987. case 14: return "OnKeyUpTrigger";
  56988. case 15: return "OnPickOutTrigger";
  56989. default: return "";
  56990. }
  56991. };
  56992. /**
  56993. * Nothing
  56994. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56995. */
  56996. ActionManager.NothingTrigger = 0;
  56997. /**
  56998. * On pick
  56999. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57000. */
  57001. ActionManager.OnPickTrigger = 1;
  57002. /**
  57003. * On left pick
  57004. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57005. */
  57006. ActionManager.OnLeftPickTrigger = 2;
  57007. /**
  57008. * On right pick
  57009. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57010. */
  57011. ActionManager.OnRightPickTrigger = 3;
  57012. /**
  57013. * On center pick
  57014. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57015. */
  57016. ActionManager.OnCenterPickTrigger = 4;
  57017. /**
  57018. * On pick down
  57019. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57020. */
  57021. ActionManager.OnPickDownTrigger = 5;
  57022. /**
  57023. * On double pick
  57024. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57025. */
  57026. ActionManager.OnDoublePickTrigger = 6;
  57027. /**
  57028. * On pick up
  57029. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57030. */
  57031. ActionManager.OnPickUpTrigger = 7;
  57032. /**
  57033. * On pick out.
  57034. * This trigger will only be raised if you also declared a OnPickDown
  57035. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57036. */
  57037. ActionManager.OnPickOutTrigger = 16;
  57038. /**
  57039. * On long press
  57040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57041. */
  57042. ActionManager.OnLongPressTrigger = 8;
  57043. /**
  57044. * On pointer over
  57045. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57046. */
  57047. ActionManager.OnPointerOverTrigger = 9;
  57048. /**
  57049. * On pointer out
  57050. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57051. */
  57052. ActionManager.OnPointerOutTrigger = 10;
  57053. /**
  57054. * On every frame
  57055. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57056. */
  57057. ActionManager.OnEveryFrameTrigger = 11;
  57058. /**
  57059. * On intersection enter
  57060. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57061. */
  57062. ActionManager.OnIntersectionEnterTrigger = 12;
  57063. /**
  57064. * On intersection exit
  57065. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57066. */
  57067. ActionManager.OnIntersectionExitTrigger = 13;
  57068. /**
  57069. * On key down
  57070. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57071. */
  57072. ActionManager.OnKeyDownTrigger = 14;
  57073. /**
  57074. * On key up
  57075. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57076. */
  57077. ActionManager.OnKeyUpTrigger = 15;
  57078. /** Gets the list of active triggers */
  57079. ActionManager.Triggers = {};
  57080. return ActionManager;
  57081. }());
  57082. BABYLON.ActionManager = ActionManager;
  57083. })(BABYLON || (BABYLON = {}));
  57084. //# sourceMappingURL=babylon.actionManager.js.map
  57085. var BABYLON;
  57086. (function (BABYLON) {
  57087. /**
  57088. * This defines an action responsible to change the value of a property
  57089. * by interpolating between its current value and the newly set one once triggered.
  57090. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57091. */
  57092. var InterpolateValueAction = /** @class */ (function (_super) {
  57093. __extends(InterpolateValueAction, _super);
  57094. /**
  57095. * Instantiate the action
  57096. * @param triggerOptions defines the trigger options
  57097. * @param target defines the object containing the value to interpolate
  57098. * @param propertyPath defines the path to the property in the target object
  57099. * @param value defines the target value at the end of the interpolation
  57100. * @param duration deines the time it will take for the property to interpolate to the value.
  57101. * @param condition defines the trigger related conditions
  57102. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57103. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57104. */
  57105. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57106. if (duration === void 0) { duration = 1000; }
  57107. var _this = _super.call(this, triggerOptions, condition) || this;
  57108. /**
  57109. * Defines the time it will take for the property to interpolate to the value.
  57110. */
  57111. _this.duration = 1000;
  57112. /**
  57113. * Observable triggered once the interpolation animation has been done.
  57114. */
  57115. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57116. _this.propertyPath = propertyPath;
  57117. _this.value = value;
  57118. _this.duration = duration;
  57119. _this.stopOtherAnimations = stopOtherAnimations;
  57120. _this.onInterpolationDone = onInterpolationDone;
  57121. _this._target = _this._effectiveTarget = target;
  57122. return _this;
  57123. }
  57124. /** @hidden */
  57125. InterpolateValueAction.prototype._prepare = function () {
  57126. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57127. this._property = this._getProperty(this.propertyPath);
  57128. };
  57129. /**
  57130. * Execute the action starts the value interpolation.
  57131. */
  57132. InterpolateValueAction.prototype.execute = function () {
  57133. var _this = this;
  57134. var scene = this._actionManager.getScene();
  57135. var keys = [
  57136. {
  57137. frame: 0,
  57138. value: this._effectiveTarget[this._property]
  57139. }, {
  57140. frame: 100,
  57141. value: this.value
  57142. }
  57143. ];
  57144. var dataType;
  57145. if (typeof this.value === "number") {
  57146. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57147. }
  57148. else if (this.value instanceof BABYLON.Color3) {
  57149. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57150. }
  57151. else if (this.value instanceof BABYLON.Vector3) {
  57152. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57153. }
  57154. else if (this.value instanceof BABYLON.Matrix) {
  57155. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57156. }
  57157. else if (this.value instanceof BABYLON.Quaternion) {
  57158. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57159. }
  57160. else {
  57161. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57162. return;
  57163. }
  57164. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57165. animation.setKeys(keys);
  57166. if (this.stopOtherAnimations) {
  57167. scene.stopAnimation(this._effectiveTarget);
  57168. }
  57169. var wrapper = function () {
  57170. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57171. if (_this.onInterpolationDone) {
  57172. _this.onInterpolationDone();
  57173. }
  57174. };
  57175. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57176. };
  57177. /**
  57178. * Serializes the actions and its related information.
  57179. * @param parent defines the object to serialize in
  57180. * @returns the serialized object
  57181. */
  57182. InterpolateValueAction.prototype.serialize = function (parent) {
  57183. return _super.prototype._serialize.call(this, {
  57184. name: "InterpolateValueAction",
  57185. properties: [
  57186. BABYLON.Action._GetTargetProperty(this._target),
  57187. { name: "propertyPath", value: this.propertyPath },
  57188. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57189. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57190. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57191. ]
  57192. }, parent);
  57193. };
  57194. return InterpolateValueAction;
  57195. }(BABYLON.Action));
  57196. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57197. })(BABYLON || (BABYLON = {}));
  57198. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  57199. var BABYLON;
  57200. (function (BABYLON) {
  57201. /**
  57202. * This defines an action responsible to toggle a boolean once triggered.
  57203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57204. */
  57205. var SwitchBooleanAction = /** @class */ (function (_super) {
  57206. __extends(SwitchBooleanAction, _super);
  57207. /**
  57208. * Instantiate the action
  57209. * @param triggerOptions defines the trigger options
  57210. * @param target defines the object containing the boolean
  57211. * @param propertyPath defines the path to the boolean property in the target object
  57212. * @param condition defines the trigger related conditions
  57213. */
  57214. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57215. var _this = _super.call(this, triggerOptions, condition) || this;
  57216. _this.propertyPath = propertyPath;
  57217. _this._target = _this._effectiveTarget = target;
  57218. return _this;
  57219. }
  57220. /** @hidden */
  57221. SwitchBooleanAction.prototype._prepare = function () {
  57222. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57223. this._property = this._getProperty(this.propertyPath);
  57224. };
  57225. /**
  57226. * Execute the action toggle the boolean value.
  57227. */
  57228. SwitchBooleanAction.prototype.execute = function () {
  57229. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57230. };
  57231. /**
  57232. * Serializes the actions and its related information.
  57233. * @param parent defines the object to serialize in
  57234. * @returns the serialized object
  57235. */
  57236. SwitchBooleanAction.prototype.serialize = function (parent) {
  57237. return _super.prototype._serialize.call(this, {
  57238. name: "SwitchBooleanAction",
  57239. properties: [
  57240. BABYLON.Action._GetTargetProperty(this._target),
  57241. { name: "propertyPath", value: this.propertyPath }
  57242. ]
  57243. }, parent);
  57244. };
  57245. return SwitchBooleanAction;
  57246. }(BABYLON.Action));
  57247. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57248. /**
  57249. * This defines an action responsible to set a the state field of the target
  57250. * to a desired value once triggered.
  57251. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57252. */
  57253. var SetStateAction = /** @class */ (function (_super) {
  57254. __extends(SetStateAction, _super);
  57255. /**
  57256. * Instantiate the action
  57257. * @param triggerOptions defines the trigger options
  57258. * @param target defines the object containing the state property
  57259. * @param value defines the value to store in the state field
  57260. * @param condition defines the trigger related conditions
  57261. */
  57262. function SetStateAction(triggerOptions, target, value, condition) {
  57263. var _this = _super.call(this, triggerOptions, condition) || this;
  57264. _this.value = value;
  57265. _this._target = target;
  57266. return _this;
  57267. }
  57268. /**
  57269. * Execute the action and store the value on the target state property.
  57270. */
  57271. SetStateAction.prototype.execute = function () {
  57272. this._target.state = this.value;
  57273. };
  57274. /**
  57275. * Serializes the actions and its related information.
  57276. * @param parent defines the object to serialize in
  57277. * @returns the serialized object
  57278. */
  57279. SetStateAction.prototype.serialize = function (parent) {
  57280. return _super.prototype._serialize.call(this, {
  57281. name: "SetStateAction",
  57282. properties: [
  57283. BABYLON.Action._GetTargetProperty(this._target),
  57284. { name: "value", value: this.value }
  57285. ]
  57286. }, parent);
  57287. };
  57288. return SetStateAction;
  57289. }(BABYLON.Action));
  57290. BABYLON.SetStateAction = SetStateAction;
  57291. /**
  57292. * This defines an action responsible to set a property of the target
  57293. * to a desired value once triggered.
  57294. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57295. */
  57296. var SetValueAction = /** @class */ (function (_super) {
  57297. __extends(SetValueAction, _super);
  57298. /**
  57299. * Instantiate the action
  57300. * @param triggerOptions defines the trigger options
  57301. * @param target defines the object containing the property
  57302. * @param propertyPath defines the path of the property to set in the target
  57303. * @param value defines the value to set in the property
  57304. * @param condition defines the trigger related conditions
  57305. */
  57306. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57307. var _this = _super.call(this, triggerOptions, condition) || this;
  57308. _this.propertyPath = propertyPath;
  57309. _this.value = value;
  57310. _this._target = _this._effectiveTarget = target;
  57311. return _this;
  57312. }
  57313. /** @hidden */
  57314. SetValueAction.prototype._prepare = function () {
  57315. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57316. this._property = this._getProperty(this.propertyPath);
  57317. };
  57318. /**
  57319. * Execute the action and set the targetted property to the desired value.
  57320. */
  57321. SetValueAction.prototype.execute = function () {
  57322. this._effectiveTarget[this._property] = this.value;
  57323. if (this._target.markAsDirty) {
  57324. this._target.markAsDirty(this._property);
  57325. }
  57326. };
  57327. /**
  57328. * Serializes the actions and its related information.
  57329. * @param parent defines the object to serialize in
  57330. * @returns the serialized object
  57331. */
  57332. SetValueAction.prototype.serialize = function (parent) {
  57333. return _super.prototype._serialize.call(this, {
  57334. name: "SetValueAction",
  57335. properties: [
  57336. BABYLON.Action._GetTargetProperty(this._target),
  57337. { name: "propertyPath", value: this.propertyPath },
  57338. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57339. ]
  57340. }, parent);
  57341. };
  57342. return SetValueAction;
  57343. }(BABYLON.Action));
  57344. BABYLON.SetValueAction = SetValueAction;
  57345. /**
  57346. * This defines an action responsible to increment the target value
  57347. * to a desired value once triggered.
  57348. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57349. */
  57350. var IncrementValueAction = /** @class */ (function (_super) {
  57351. __extends(IncrementValueAction, _super);
  57352. /**
  57353. * Instantiate the action
  57354. * @param triggerOptions defines the trigger options
  57355. * @param target defines the object containing the property
  57356. * @param propertyPath defines the path of the property to increment in the target
  57357. * @param value defines the value value we should increment the property by
  57358. * @param condition defines the trigger related conditions
  57359. */
  57360. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57361. var _this = _super.call(this, triggerOptions, condition) || this;
  57362. _this.propertyPath = propertyPath;
  57363. _this.value = value;
  57364. _this._target = _this._effectiveTarget = target;
  57365. return _this;
  57366. }
  57367. /** @hidden */
  57368. IncrementValueAction.prototype._prepare = function () {
  57369. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57370. this._property = this._getProperty(this.propertyPath);
  57371. if (typeof this._effectiveTarget[this._property] !== "number") {
  57372. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57373. }
  57374. };
  57375. /**
  57376. * Execute the action and increment the target of the value amount.
  57377. */
  57378. IncrementValueAction.prototype.execute = function () {
  57379. this._effectiveTarget[this._property] += this.value;
  57380. if (this._target.markAsDirty) {
  57381. this._target.markAsDirty(this._property);
  57382. }
  57383. };
  57384. /**
  57385. * Serializes the actions and its related information.
  57386. * @param parent defines the object to serialize in
  57387. * @returns the serialized object
  57388. */
  57389. IncrementValueAction.prototype.serialize = function (parent) {
  57390. return _super.prototype._serialize.call(this, {
  57391. name: "IncrementValueAction",
  57392. properties: [
  57393. BABYLON.Action._GetTargetProperty(this._target),
  57394. { name: "propertyPath", value: this.propertyPath },
  57395. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57396. ]
  57397. }, parent);
  57398. };
  57399. return IncrementValueAction;
  57400. }(BABYLON.Action));
  57401. BABYLON.IncrementValueAction = IncrementValueAction;
  57402. /**
  57403. * This defines an action responsible to start an animation once triggered.
  57404. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57405. */
  57406. var PlayAnimationAction = /** @class */ (function (_super) {
  57407. __extends(PlayAnimationAction, _super);
  57408. /**
  57409. * Instantiate the action
  57410. * @param triggerOptions defines the trigger options
  57411. * @param target defines the target animation or animation name
  57412. * @param from defines from where the animation should start (animation frame)
  57413. * @param end defines where the animation should stop (animation frame)
  57414. * @param loop defines if the animation should loop or stop after the first play
  57415. * @param condition defines the trigger related conditions
  57416. */
  57417. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57418. var _this = _super.call(this, triggerOptions, condition) || this;
  57419. _this.from = from;
  57420. _this.to = to;
  57421. _this.loop = loop;
  57422. _this._target = target;
  57423. return _this;
  57424. }
  57425. /** @hidden */
  57426. PlayAnimationAction.prototype._prepare = function () {
  57427. };
  57428. /**
  57429. * Execute the action and play the animation.
  57430. */
  57431. PlayAnimationAction.prototype.execute = function () {
  57432. var scene = this._actionManager.getScene();
  57433. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57434. };
  57435. /**
  57436. * Serializes the actions and its related information.
  57437. * @param parent defines the object to serialize in
  57438. * @returns the serialized object
  57439. */
  57440. PlayAnimationAction.prototype.serialize = function (parent) {
  57441. return _super.prototype._serialize.call(this, {
  57442. name: "PlayAnimationAction",
  57443. properties: [
  57444. BABYLON.Action._GetTargetProperty(this._target),
  57445. { name: "from", value: String(this.from) },
  57446. { name: "to", value: String(this.to) },
  57447. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57448. ]
  57449. }, parent);
  57450. };
  57451. return PlayAnimationAction;
  57452. }(BABYLON.Action));
  57453. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57454. /**
  57455. * This defines an action responsible to stop an animation once triggered.
  57456. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57457. */
  57458. var StopAnimationAction = /** @class */ (function (_super) {
  57459. __extends(StopAnimationAction, _super);
  57460. /**
  57461. * Instantiate the action
  57462. * @param triggerOptions defines the trigger options
  57463. * @param target defines the target animation or animation name
  57464. * @param condition defines the trigger related conditions
  57465. */
  57466. function StopAnimationAction(triggerOptions, target, condition) {
  57467. var _this = _super.call(this, triggerOptions, condition) || this;
  57468. _this._target = target;
  57469. return _this;
  57470. }
  57471. /** @hidden */
  57472. StopAnimationAction.prototype._prepare = function () {
  57473. };
  57474. /**
  57475. * Execute the action and stop the animation.
  57476. */
  57477. StopAnimationAction.prototype.execute = function () {
  57478. var scene = this._actionManager.getScene();
  57479. scene.stopAnimation(this._target);
  57480. };
  57481. /**
  57482. * Serializes the actions and its related information.
  57483. * @param parent defines the object to serialize in
  57484. * @returns the serialized object
  57485. */
  57486. StopAnimationAction.prototype.serialize = function (parent) {
  57487. return _super.prototype._serialize.call(this, {
  57488. name: "StopAnimationAction",
  57489. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57490. }, parent);
  57491. };
  57492. return StopAnimationAction;
  57493. }(BABYLON.Action));
  57494. BABYLON.StopAnimationAction = StopAnimationAction;
  57495. /**
  57496. * This defines an action responsible that does nothing once triggered.
  57497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57498. */
  57499. var DoNothingAction = /** @class */ (function (_super) {
  57500. __extends(DoNothingAction, _super);
  57501. /**
  57502. * Instantiate the action
  57503. * @param triggerOptions defines the trigger options
  57504. * @param condition defines the trigger related conditions
  57505. */
  57506. function DoNothingAction(triggerOptions, condition) {
  57507. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57508. return _super.call(this, triggerOptions, condition) || this;
  57509. }
  57510. /**
  57511. * Execute the action and do nothing.
  57512. */
  57513. DoNothingAction.prototype.execute = function () {
  57514. };
  57515. /**
  57516. * Serializes the actions and its related information.
  57517. * @param parent defines the object to serialize in
  57518. * @returns the serialized object
  57519. */
  57520. DoNothingAction.prototype.serialize = function (parent) {
  57521. return _super.prototype._serialize.call(this, {
  57522. name: "DoNothingAction",
  57523. properties: []
  57524. }, parent);
  57525. };
  57526. return DoNothingAction;
  57527. }(BABYLON.Action));
  57528. BABYLON.DoNothingAction = DoNothingAction;
  57529. /**
  57530. * This defines an action responsible to trigger several actions once triggered.
  57531. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57532. */
  57533. var CombineAction = /** @class */ (function (_super) {
  57534. __extends(CombineAction, _super);
  57535. /**
  57536. * Instantiate the action
  57537. * @param triggerOptions defines the trigger options
  57538. * @param children defines the list of aggregated animations to run
  57539. * @param condition defines the trigger related conditions
  57540. */
  57541. function CombineAction(triggerOptions, children, condition) {
  57542. var _this = _super.call(this, triggerOptions, condition) || this;
  57543. _this.children = children;
  57544. return _this;
  57545. }
  57546. /** @hidden */
  57547. CombineAction.prototype._prepare = function () {
  57548. for (var index = 0; index < this.children.length; index++) {
  57549. this.children[index]._actionManager = this._actionManager;
  57550. this.children[index]._prepare();
  57551. }
  57552. };
  57553. /**
  57554. * Execute the action and executes all the aggregated actions.
  57555. */
  57556. CombineAction.prototype.execute = function (evt) {
  57557. for (var index = 0; index < this.children.length; index++) {
  57558. this.children[index].execute(evt);
  57559. }
  57560. };
  57561. /**
  57562. * Serializes the actions and its related information.
  57563. * @param parent defines the object to serialize in
  57564. * @returns the serialized object
  57565. */
  57566. CombineAction.prototype.serialize = function (parent) {
  57567. var serializationObject = _super.prototype._serialize.call(this, {
  57568. name: "CombineAction",
  57569. properties: [],
  57570. combine: []
  57571. }, parent);
  57572. for (var i = 0; i < this.children.length; i++) {
  57573. serializationObject.combine.push(this.children[i].serialize(null));
  57574. }
  57575. return serializationObject;
  57576. };
  57577. return CombineAction;
  57578. }(BABYLON.Action));
  57579. BABYLON.CombineAction = CombineAction;
  57580. /**
  57581. * This defines an action responsible to run code (external event) once triggered.
  57582. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57583. */
  57584. var ExecuteCodeAction = /** @class */ (function (_super) {
  57585. __extends(ExecuteCodeAction, _super);
  57586. /**
  57587. * Instantiate the action
  57588. * @param triggerOptions defines the trigger options
  57589. * @param func defines the callback function to run
  57590. * @param condition defines the trigger related conditions
  57591. */
  57592. function ExecuteCodeAction(triggerOptions, func, condition) {
  57593. var _this = _super.call(this, triggerOptions, condition) || this;
  57594. _this.func = func;
  57595. return _this;
  57596. }
  57597. /**
  57598. * Execute the action and run the attached code.
  57599. */
  57600. ExecuteCodeAction.prototype.execute = function (evt) {
  57601. this.func(evt);
  57602. };
  57603. return ExecuteCodeAction;
  57604. }(BABYLON.Action));
  57605. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  57606. /**
  57607. * This defines an action responsible to set the parent property of the target once triggered.
  57608. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57609. */
  57610. var SetParentAction = /** @class */ (function (_super) {
  57611. __extends(SetParentAction, _super);
  57612. /**
  57613. * Instantiate the action
  57614. * @param triggerOptions defines the trigger options
  57615. * @param target defines the target containing the parent property
  57616. * @param parent defines from where the animation should start (animation frame)
  57617. * @param condition defines the trigger related conditions
  57618. */
  57619. function SetParentAction(triggerOptions, target, parent, condition) {
  57620. var _this = _super.call(this, triggerOptions, condition) || this;
  57621. _this._target = target;
  57622. _this._parent = parent;
  57623. return _this;
  57624. }
  57625. /** @hidden */
  57626. SetParentAction.prototype._prepare = function () {
  57627. };
  57628. /**
  57629. * Execute the action and set the parent property.
  57630. */
  57631. SetParentAction.prototype.execute = function () {
  57632. if (this._target.parent === this._parent) {
  57633. return;
  57634. }
  57635. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  57636. invertParentWorldMatrix.invert();
  57637. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  57638. this._target.parent = this._parent;
  57639. };
  57640. /**
  57641. * Serializes the actions and its related information.
  57642. * @param parent defines the object to serialize in
  57643. * @returns the serialized object
  57644. */
  57645. SetParentAction.prototype.serialize = function (parent) {
  57646. return _super.prototype._serialize.call(this, {
  57647. name: "SetParentAction",
  57648. properties: [
  57649. BABYLON.Action._GetTargetProperty(this._target),
  57650. BABYLON.Action._GetTargetProperty(this._parent),
  57651. ]
  57652. }, parent);
  57653. };
  57654. return SetParentAction;
  57655. }(BABYLON.Action));
  57656. BABYLON.SetParentAction = SetParentAction;
  57657. })(BABYLON || (BABYLON = {}));
  57658. //# sourceMappingURL=babylon.directActions.js.map
  57659. var BABYLON;
  57660. (function (BABYLON) {
  57661. /**
  57662. * Class used to manage multiple sprites on the same spritesheet
  57663. * @see http://doc.babylonjs.com/babylon101/sprites
  57664. */
  57665. var SpriteManager = /** @class */ (function () {
  57666. /**
  57667. * Creates a new sprite manager
  57668. * @param name defines the manager's name
  57669. * @param imgUrl defines the sprite sheet url
  57670. * @param capacity defines the maximum allowed number of sprites
  57671. * @param cellSize defines the size of a sprite cell
  57672. * @param scene defines the hosting scene
  57673. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  57674. * @param samplingMode defines the smapling mode to use with spritesheet
  57675. */
  57676. function SpriteManager(
  57677. /** defines the manager's name */
  57678. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  57679. if (epsilon === void 0) { epsilon = 0.01; }
  57680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57681. this.name = name;
  57682. /** Gets the list of sprites */
  57683. this.sprites = new Array();
  57684. /** Gets or sets the rendering group id (0 by default) */
  57685. this.renderingGroupId = 0;
  57686. /** Gets or sets camera layer mask */
  57687. this.layerMask = 0x0FFFFFFF;
  57688. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  57689. this.fogEnabled = true;
  57690. /** Gets or sets a boolean indicating if the sprites are pickable */
  57691. this.isPickable = false;
  57692. /**
  57693. * An event triggered when the manager is disposed.
  57694. */
  57695. this.onDisposeObservable = new BABYLON.Observable();
  57696. this._vertexBuffers = {};
  57697. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  57698. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  57699. }
  57700. this._capacity = capacity;
  57701. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  57702. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57703. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57704. if (cellSize.width && cellSize.height) {
  57705. this.cellWidth = cellSize.width;
  57706. this.cellHeight = cellSize.height;
  57707. }
  57708. else if (cellSize !== undefined) {
  57709. this.cellWidth = cellSize;
  57710. this.cellHeight = cellSize;
  57711. }
  57712. else {
  57713. return;
  57714. }
  57715. this._epsilon = epsilon;
  57716. this._scene = scene;
  57717. this._scene.spriteManagers.push(this);
  57718. var indices = [];
  57719. var index = 0;
  57720. for (var count = 0; count < capacity; count++) {
  57721. indices.push(index);
  57722. indices.push(index + 1);
  57723. indices.push(index + 2);
  57724. indices.push(index);
  57725. indices.push(index + 2);
  57726. indices.push(index + 3);
  57727. index += 4;
  57728. }
  57729. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  57730. // VBO
  57731. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  57732. this._vertexData = new Float32Array(capacity * 16 * 4);
  57733. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  57734. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  57735. var options = this._buffer.createVertexBuffer("options", 4, 4);
  57736. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  57737. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  57738. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57739. this._vertexBuffers["options"] = options;
  57740. this._vertexBuffers["cellInfo"] = cellInfo;
  57741. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57742. // Effects
  57743. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  57744. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  57745. }
  57746. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  57747. /**
  57748. * Callback called when the manager is disposed
  57749. */
  57750. set: function (callback) {
  57751. if (this._onDisposeObserver) {
  57752. this.onDisposeObservable.remove(this._onDisposeObserver);
  57753. }
  57754. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57755. },
  57756. enumerable: true,
  57757. configurable: true
  57758. });
  57759. Object.defineProperty(SpriteManager.prototype, "texture", {
  57760. /**
  57761. * Gets or sets the spritesheet texture
  57762. */
  57763. get: function () {
  57764. return this._spriteTexture;
  57765. },
  57766. set: function (value) {
  57767. this._spriteTexture = value;
  57768. },
  57769. enumerable: true,
  57770. configurable: true
  57771. });
  57772. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  57773. var arrayOffset = index * 16;
  57774. if (offsetX === 0) {
  57775. offsetX = this._epsilon;
  57776. }
  57777. else if (offsetX === 1) {
  57778. offsetX = 1 - this._epsilon;
  57779. }
  57780. if (offsetY === 0) {
  57781. offsetY = this._epsilon;
  57782. }
  57783. else if (offsetY === 1) {
  57784. offsetY = 1 - this._epsilon;
  57785. }
  57786. this._vertexData[arrayOffset] = sprite.position.x;
  57787. this._vertexData[arrayOffset + 1] = sprite.position.y;
  57788. this._vertexData[arrayOffset + 2] = sprite.position.z;
  57789. this._vertexData[arrayOffset + 3] = sprite.angle;
  57790. this._vertexData[arrayOffset + 4] = sprite.width;
  57791. this._vertexData[arrayOffset + 5] = sprite.height;
  57792. this._vertexData[arrayOffset + 6] = offsetX;
  57793. this._vertexData[arrayOffset + 7] = offsetY;
  57794. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  57795. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  57796. var offset = (sprite.cellIndex / rowSize) >> 0;
  57797. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  57798. this._vertexData[arrayOffset + 11] = offset;
  57799. // Color
  57800. this._vertexData[arrayOffset + 12] = sprite.color.r;
  57801. this._vertexData[arrayOffset + 13] = sprite.color.g;
  57802. this._vertexData[arrayOffset + 14] = sprite.color.b;
  57803. this._vertexData[arrayOffset + 15] = sprite.color.a;
  57804. };
  57805. /**
  57806. * Intersects the sprites with a ray
  57807. * @param ray defines the ray to intersect with
  57808. * @param camera defines the current active camera
  57809. * @param predicate defines a predicate used to select candidate sprites
  57810. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  57811. * @returns null if no hit or a PickingInfo
  57812. */
  57813. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  57814. var count = Math.min(this._capacity, this.sprites.length);
  57815. var min = BABYLON.Vector3.Zero();
  57816. var max = BABYLON.Vector3.Zero();
  57817. var distance = Number.MAX_VALUE;
  57818. var currentSprite = null;
  57819. var cameraSpacePosition = BABYLON.Vector3.Zero();
  57820. var cameraView = camera.getViewMatrix();
  57821. for (var index = 0; index < count; index++) {
  57822. var sprite = this.sprites[index];
  57823. if (!sprite) {
  57824. continue;
  57825. }
  57826. if (predicate) {
  57827. if (!predicate(sprite)) {
  57828. continue;
  57829. }
  57830. }
  57831. else if (!sprite.isPickable) {
  57832. continue;
  57833. }
  57834. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  57835. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  57836. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  57837. if (ray.intersectsBoxMinMax(min, max)) {
  57838. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  57839. if (distance > currentDistance) {
  57840. distance = currentDistance;
  57841. currentSprite = sprite;
  57842. if (fastCheck) {
  57843. break;
  57844. }
  57845. }
  57846. }
  57847. }
  57848. if (currentSprite) {
  57849. var result = new BABYLON.PickingInfo();
  57850. result.hit = true;
  57851. result.pickedSprite = currentSprite;
  57852. result.distance = distance;
  57853. return result;
  57854. }
  57855. return null;
  57856. };
  57857. /**
  57858. * Render all child sprites
  57859. */
  57860. SpriteManager.prototype.render = function () {
  57861. // Check
  57862. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  57863. return;
  57864. }
  57865. var engine = this._scene.getEngine();
  57866. var baseSize = this._spriteTexture.getBaseSize();
  57867. // Sprites
  57868. var deltaTime = engine.getDeltaTime();
  57869. var max = Math.min(this._capacity, this.sprites.length);
  57870. var rowSize = baseSize.width / this.cellWidth;
  57871. var offset = 0;
  57872. for (var index = 0; index < max; index++) {
  57873. var sprite = this.sprites[index];
  57874. if (!sprite || !sprite.isVisible) {
  57875. continue;
  57876. }
  57877. sprite._animate(deltaTime);
  57878. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  57879. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  57880. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  57881. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  57882. }
  57883. this._buffer.update(this._vertexData);
  57884. // Render
  57885. var effect = this._effectBase;
  57886. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57887. effect = this._effectFog;
  57888. }
  57889. engine.enableEffect(effect);
  57890. var viewMatrix = this._scene.getViewMatrix();
  57891. effect.setTexture("diffuseSampler", this._spriteTexture);
  57892. effect.setMatrix("view", viewMatrix);
  57893. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57894. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  57895. // Fog
  57896. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57897. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  57898. effect.setColor3("vFogColor", this._scene.fogColor);
  57899. }
  57900. // VBOs
  57901. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57902. // Draw order
  57903. engine.setDepthFunctionToLessOrEqual();
  57904. effect.setBool("alphaTest", true);
  57905. engine.setColorWrite(false);
  57906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57907. engine.setColorWrite(true);
  57908. effect.setBool("alphaTest", false);
  57909. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57910. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57911. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57912. };
  57913. /**
  57914. * Release associated resources
  57915. */
  57916. SpriteManager.prototype.dispose = function () {
  57917. if (this._buffer) {
  57918. this._buffer.dispose();
  57919. this._buffer = null;
  57920. }
  57921. if (this._indexBuffer) {
  57922. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57923. this._indexBuffer = null;
  57924. }
  57925. if (this._spriteTexture) {
  57926. this._spriteTexture.dispose();
  57927. this._spriteTexture = null;
  57928. }
  57929. // Remove from scene
  57930. var index = this._scene.spriteManagers.indexOf(this);
  57931. this._scene.spriteManagers.splice(index, 1);
  57932. // Callback
  57933. this.onDisposeObservable.notifyObservers(this);
  57934. this.onDisposeObservable.clear();
  57935. };
  57936. return SpriteManager;
  57937. }());
  57938. BABYLON.SpriteManager = SpriteManager;
  57939. })(BABYLON || (BABYLON = {}));
  57940. //# sourceMappingURL=babylon.spriteManager.js.map
  57941. var BABYLON;
  57942. (function (BABYLON) {
  57943. /**
  57944. * Class used to represent a sprite
  57945. * @see http://doc.babylonjs.com/babylon101/sprites
  57946. */
  57947. var Sprite = /** @class */ (function () {
  57948. /**
  57949. * Creates a new Sprite
  57950. * @param name defines the name
  57951. * @param manager defines the manager
  57952. */
  57953. function Sprite(
  57954. /** defines the name */
  57955. name, manager) {
  57956. this.name = name;
  57957. /** Gets or sets the main color */
  57958. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57959. /** Gets or sets the width */
  57960. this.width = 1.0;
  57961. /** Gets or sets the height */
  57962. this.height = 1.0;
  57963. /** Gets or sets rotation angle */
  57964. this.angle = 0;
  57965. /** Gets or sets the cell index in the sprite sheet */
  57966. this.cellIndex = 0;
  57967. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  57968. this.invertU = 0;
  57969. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  57970. this.invertV = 0;
  57971. /** Gets the list of attached animations */
  57972. this.animations = new Array();
  57973. /** Gets or sets a boolean indicating if the sprite can be picked */
  57974. this.isPickable = false;
  57975. this._animationStarted = false;
  57976. this._loopAnimation = false;
  57977. this._fromIndex = 0;
  57978. this._toIndex = 0;
  57979. this._delay = 0;
  57980. this._direction = 1;
  57981. this._time = 0;
  57982. /**
  57983. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  57984. */
  57985. this.isVisible = true;
  57986. this._manager = manager;
  57987. this._manager.sprites.push(this);
  57988. this.position = BABYLON.Vector3.Zero();
  57989. }
  57990. Object.defineProperty(Sprite.prototype, "size", {
  57991. /**
  57992. * Gets or sets the sprite size
  57993. */
  57994. get: function () {
  57995. return this.width;
  57996. },
  57997. set: function (value) {
  57998. this.width = value;
  57999. this.height = value;
  58000. },
  58001. enumerable: true,
  58002. configurable: true
  58003. });
  58004. /**
  58005. * Starts an animation
  58006. * @param from defines the initial key
  58007. * @param to defines the end key
  58008. * @param loop defines if the animation must loop
  58009. * @param delay defines the start delay (in ms)
  58010. * @param onAnimationEnd defines a callback to call when animation ends
  58011. */
  58012. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58013. this._fromIndex = from;
  58014. this._toIndex = to;
  58015. this._loopAnimation = loop;
  58016. this._delay = delay;
  58017. this._animationStarted = true;
  58018. this._direction = from < to ? 1 : -1;
  58019. this.cellIndex = from;
  58020. this._time = 0;
  58021. this._onAnimationEnd = onAnimationEnd;
  58022. };
  58023. /** Stops current animation (if any) */
  58024. Sprite.prototype.stopAnimation = function () {
  58025. this._animationStarted = false;
  58026. };
  58027. /** @hidden */
  58028. Sprite.prototype._animate = function (deltaTime) {
  58029. if (!this._animationStarted) {
  58030. return;
  58031. }
  58032. this._time += deltaTime;
  58033. if (this._time > this._delay) {
  58034. this._time = this._time % this._delay;
  58035. this.cellIndex += this._direction;
  58036. if (this.cellIndex > this._toIndex) {
  58037. if (this._loopAnimation) {
  58038. this.cellIndex = this._fromIndex;
  58039. }
  58040. else {
  58041. this.cellIndex = this._toIndex;
  58042. this._animationStarted = false;
  58043. if (this._onAnimationEnd) {
  58044. this._onAnimationEnd();
  58045. }
  58046. if (this.disposeWhenFinishedAnimating) {
  58047. this.dispose();
  58048. }
  58049. }
  58050. }
  58051. }
  58052. };
  58053. /** Release associated resources */
  58054. Sprite.prototype.dispose = function () {
  58055. for (var i = 0; i < this._manager.sprites.length; i++) {
  58056. if (this._manager.sprites[i] == this) {
  58057. this._manager.sprites.splice(i, 1);
  58058. }
  58059. }
  58060. };
  58061. return Sprite;
  58062. }());
  58063. BABYLON.Sprite = Sprite;
  58064. })(BABYLON || (BABYLON = {}));
  58065. //# sourceMappingURL=babylon.sprite.js.map
  58066. var BABYLON;
  58067. (function (BABYLON) {
  58068. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58069. if (!BABYLON.PickingInfo) {
  58070. return null;
  58071. }
  58072. var pickingInfo = null;
  58073. if (!camera) {
  58074. if (!this.activeCamera) {
  58075. return null;
  58076. }
  58077. camera = this.activeCamera;
  58078. }
  58079. if (this.spriteManagers.length > 0) {
  58080. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58081. var spriteManager = this.spriteManagers[spriteIndex];
  58082. if (!spriteManager.isPickable) {
  58083. continue;
  58084. }
  58085. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58086. if (!result || !result.hit) {
  58087. continue;
  58088. }
  58089. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58090. continue;
  58091. }
  58092. pickingInfo = result;
  58093. if (fastCheck) {
  58094. break;
  58095. }
  58096. }
  58097. }
  58098. return pickingInfo || new BABYLON.PickingInfo();
  58099. };
  58100. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58101. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58102. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58103. };
  58104. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58105. if (!this._tempSpritePickingRay) {
  58106. return null;
  58107. }
  58108. if (!camera) {
  58109. if (!this.activeCamera) {
  58110. return null;
  58111. }
  58112. camera = this.activeCamera;
  58113. }
  58114. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58115. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58116. };
  58117. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58118. if (this._pointerOverSprite === sprite) {
  58119. return;
  58120. }
  58121. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58122. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58123. }
  58124. this._pointerOverSprite = sprite;
  58125. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58126. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58127. }
  58128. };
  58129. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58130. return this._pointerOverSprite;
  58131. };
  58132. /**
  58133. * Defines the sprite scene component responsible to manage sprites
  58134. * in a given scene.
  58135. */
  58136. var SpriteSceneComponent = /** @class */ (function () {
  58137. /**
  58138. * Creates a new instance of the component for the given scene
  58139. * @param scene Defines the scene to register the component in
  58140. */
  58141. function SpriteSceneComponent(scene) {
  58142. /**
  58143. * The component name helpfull to identify the component in the list of scene components.
  58144. */
  58145. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58146. this.scene = scene;
  58147. this.scene.spriteManagers = new Array();
  58148. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58149. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58150. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58151. this._spritePredicate = function (sprite) {
  58152. if (!sprite.actionManager) {
  58153. return false;
  58154. }
  58155. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58156. };
  58157. }
  58158. /**
  58159. * Registers the component in a given scene
  58160. */
  58161. SpriteSceneComponent.prototype.register = function () {
  58162. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58163. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58164. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58165. };
  58166. /**
  58167. * Rebuilds the elements related to this component in case of
  58168. * context lost for instance.
  58169. */
  58170. SpriteSceneComponent.prototype.rebuild = function () {
  58171. /** Nothing to do for sprites */
  58172. };
  58173. /**
  58174. * Disposes the component and the associated ressources.
  58175. */
  58176. SpriteSceneComponent.prototype.dispose = function () {
  58177. this.scene.onBeforeSpritesRenderingObservable.clear();
  58178. this.scene.onAfterSpritesRenderingObservable.clear();
  58179. var spriteManagers = this.scene.spriteManagers;
  58180. while (spriteManagers.length) {
  58181. spriteManagers[0].dispose();
  58182. }
  58183. };
  58184. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58185. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58186. if (result) {
  58187. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58188. }
  58189. return result;
  58190. };
  58191. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58192. var scene = this.scene;
  58193. if (isMeshPicked) {
  58194. scene.setPointerOverSprite(null);
  58195. }
  58196. else {
  58197. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58198. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58199. scene.setPointerOverSprite(pickResult.pickedSprite);
  58200. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58201. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58202. }
  58203. else {
  58204. canvas.style.cursor = scene.hoverCursor;
  58205. }
  58206. }
  58207. else {
  58208. scene.setPointerOverSprite(null);
  58209. }
  58210. }
  58211. return pickResult;
  58212. };
  58213. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58214. var scene = this.scene;
  58215. scene._pickedDownSprite = null;
  58216. if (scene.spriteManagers.length > 0) {
  58217. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58218. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58219. if (pickResult.pickedSprite.actionManager) {
  58220. scene._pickedDownSprite = pickResult.pickedSprite;
  58221. switch (evt.button) {
  58222. case 0:
  58223. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58224. break;
  58225. case 1:
  58226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58227. break;
  58228. case 2:
  58229. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58230. break;
  58231. }
  58232. if (pickResult.pickedSprite.actionManager) {
  58233. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58234. }
  58235. }
  58236. }
  58237. }
  58238. return pickResult;
  58239. };
  58240. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58241. var scene = this.scene;
  58242. if (scene.spriteManagers.length > 0) {
  58243. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58244. if (spritePickResult) {
  58245. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58246. if (spritePickResult.pickedSprite.actionManager) {
  58247. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58248. if (spritePickResult.pickedSprite.actionManager) {
  58249. if (!this.scene._isPointerSwiping()) {
  58250. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58251. }
  58252. }
  58253. }
  58254. }
  58255. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58256. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58257. }
  58258. }
  58259. }
  58260. return pickResult;
  58261. };
  58262. return SpriteSceneComponent;
  58263. }());
  58264. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58265. })(BABYLON || (BABYLON = {}));
  58266. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  58267. var BABYLON;
  58268. (function (BABYLON) {
  58269. /**
  58270. * @hidden
  58271. */
  58272. var IntersectionInfo = /** @class */ (function () {
  58273. function IntersectionInfo(bu, bv, distance) {
  58274. this.bu = bu;
  58275. this.bv = bv;
  58276. this.distance = distance;
  58277. this.faceId = 0;
  58278. this.subMeshId = 0;
  58279. }
  58280. return IntersectionInfo;
  58281. }());
  58282. BABYLON.IntersectionInfo = IntersectionInfo;
  58283. /**
  58284. * Information about the result of picking within a scene
  58285. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58286. */
  58287. var PickingInfo = /** @class */ (function () {
  58288. function PickingInfo() {
  58289. /**
  58290. * If the pick collided with an object
  58291. */
  58292. this.hit = false;
  58293. /**
  58294. * Distance away where the pick collided
  58295. */
  58296. this.distance = 0;
  58297. /**
  58298. * The location of pick collision
  58299. */
  58300. this.pickedPoint = null;
  58301. /**
  58302. * The mesh corresponding the the pick collision
  58303. */
  58304. this.pickedMesh = null;
  58305. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58306. this.bu = 0;
  58307. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58308. this.bv = 0;
  58309. /** The id of the face on the mesh that was picked */
  58310. this.faceId = -1;
  58311. /** Id of the the submesh that was picked */
  58312. this.subMeshId = 0;
  58313. /** If a sprite was picked, this will be the sprite the pick collided with */
  58314. this.pickedSprite = null;
  58315. /**
  58316. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58317. */
  58318. this.originMesh = null;
  58319. /**
  58320. * The ray that was used to perform the picking.
  58321. */
  58322. this.ray = null;
  58323. }
  58324. /**
  58325. * Gets the normal correspodning to the face the pick collided with
  58326. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58327. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58328. * @returns The normal correspodning to the face the pick collided with
  58329. */
  58330. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58331. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58332. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58333. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58334. return null;
  58335. }
  58336. var indices = this.pickedMesh.getIndices();
  58337. if (!indices) {
  58338. return null;
  58339. }
  58340. var result;
  58341. if (useVerticesNormals) {
  58342. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58343. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58344. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58345. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58346. normal0 = normal0.scale(this.bu);
  58347. normal1 = normal1.scale(this.bv);
  58348. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58349. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58350. }
  58351. else {
  58352. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58353. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58354. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58355. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58356. var p1p2 = vertex1.subtract(vertex2);
  58357. var p3p2 = vertex3.subtract(vertex2);
  58358. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58359. }
  58360. if (useWorldCoordinates) {
  58361. var wm = this.pickedMesh.getWorldMatrix();
  58362. if (this.pickedMesh.nonUniformScaling) {
  58363. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58364. wm = BABYLON.Tmp.Matrix[0];
  58365. wm.setTranslationFromFloats(0, 0, 0);
  58366. wm.invert();
  58367. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58368. wm = BABYLON.Tmp.Matrix[1];
  58369. }
  58370. result = BABYLON.Vector3.TransformNormal(result, wm);
  58371. }
  58372. result.normalize();
  58373. return result;
  58374. };
  58375. /**
  58376. * Gets the texture coordinates of where the pick occured
  58377. * @returns the vector containing the coordnates of the texture
  58378. */
  58379. PickingInfo.prototype.getTextureCoordinates = function () {
  58380. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58381. return null;
  58382. }
  58383. var indices = this.pickedMesh.getIndices();
  58384. if (!indices) {
  58385. return null;
  58386. }
  58387. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58388. if (!uvs) {
  58389. return null;
  58390. }
  58391. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58392. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58393. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58394. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58395. uv1 = uv1.scale(this.bu);
  58396. uv2 = uv2.scale(this.bv);
  58397. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58398. };
  58399. return PickingInfo;
  58400. }());
  58401. BABYLON.PickingInfo = PickingInfo;
  58402. })(BABYLON || (BABYLON = {}));
  58403. //# sourceMappingURL=babylon.pickingInfo.js.map
  58404. var BABYLON;
  58405. (function (BABYLON) {
  58406. /**
  58407. * Class representing a ray with position and direction
  58408. */
  58409. var Ray = /** @class */ (function () {
  58410. /**
  58411. * Creates a new ray
  58412. * @param origin origin point
  58413. * @param direction direction
  58414. * @param length length of the ray
  58415. */
  58416. function Ray(
  58417. /** origin point */
  58418. origin,
  58419. /** direction */
  58420. direction,
  58421. /** length of the ray */
  58422. length) {
  58423. if (length === void 0) { length = Number.MAX_VALUE; }
  58424. this.origin = origin;
  58425. this.direction = direction;
  58426. this.length = length;
  58427. }
  58428. // Methods
  58429. /**
  58430. * Checks if the ray intersects a box
  58431. * @param minimum bound of the box
  58432. * @param maximum bound of the box
  58433. * @returns if the box was hit
  58434. */
  58435. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  58436. var d = 0.0;
  58437. var maxValue = Number.MAX_VALUE;
  58438. var inv;
  58439. var min;
  58440. var max;
  58441. var temp;
  58442. if (Math.abs(this.direction.x) < 0.0000001) {
  58443. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  58444. return false;
  58445. }
  58446. }
  58447. else {
  58448. inv = 1.0 / this.direction.x;
  58449. min = (minimum.x - this.origin.x) * inv;
  58450. max = (maximum.x - this.origin.x) * inv;
  58451. if (max === -Infinity) {
  58452. max = Infinity;
  58453. }
  58454. if (min > max) {
  58455. temp = min;
  58456. min = max;
  58457. max = temp;
  58458. }
  58459. d = Math.max(min, d);
  58460. maxValue = Math.min(max, maxValue);
  58461. if (d > maxValue) {
  58462. return false;
  58463. }
  58464. }
  58465. if (Math.abs(this.direction.y) < 0.0000001) {
  58466. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  58467. return false;
  58468. }
  58469. }
  58470. else {
  58471. inv = 1.0 / this.direction.y;
  58472. min = (minimum.y - this.origin.y) * inv;
  58473. max = (maximum.y - this.origin.y) * inv;
  58474. if (max === -Infinity) {
  58475. max = Infinity;
  58476. }
  58477. if (min > max) {
  58478. temp = min;
  58479. min = max;
  58480. max = temp;
  58481. }
  58482. d = Math.max(min, d);
  58483. maxValue = Math.min(max, maxValue);
  58484. if (d > maxValue) {
  58485. return false;
  58486. }
  58487. }
  58488. if (Math.abs(this.direction.z) < 0.0000001) {
  58489. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  58490. return false;
  58491. }
  58492. }
  58493. else {
  58494. inv = 1.0 / this.direction.z;
  58495. min = (minimum.z - this.origin.z) * inv;
  58496. max = (maximum.z - this.origin.z) * inv;
  58497. if (max === -Infinity) {
  58498. max = Infinity;
  58499. }
  58500. if (min > max) {
  58501. temp = min;
  58502. min = max;
  58503. max = temp;
  58504. }
  58505. d = Math.max(min, d);
  58506. maxValue = Math.min(max, maxValue);
  58507. if (d > maxValue) {
  58508. return false;
  58509. }
  58510. }
  58511. return true;
  58512. };
  58513. /**
  58514. * Checks if the ray intersects a box
  58515. * @param box the bounding box to check
  58516. * @returns if the box was hit
  58517. */
  58518. Ray.prototype.intersectsBox = function (box) {
  58519. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  58520. };
  58521. /**
  58522. * If the ray hits a sphere
  58523. * @param sphere the bounding sphere to check
  58524. * @returns true if it hits the sphere
  58525. */
  58526. Ray.prototype.intersectsSphere = function (sphere) {
  58527. var x = sphere.center.x - this.origin.x;
  58528. var y = sphere.center.y - this.origin.y;
  58529. var z = sphere.center.z - this.origin.z;
  58530. var pyth = (x * x) + (y * y) + (z * z);
  58531. var rr = sphere.radius * sphere.radius;
  58532. if (pyth <= rr) {
  58533. return true;
  58534. }
  58535. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58536. if (dot < 0.0) {
  58537. return false;
  58538. }
  58539. var temp = pyth - (dot * dot);
  58540. return temp <= rr;
  58541. };
  58542. /**
  58543. * If the ray hits a triange
  58544. * @param vertex0 triangle vertex
  58545. * @param vertex1 triangle vertex
  58546. * @param vertex2 triangle vertex
  58547. * @returns intersection information if hit
  58548. */
  58549. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  58550. if (!this._edge1) {
  58551. this._edge1 = BABYLON.Vector3.Zero();
  58552. this._edge2 = BABYLON.Vector3.Zero();
  58553. this._pvec = BABYLON.Vector3.Zero();
  58554. this._tvec = BABYLON.Vector3.Zero();
  58555. this._qvec = BABYLON.Vector3.Zero();
  58556. }
  58557. vertex1.subtractToRef(vertex0, this._edge1);
  58558. vertex2.subtractToRef(vertex0, this._edge2);
  58559. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  58560. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  58561. if (det === 0) {
  58562. return null;
  58563. }
  58564. var invdet = 1 / det;
  58565. this.origin.subtractToRef(vertex0, this._tvec);
  58566. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  58567. if (bu < 0 || bu > 1.0) {
  58568. return null;
  58569. }
  58570. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  58571. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  58572. if (bv < 0 || bu + bv > 1.0) {
  58573. return null;
  58574. }
  58575. //check if the distance is longer than the predefined length.
  58576. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  58577. if (distance > this.length) {
  58578. return null;
  58579. }
  58580. return new BABYLON.IntersectionInfo(bu, bv, distance);
  58581. };
  58582. /**
  58583. * Checks if ray intersects a plane
  58584. * @param plane the plane to check
  58585. * @returns the distance away it was hit
  58586. */
  58587. Ray.prototype.intersectsPlane = function (plane) {
  58588. var distance;
  58589. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  58590. if (Math.abs(result1) < 9.99999997475243E-07) {
  58591. return null;
  58592. }
  58593. else {
  58594. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  58595. distance = (-plane.d - result2) / result1;
  58596. if (distance < 0.0) {
  58597. if (distance < -9.99999997475243E-07) {
  58598. return null;
  58599. }
  58600. else {
  58601. return 0;
  58602. }
  58603. }
  58604. return distance;
  58605. }
  58606. };
  58607. /**
  58608. * Checks if ray intersects a mesh
  58609. * @param mesh the mesh to check
  58610. * @param fastCheck if only the bounding box should checked
  58611. * @returns picking info of the intersecton
  58612. */
  58613. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  58614. var tm = BABYLON.Tmp.Matrix[0];
  58615. mesh.getWorldMatrix().invertToRef(tm);
  58616. if (this._tmpRay) {
  58617. Ray.TransformToRef(this, tm, this._tmpRay);
  58618. }
  58619. else {
  58620. this._tmpRay = Ray.Transform(this, tm);
  58621. }
  58622. return mesh.intersects(this._tmpRay, fastCheck);
  58623. };
  58624. /**
  58625. * Checks if ray intersects a mesh
  58626. * @param meshes the meshes to check
  58627. * @param fastCheck if only the bounding box should checked
  58628. * @param results array to store result in
  58629. * @returns Array of picking infos
  58630. */
  58631. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  58632. if (results) {
  58633. results.length = 0;
  58634. }
  58635. else {
  58636. results = [];
  58637. }
  58638. for (var i = 0; i < meshes.length; i++) {
  58639. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  58640. if (pickInfo.hit) {
  58641. results.push(pickInfo);
  58642. }
  58643. }
  58644. results.sort(this._comparePickingInfo);
  58645. return results;
  58646. };
  58647. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  58648. if (pickingInfoA.distance < pickingInfoB.distance) {
  58649. return -1;
  58650. }
  58651. else if (pickingInfoA.distance > pickingInfoB.distance) {
  58652. return 1;
  58653. }
  58654. else {
  58655. return 0;
  58656. }
  58657. };
  58658. /**
  58659. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  58660. * @param sega the first point of the segment to test the intersection against
  58661. * @param segb the second point of the segment to test the intersection against
  58662. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  58663. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  58664. */
  58665. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  58666. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  58667. var u = segb.subtract(sega);
  58668. var v = rsegb.subtract(this.origin);
  58669. var w = sega.subtract(this.origin);
  58670. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  58671. var b = BABYLON.Vector3.Dot(u, v);
  58672. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  58673. var d = BABYLON.Vector3.Dot(u, w);
  58674. var e = BABYLON.Vector3.Dot(v, w);
  58675. var D = a * c - b * b; // always >= 0
  58676. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  58677. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  58678. // compute the line parameters of the two closest points
  58679. if (D < Ray.smallnum) { // the lines are almost parallel
  58680. sN = 0.0; // force using point P0 on segment S1
  58681. sD = 1.0; // to prevent possible division by 0.0 later
  58682. tN = e;
  58683. tD = c;
  58684. }
  58685. else { // get the closest points on the infinite lines
  58686. sN = (b * e - c * d);
  58687. tN = (a * e - b * d);
  58688. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  58689. sN = 0.0;
  58690. tN = e;
  58691. tD = c;
  58692. }
  58693. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  58694. sN = sD;
  58695. tN = e + b;
  58696. tD = c;
  58697. }
  58698. }
  58699. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  58700. tN = 0.0;
  58701. // recompute sc for this edge
  58702. if (-d < 0.0) {
  58703. sN = 0.0;
  58704. }
  58705. else if (-d > a) {
  58706. sN = sD;
  58707. }
  58708. else {
  58709. sN = -d;
  58710. sD = a;
  58711. }
  58712. }
  58713. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  58714. tN = tD;
  58715. // recompute sc for this edge
  58716. if ((-d + b) < 0.0) {
  58717. sN = 0;
  58718. }
  58719. else if ((-d + b) > a) {
  58720. sN = sD;
  58721. }
  58722. else {
  58723. sN = (-d + b);
  58724. sD = a;
  58725. }
  58726. }
  58727. // finally do the division to get sc and tc
  58728. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  58729. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  58730. // get the difference of the two closest points
  58731. var qtc = v.multiplyByFloats(tc, tc, tc);
  58732. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  58733. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  58734. if (isIntersected) {
  58735. return qtc.length();
  58736. }
  58737. return -1;
  58738. };
  58739. /**
  58740. * Update the ray from viewport position
  58741. * @param x position
  58742. * @param y y position
  58743. * @param viewportWidth viewport width
  58744. * @param viewportHeight viewport height
  58745. * @param world world matrix
  58746. * @param view view matrix
  58747. * @param projection projection matrix
  58748. * @returns this ray updated
  58749. */
  58750. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58751. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  58752. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  58753. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  58754. this.direction.normalize();
  58755. return this;
  58756. };
  58757. // Statics
  58758. /**
  58759. * Creates a ray with origin and direction of 0,0,0
  58760. * @returns the new ray
  58761. */
  58762. Ray.Zero = function () {
  58763. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  58764. };
  58765. /**
  58766. * Creates a new ray from screen space and viewport
  58767. * @param x position
  58768. * @param y y position
  58769. * @param viewportWidth viewport width
  58770. * @param viewportHeight viewport height
  58771. * @param world world matrix
  58772. * @param view view matrix
  58773. * @param projection projection matrix
  58774. * @returns new ray
  58775. */
  58776. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58777. var result = Ray.Zero();
  58778. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  58779. };
  58780. /**
  58781. * 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
  58782. * transformed to the given world matrix.
  58783. * @param origin The origin point
  58784. * @param end The end point
  58785. * @param world a matrix to transform the ray to. Default is the identity matrix.
  58786. * @returns the new ray
  58787. */
  58788. Ray.CreateNewFromTo = function (origin, end, world) {
  58789. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  58790. var direction = end.subtract(origin);
  58791. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  58792. direction.normalize();
  58793. return Ray.Transform(new Ray(origin, direction, length), world);
  58794. };
  58795. /**
  58796. * Transforms a ray by a matrix
  58797. * @param ray ray to transform
  58798. * @param matrix matrix to apply
  58799. * @returns the resulting new ray
  58800. */
  58801. Ray.Transform = function (ray, matrix) {
  58802. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  58803. Ray.TransformToRef(ray, matrix, result);
  58804. return result;
  58805. };
  58806. /**
  58807. * Transforms a ray by a matrix
  58808. * @param ray ray to transform
  58809. * @param matrix matrix to apply
  58810. * @param result ray to store result in
  58811. */
  58812. Ray.TransformToRef = function (ray, matrix, result) {
  58813. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  58814. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  58815. result.length = ray.length;
  58816. var dir = result.direction;
  58817. var len = dir.length();
  58818. if (!(len === 0 || len === 1)) {
  58819. var num = 1.0 / len;
  58820. dir.x *= num;
  58821. dir.y *= num;
  58822. dir.z *= num;
  58823. result.length *= len;
  58824. }
  58825. };
  58826. Ray.smallnum = 0.00000001;
  58827. Ray.rayl = 10e8;
  58828. return Ray;
  58829. }());
  58830. BABYLON.Ray = Ray;
  58831. })(BABYLON || (BABYLON = {}));
  58832. //# sourceMappingURL=babylon.ray.js.map
  58833. var BABYLON;
  58834. (function (BABYLON) {
  58835. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  58836. if (boxMin.x > sphereCenter.x + sphereRadius) {
  58837. return false;
  58838. }
  58839. if (sphereCenter.x - sphereRadius > boxMax.x) {
  58840. return false;
  58841. }
  58842. if (boxMin.y > sphereCenter.y + sphereRadius) {
  58843. return false;
  58844. }
  58845. if (sphereCenter.y - sphereRadius > boxMax.y) {
  58846. return false;
  58847. }
  58848. if (boxMin.z > sphereCenter.z + sphereRadius) {
  58849. return false;
  58850. }
  58851. if (sphereCenter.z - sphereRadius > boxMax.z) {
  58852. return false;
  58853. }
  58854. return true;
  58855. };
  58856. var getLowestRoot = (function () {
  58857. var result = { root: 0, found: false };
  58858. return function (a, b, c, maxR) {
  58859. result.root = 0;
  58860. result.found = false;
  58861. var determinant = b * b - 4.0 * a * c;
  58862. if (determinant < 0) {
  58863. return result;
  58864. }
  58865. var sqrtD = Math.sqrt(determinant);
  58866. var r1 = (-b - sqrtD) / (2.0 * a);
  58867. var r2 = (-b + sqrtD) / (2.0 * a);
  58868. if (r1 > r2) {
  58869. var temp = r2;
  58870. r2 = r1;
  58871. r1 = temp;
  58872. }
  58873. if (r1 > 0 && r1 < maxR) {
  58874. result.root = r1;
  58875. result.found = true;
  58876. return result;
  58877. }
  58878. if (r2 > 0 && r2 < maxR) {
  58879. result.root = r2;
  58880. result.found = true;
  58881. return result;
  58882. }
  58883. return result;
  58884. };
  58885. })();
  58886. /** @hidden */
  58887. var Collider = /** @class */ (function () {
  58888. function Collider() {
  58889. this._collisionPoint = BABYLON.Vector3.Zero();
  58890. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  58891. this._tempVector = BABYLON.Vector3.Zero();
  58892. this._tempVector2 = BABYLON.Vector3.Zero();
  58893. this._tempVector3 = BABYLON.Vector3.Zero();
  58894. this._tempVector4 = BABYLON.Vector3.Zero();
  58895. this._edge = BABYLON.Vector3.Zero();
  58896. this._baseToVertex = BABYLON.Vector3.Zero();
  58897. this._destinationPoint = BABYLON.Vector3.Zero();
  58898. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  58899. this._displacementVector = BABYLON.Vector3.Zero();
  58900. /** @hidden */
  58901. this._radius = BABYLON.Vector3.One();
  58902. /** @hidden */
  58903. this._retry = 0;
  58904. /** @hidden */
  58905. this._basePointWorld = BABYLON.Vector3.Zero();
  58906. this._velocityWorld = BABYLON.Vector3.Zero();
  58907. this._normalizedVelocity = BABYLON.Vector3.Zero();
  58908. this._collisionMask = -1;
  58909. }
  58910. Object.defineProperty(Collider.prototype, "collisionMask", {
  58911. get: function () {
  58912. return this._collisionMask;
  58913. },
  58914. set: function (mask) {
  58915. this._collisionMask = !isNaN(mask) ? mask : -1;
  58916. },
  58917. enumerable: true,
  58918. configurable: true
  58919. });
  58920. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  58921. /**
  58922. * Gets the plane normal used to compute the sliding response (in local space)
  58923. */
  58924. get: function () {
  58925. return this._slidePlaneNormal;
  58926. },
  58927. enumerable: true,
  58928. configurable: true
  58929. });
  58930. // Methods
  58931. /** @hidden */
  58932. Collider.prototype._initialize = function (source, dir, e) {
  58933. this._velocity = dir;
  58934. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  58935. this._basePoint = source;
  58936. source.multiplyToRef(this._radius, this._basePointWorld);
  58937. dir.multiplyToRef(this._radius, this._velocityWorld);
  58938. this._velocityWorldLength = this._velocityWorld.length();
  58939. this._epsilon = e;
  58940. this.collisionFound = false;
  58941. };
  58942. /** @hidden */
  58943. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  58944. pa.subtractToRef(point, this._tempVector);
  58945. pb.subtractToRef(point, this._tempVector2);
  58946. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  58947. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58948. if (d < 0) {
  58949. return false;
  58950. }
  58951. pc.subtractToRef(point, this._tempVector3);
  58952. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  58953. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58954. if (d < 0) {
  58955. return false;
  58956. }
  58957. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  58958. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58959. return d >= 0;
  58960. };
  58961. /** @hidden */
  58962. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  58963. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  58964. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  58965. if (distance > this._velocityWorldLength + max + sphereRadius) {
  58966. return false;
  58967. }
  58968. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  58969. return false;
  58970. }
  58971. return true;
  58972. };
  58973. /** @hidden */
  58974. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  58975. var t0;
  58976. var embeddedInPlane = false;
  58977. //defensive programming, actually not needed.
  58978. if (!trianglePlaneArray) {
  58979. trianglePlaneArray = [];
  58980. }
  58981. if (!trianglePlaneArray[faceIndex]) {
  58982. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  58983. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  58984. }
  58985. var trianglePlane = trianglePlaneArray[faceIndex];
  58986. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  58987. return;
  58988. }
  58989. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  58990. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  58991. if (normalDotVelocity == 0) {
  58992. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  58993. return;
  58994. }
  58995. embeddedInPlane = true;
  58996. t0 = 0;
  58997. }
  58998. else {
  58999. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59000. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59001. if (t0 > t1) {
  59002. var temp = t1;
  59003. t1 = t0;
  59004. t0 = temp;
  59005. }
  59006. if (t0 > 1.0 || t1 < 0.0) {
  59007. return;
  59008. }
  59009. if (t0 < 0) {
  59010. t0 = 0;
  59011. }
  59012. if (t0 > 1.0) {
  59013. t0 = 1.0;
  59014. }
  59015. }
  59016. this._collisionPoint.copyFromFloats(0, 0, 0);
  59017. var found = false;
  59018. var t = 1.0;
  59019. if (!embeddedInPlane) {
  59020. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59021. this._velocity.scaleToRef(t0, this._tempVector);
  59022. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59023. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59024. found = true;
  59025. t = t0;
  59026. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59027. }
  59028. }
  59029. if (!found) {
  59030. var velocitySquaredLength = this._velocity.lengthSquared();
  59031. var a = velocitySquaredLength;
  59032. this._basePoint.subtractToRef(p1, this._tempVector);
  59033. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59034. var c = this._tempVector.lengthSquared() - 1.0;
  59035. var lowestRoot = getLowestRoot(a, b, c, t);
  59036. if (lowestRoot.found) {
  59037. t = lowestRoot.root;
  59038. found = true;
  59039. this._collisionPoint.copyFrom(p1);
  59040. }
  59041. this._basePoint.subtractToRef(p2, this._tempVector);
  59042. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59043. c = this._tempVector.lengthSquared() - 1.0;
  59044. lowestRoot = getLowestRoot(a, b, c, t);
  59045. if (lowestRoot.found) {
  59046. t = lowestRoot.root;
  59047. found = true;
  59048. this._collisionPoint.copyFrom(p2);
  59049. }
  59050. this._basePoint.subtractToRef(p3, this._tempVector);
  59051. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59052. c = this._tempVector.lengthSquared() - 1.0;
  59053. lowestRoot = getLowestRoot(a, b, c, t);
  59054. if (lowestRoot.found) {
  59055. t = lowestRoot.root;
  59056. found = true;
  59057. this._collisionPoint.copyFrom(p3);
  59058. }
  59059. p2.subtractToRef(p1, this._edge);
  59060. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59061. var edgeSquaredLength = this._edge.lengthSquared();
  59062. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59063. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59064. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59065. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59066. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59067. lowestRoot = getLowestRoot(a, b, c, t);
  59068. if (lowestRoot.found) {
  59069. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59070. if (f >= 0.0 && f <= 1.0) {
  59071. t = lowestRoot.root;
  59072. found = true;
  59073. this._edge.scaleInPlace(f);
  59074. p1.addToRef(this._edge, this._collisionPoint);
  59075. }
  59076. }
  59077. p3.subtractToRef(p2, this._edge);
  59078. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59079. edgeSquaredLength = this._edge.lengthSquared();
  59080. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59081. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59082. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59083. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59084. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59085. lowestRoot = getLowestRoot(a, b, c, t);
  59086. if (lowestRoot.found) {
  59087. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59088. if (f >= 0.0 && f <= 1.0) {
  59089. t = lowestRoot.root;
  59090. found = true;
  59091. this._edge.scaleInPlace(f);
  59092. p2.addToRef(this._edge, this._collisionPoint);
  59093. }
  59094. }
  59095. p1.subtractToRef(p3, this._edge);
  59096. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59097. edgeSquaredLength = this._edge.lengthSquared();
  59098. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59099. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59100. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59101. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59102. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59103. lowestRoot = getLowestRoot(a, b, c, t);
  59104. if (lowestRoot.found) {
  59105. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59106. if (f >= 0.0 && f <= 1.0) {
  59107. t = lowestRoot.root;
  59108. found = true;
  59109. this._edge.scaleInPlace(f);
  59110. p3.addToRef(this._edge, this._collisionPoint);
  59111. }
  59112. }
  59113. }
  59114. if (found) {
  59115. var distToCollision = t * this._velocity.length();
  59116. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59117. if (!this.intersectionPoint) {
  59118. this.intersectionPoint = this._collisionPoint.clone();
  59119. }
  59120. else {
  59121. this.intersectionPoint.copyFrom(this._collisionPoint);
  59122. }
  59123. this._nearestDistance = distToCollision;
  59124. this.collisionFound = true;
  59125. }
  59126. }
  59127. };
  59128. /** @hidden */
  59129. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59130. for (var i = indexStart; i < indexEnd; i += 3) {
  59131. var p1 = pts[indices[i] - decal];
  59132. var p2 = pts[indices[i + 1] - decal];
  59133. var p3 = pts[indices[i + 2] - decal];
  59134. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59135. }
  59136. };
  59137. /** @hidden */
  59138. Collider.prototype._getResponse = function (pos, vel) {
  59139. pos.addToRef(vel, this._destinationPoint);
  59140. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59141. this._basePoint.addToRef(vel, pos);
  59142. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59143. this._slidePlaneNormal.normalize();
  59144. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59145. pos.addInPlace(this._displacementVector);
  59146. this.intersectionPoint.addInPlace(this._displacementVector);
  59147. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59148. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59149. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59150. };
  59151. return Collider;
  59152. }());
  59153. BABYLON.Collider = Collider;
  59154. })(BABYLON || (BABYLON = {}));
  59155. //# sourceMappingURL=babylon.collider.js.map
  59156. var BABYLON;
  59157. (function (BABYLON) {
  59158. //WebWorker code will be inserted to this variable.
  59159. /** @hidden */
  59160. BABYLON.CollisionWorker = "";
  59161. /** Defines supported task for worker process */
  59162. var WorkerTaskType;
  59163. (function (WorkerTaskType) {
  59164. /** Initialization */
  59165. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59166. /** Update of geometry */
  59167. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59168. /** Evaluate collision */
  59169. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59170. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59171. /** Defines kind of replies returned by worker */
  59172. var WorkerReplyType;
  59173. (function (WorkerReplyType) {
  59174. /** Success */
  59175. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59176. /** Unkown error */
  59177. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59178. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59179. /** @hidden */
  59180. var CollisionCoordinatorWorker = /** @class */ (function () {
  59181. function CollisionCoordinatorWorker() {
  59182. var _this = this;
  59183. this._scaledPosition = BABYLON.Vector3.Zero();
  59184. this._scaledVelocity = BABYLON.Vector3.Zero();
  59185. this.onMeshUpdated = function (transformNode) {
  59186. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59187. };
  59188. this.onGeometryUpdated = function (geometry) {
  59189. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59190. };
  59191. this._afterRender = function () {
  59192. if (!_this._init) {
  59193. return;
  59194. }
  59195. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59196. return;
  59197. }
  59198. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59199. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59200. if (_this._runningUpdated > 4) {
  59201. return;
  59202. }
  59203. ++_this._runningUpdated;
  59204. var payload = {
  59205. updatedMeshes: _this._addUpdateMeshesList,
  59206. updatedGeometries: _this._addUpdateGeometriesList,
  59207. removedGeometries: _this._toRemoveGeometryArray,
  59208. removedMeshes: _this._toRemoveMeshesArray
  59209. };
  59210. var message = {
  59211. payload: payload,
  59212. taskType: WorkerTaskType.UPDATE
  59213. };
  59214. var serializable = [];
  59215. for (var id in payload.updatedGeometries) {
  59216. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59217. //prepare transferables
  59218. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59219. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59220. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59221. }
  59222. }
  59223. _this._worker.postMessage(message, serializable);
  59224. _this._addUpdateMeshesList = {};
  59225. _this._addUpdateGeometriesList = {};
  59226. _this._toRemoveGeometryArray = [];
  59227. _this._toRemoveMeshesArray = [];
  59228. };
  59229. this._onMessageFromWorker = function (e) {
  59230. var returnData = e.data;
  59231. if (returnData.error != WorkerReplyType.SUCCESS) {
  59232. //TODO what errors can be returned from the worker?
  59233. BABYLON.Tools.Warn("error returned from worker!");
  59234. return;
  59235. }
  59236. switch (returnData.taskType) {
  59237. case WorkerTaskType.INIT:
  59238. _this._init = true;
  59239. //Update the worked with ALL of the scene's current state
  59240. _this._scene.meshes.forEach(function (mesh) {
  59241. _this.onMeshAdded(mesh);
  59242. });
  59243. _this._scene.getGeometries().forEach(function (geometry) {
  59244. _this.onGeometryAdded(geometry);
  59245. });
  59246. break;
  59247. case WorkerTaskType.UPDATE:
  59248. _this._runningUpdated--;
  59249. break;
  59250. case WorkerTaskType.COLLIDE:
  59251. var returnPayload = returnData.payload;
  59252. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59253. return;
  59254. }
  59255. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59256. if (callback) {
  59257. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59258. if (mesh) {
  59259. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59260. }
  59261. }
  59262. //cleanup
  59263. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59264. break;
  59265. }
  59266. };
  59267. this._collisionsCallbackArray = [];
  59268. this._init = false;
  59269. this._runningUpdated = 0;
  59270. this._addUpdateMeshesList = {};
  59271. this._addUpdateGeometriesList = {};
  59272. this._toRemoveGeometryArray = [];
  59273. this._toRemoveMeshesArray = [];
  59274. }
  59275. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59276. if (!this._init) {
  59277. return;
  59278. }
  59279. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59280. return;
  59281. }
  59282. position.divideToRef(collider._radius, this._scaledPosition);
  59283. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59284. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59285. var payload = {
  59286. collider: {
  59287. position: this._scaledPosition.asArray(),
  59288. velocity: this._scaledVelocity.asArray(),
  59289. radius: collider._radius.asArray()
  59290. },
  59291. collisionId: collisionIndex,
  59292. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59293. maximumRetry: maximumRetry
  59294. };
  59295. var message = {
  59296. payload: payload,
  59297. taskType: WorkerTaskType.COLLIDE
  59298. };
  59299. this._worker.postMessage(message);
  59300. };
  59301. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59302. this._scene = scene;
  59303. this._scene.registerAfterRender(this._afterRender);
  59304. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59305. this._worker = new Worker(workerUrl);
  59306. this._worker.onmessage = this._onMessageFromWorker;
  59307. var message = {
  59308. payload: {},
  59309. taskType: WorkerTaskType.INIT
  59310. };
  59311. this._worker.postMessage(message);
  59312. };
  59313. CollisionCoordinatorWorker.prototype.destroy = function () {
  59314. this._scene.unregisterAfterRender(this._afterRender);
  59315. this._worker.terminate();
  59316. };
  59317. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59318. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59319. this.onMeshUpdated(mesh);
  59320. };
  59321. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59322. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59323. };
  59324. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59325. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59326. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59327. this.onGeometryUpdated(geometry);
  59328. };
  59329. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59330. this._toRemoveGeometryArray.push(geometry.id);
  59331. };
  59332. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59333. var submeshes = [];
  59334. if (mesh.subMeshes) {
  59335. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59336. var boundingInfo = sm.getBoundingInfo();
  59337. return {
  59338. position: idx,
  59339. verticesStart: sm.verticesStart,
  59340. verticesCount: sm.verticesCount,
  59341. indexStart: sm.indexStart,
  59342. indexCount: sm.indexCount,
  59343. hasMaterial: !!sm.getMaterial(),
  59344. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59345. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59346. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59347. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59348. };
  59349. });
  59350. }
  59351. var geometryId = null;
  59352. if (mesh instanceof BABYLON.Mesh) {
  59353. var geometry = mesh.geometry;
  59354. geometryId = geometry ? geometry.id : null;
  59355. }
  59356. else if (mesh instanceof BABYLON.InstancedMesh) {
  59357. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59358. geometryId = geometry ? geometry.id : null;
  59359. }
  59360. var boundingInfo = mesh.getBoundingInfo();
  59361. return {
  59362. uniqueId: mesh.uniqueId,
  59363. id: mesh.id,
  59364. name: mesh.name,
  59365. geometryId: geometryId,
  59366. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59367. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59368. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59369. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59370. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59371. subMeshes: submeshes,
  59372. checkCollisions: mesh.checkCollisions
  59373. };
  59374. };
  59375. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59376. return {
  59377. id: geometry.id,
  59378. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59379. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59380. indices: new Uint32Array(geometry.getIndices() || []),
  59381. };
  59382. };
  59383. return CollisionCoordinatorWorker;
  59384. }());
  59385. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59386. /** @hidden */
  59387. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59388. function CollisionCoordinatorLegacy() {
  59389. this._scaledPosition = BABYLON.Vector3.Zero();
  59390. this._scaledVelocity = BABYLON.Vector3.Zero();
  59391. this._finalPosition = BABYLON.Vector3.Zero();
  59392. }
  59393. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59394. position.divideToRef(collider._radius, this._scaledPosition);
  59395. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59396. collider.collidedMesh = null;
  59397. collider._retry = 0;
  59398. collider._initialVelocity = this._scaledVelocity;
  59399. collider._initialPosition = this._scaledPosition;
  59400. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59401. this._finalPosition.multiplyInPlace(collider._radius);
  59402. //run the callback
  59403. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59404. };
  59405. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59406. this._scene = scene;
  59407. };
  59408. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59409. //Legacy need no destruction method.
  59410. };
  59411. //No update in legacy mode
  59412. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59413. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59414. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59415. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59416. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59417. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59418. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59419. if (excludedMesh === void 0) { excludedMesh = null; }
  59420. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59421. if (collider._retry >= maximumRetry) {
  59422. finalPosition.copyFrom(position);
  59423. return;
  59424. }
  59425. // Check if this is a mesh else camera or -1
  59426. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59427. collider._initialize(position, velocity, closeDistance);
  59428. // Check all meshes
  59429. for (var index = 0; index < this._scene.meshes.length; index++) {
  59430. var mesh = this._scene.meshes[index];
  59431. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59432. mesh._checkCollision(collider);
  59433. }
  59434. }
  59435. if (!collider.collisionFound) {
  59436. position.addToRef(velocity, finalPosition);
  59437. return;
  59438. }
  59439. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59440. collider._getResponse(position, velocity);
  59441. }
  59442. if (velocity.length() <= closeDistance) {
  59443. finalPosition.copyFrom(position);
  59444. return;
  59445. }
  59446. collider._retry++;
  59447. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59448. };
  59449. return CollisionCoordinatorLegacy;
  59450. }());
  59451. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59452. })(BABYLON || (BABYLON = {}));
  59453. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  59454. var BABYLON;
  59455. (function (BABYLON) {
  59456. /**
  59457. * A particle represents one of the element emitted by a particle system.
  59458. * This is mainly define by its coordinates, direction, velocity and age.
  59459. */
  59460. var Particle = /** @class */ (function () {
  59461. /**
  59462. * Creates a new instance Particle
  59463. * @param particleSystem the particle system the particle belongs to
  59464. */
  59465. function Particle(
  59466. /**
  59467. * The particle system the particle belongs to.
  59468. */
  59469. particleSystem) {
  59470. this.particleSystem = particleSystem;
  59471. /**
  59472. * The world position of the particle in the scene.
  59473. */
  59474. this.position = BABYLON.Vector3.Zero();
  59475. /**
  59476. * The world direction of the particle in the scene.
  59477. */
  59478. this.direction = BABYLON.Vector3.Zero();
  59479. /**
  59480. * The color of the particle.
  59481. */
  59482. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59483. /**
  59484. * The color change of the particle per step.
  59485. */
  59486. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59487. /**
  59488. * Defines how long will the life of the particle be.
  59489. */
  59490. this.lifeTime = 1.0;
  59491. /**
  59492. * The current age of the particle.
  59493. */
  59494. this.age = 0;
  59495. /**
  59496. * The current size of the particle.
  59497. */
  59498. this.size = 0;
  59499. /**
  59500. * The current scale of the particle.
  59501. */
  59502. this.scale = new BABYLON.Vector2(1, 1);
  59503. /**
  59504. * The current angle of the particle.
  59505. */
  59506. this.angle = 0;
  59507. /**
  59508. * Defines how fast is the angle changing.
  59509. */
  59510. this.angularSpeed = 0;
  59511. /**
  59512. * Defines the cell index used by the particle to be rendered from a sprite.
  59513. */
  59514. this.cellIndex = 0;
  59515. /** @hidden */
  59516. this._attachedSubEmitters = null;
  59517. /** @hidden */
  59518. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59519. /** @hidden */
  59520. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59521. /** @hidden */
  59522. this._currentSize1 = 0;
  59523. /** @hidden */
  59524. this._currentSize2 = 0;
  59525. /** @hidden */
  59526. this._currentAngularSpeed1 = 0;
  59527. /** @hidden */
  59528. this._currentAngularSpeed2 = 0;
  59529. /** @hidden */
  59530. this._currentVelocity1 = 0;
  59531. /** @hidden */
  59532. this._currentVelocity2 = 0;
  59533. /** @hidden */
  59534. this._currentLimitVelocity1 = 0;
  59535. /** @hidden */
  59536. this._currentLimitVelocity2 = 0;
  59537. /** @hidden */
  59538. this._currentDrag1 = 0;
  59539. /** @hidden */
  59540. this._currentDrag2 = 0;
  59541. this.id = Particle._Count++;
  59542. if (!this.particleSystem.isAnimationSheetEnabled) {
  59543. return;
  59544. }
  59545. this.updateCellInfoFromSystem();
  59546. }
  59547. Particle.prototype.updateCellInfoFromSystem = function () {
  59548. this.cellIndex = this.particleSystem.startSpriteCellID;
  59549. };
  59550. /**
  59551. * Defines how the sprite cell index is updated for the particle
  59552. */
  59553. Particle.prototype.updateCellIndex = function () {
  59554. var offsetAge = this.age;
  59555. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  59556. if (this.particleSystem.spriteRandomStartCell) {
  59557. if (this._randomCellOffset === undefined) {
  59558. this._randomCellOffset = Math.random() * this.lifeTime;
  59559. }
  59560. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  59561. changeSpeed = 1;
  59562. offsetAge = this._randomCellOffset;
  59563. }
  59564. else {
  59565. offsetAge += this._randomCellOffset;
  59566. }
  59567. }
  59568. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  59569. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  59570. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  59571. };
  59572. /** @hidden */
  59573. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  59574. if (subEmitter.particleSystem.emitter.position) {
  59575. var emitterMesh = subEmitter.particleSystem.emitter;
  59576. emitterMesh.position.copyFrom(this.position);
  59577. if (subEmitter.inheritDirection) {
  59578. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  59579. // Look at using Y as forward
  59580. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  59581. }
  59582. }
  59583. else {
  59584. var emitterPosition = subEmitter.particleSystem.emitter;
  59585. emitterPosition.copyFrom(this.position);
  59586. }
  59587. // Set inheritedVelocityOffset to be used when new particles are created
  59588. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  59589. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  59590. };
  59591. /** @hidden */
  59592. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  59593. var _this = this;
  59594. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  59595. this._attachedSubEmitters.forEach(function (subEmitter) {
  59596. _this._inheritParticleInfoToSubEmitter(subEmitter);
  59597. });
  59598. }
  59599. };
  59600. /** @hidden */
  59601. Particle.prototype._reset = function () {
  59602. this.age = 0;
  59603. this._currentColorGradient = null;
  59604. this._currentSizeGradient = null;
  59605. this._currentAngularSpeedGradient = null;
  59606. this._currentVelocityGradient = null;
  59607. this._currentLimitVelocityGradient = null;
  59608. this._currentDragGradient = null;
  59609. this.cellIndex = this.particleSystem.startSpriteCellID;
  59610. this._randomCellOffset = undefined;
  59611. };
  59612. /**
  59613. * Copy the properties of particle to another one.
  59614. * @param other the particle to copy the information to.
  59615. */
  59616. Particle.prototype.copyTo = function (other) {
  59617. other.position.copyFrom(this.position);
  59618. if (this._initialDirection) {
  59619. if (other._initialDirection) {
  59620. other._initialDirection.copyFrom(this._initialDirection);
  59621. }
  59622. else {
  59623. other._initialDirection = this._initialDirection.clone();
  59624. }
  59625. }
  59626. else {
  59627. other._initialDirection = null;
  59628. }
  59629. other.direction.copyFrom(this.direction);
  59630. other.color.copyFrom(this.color);
  59631. other.colorStep.copyFrom(this.colorStep);
  59632. other.lifeTime = this.lifeTime;
  59633. other.age = this.age;
  59634. other._randomCellOffset = this._randomCellOffset;
  59635. other.size = this.size;
  59636. other.scale.copyFrom(this.scale);
  59637. other.angle = this.angle;
  59638. other.angularSpeed = this.angularSpeed;
  59639. other.particleSystem = this.particleSystem;
  59640. other.cellIndex = this.cellIndex;
  59641. other.id = this.id;
  59642. other._attachedSubEmitters = this._attachedSubEmitters;
  59643. if (this._currentColorGradient) {
  59644. other._currentColorGradient = this._currentColorGradient;
  59645. other._currentColor1.copyFrom(this._currentColor1);
  59646. other._currentColor2.copyFrom(this._currentColor2);
  59647. }
  59648. if (this._currentSizeGradient) {
  59649. other._currentSizeGradient = this._currentSizeGradient;
  59650. other._currentSize1 = this._currentSize1;
  59651. other._currentSize2 = this._currentSize2;
  59652. }
  59653. if (this._currentAngularSpeedGradient) {
  59654. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  59655. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  59656. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  59657. }
  59658. if (this._currentVelocityGradient) {
  59659. other._currentVelocityGradient = this._currentVelocityGradient;
  59660. other._currentVelocity1 = this._currentVelocity1;
  59661. other._currentVelocity2 = this._currentVelocity2;
  59662. }
  59663. if (this._currentLimitVelocityGradient) {
  59664. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  59665. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  59666. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  59667. }
  59668. if (this._currentDragGradient) {
  59669. other._currentDragGradient = this._currentDragGradient;
  59670. other._currentDrag1 = this._currentDrag1;
  59671. other._currentDrag2 = this._currentDrag2;
  59672. }
  59673. if (this.particleSystem.isAnimationSheetEnabled) {
  59674. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  59675. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  59676. }
  59677. if (this.particleSystem.useRampGradients) {
  59678. other.remapData.copyFrom(this.remapData);
  59679. }
  59680. if (this._randomNoiseCoordinates1) {
  59681. if (other._randomNoiseCoordinates1) {
  59682. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  59683. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  59684. }
  59685. else {
  59686. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  59687. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  59688. }
  59689. }
  59690. };
  59691. Particle._Count = 0;
  59692. return Particle;
  59693. }());
  59694. BABYLON.Particle = Particle;
  59695. })(BABYLON || (BABYLON = {}));
  59696. //# sourceMappingURL=babylon.particle.js.map
  59697. var BABYLON;
  59698. (function (BABYLON) {
  59699. /**
  59700. * This represents the base class for particle system in Babylon.
  59701. * 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.
  59702. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59703. * @example https://doc.babylonjs.com/babylon101/particles
  59704. */
  59705. var BaseParticleSystem = /** @class */ (function () {
  59706. /**
  59707. * Instantiates a particle system.
  59708. * 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.
  59709. * @param name The name of the particle system
  59710. */
  59711. function BaseParticleSystem(name) {
  59712. /**
  59713. * List of animations used by the particle system.
  59714. */
  59715. this.animations = [];
  59716. /**
  59717. * The rendering group used by the Particle system to chose when to render.
  59718. */
  59719. this.renderingGroupId = 0;
  59720. /**
  59721. * The emitter represents the Mesh or position we are attaching the particle system to.
  59722. */
  59723. this.emitter = null;
  59724. /**
  59725. * The maximum number of particles to emit per frame
  59726. */
  59727. this.emitRate = 10;
  59728. /**
  59729. * If you want to launch only a few particles at once, that can be done, as well.
  59730. */
  59731. this.manualEmitCount = -1;
  59732. /**
  59733. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59734. */
  59735. this.updateSpeed = 0.01;
  59736. /**
  59737. * The amount of time the particle system is running (depends of the overall update speed).
  59738. */
  59739. this.targetStopDuration = 0;
  59740. /**
  59741. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59742. */
  59743. this.disposeOnStop = false;
  59744. /**
  59745. * Minimum power of emitting particles.
  59746. */
  59747. this.minEmitPower = 1;
  59748. /**
  59749. * Maximum power of emitting particles.
  59750. */
  59751. this.maxEmitPower = 1;
  59752. /**
  59753. * Minimum life time of emitting particles.
  59754. */
  59755. this.minLifeTime = 1;
  59756. /**
  59757. * Maximum life time of emitting particles.
  59758. */
  59759. this.maxLifeTime = 1;
  59760. /**
  59761. * Minimum Size of emitting particles.
  59762. */
  59763. this.minSize = 1;
  59764. /**
  59765. * Maximum Size of emitting particles.
  59766. */
  59767. this.maxSize = 1;
  59768. /**
  59769. * Minimum scale of emitting particles on X axis.
  59770. */
  59771. this.minScaleX = 1;
  59772. /**
  59773. * Maximum scale of emitting particles on X axis.
  59774. */
  59775. this.maxScaleX = 1;
  59776. /**
  59777. * Minimum scale of emitting particles on Y axis.
  59778. */
  59779. this.minScaleY = 1;
  59780. /**
  59781. * Maximum scale of emitting particles on Y axis.
  59782. */
  59783. this.maxScaleY = 1;
  59784. /**
  59785. * Gets or sets the minimal initial rotation in radians.
  59786. */
  59787. this.minInitialRotation = 0;
  59788. /**
  59789. * Gets or sets the maximal initial rotation in radians.
  59790. */
  59791. this.maxInitialRotation = 0;
  59792. /**
  59793. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59794. */
  59795. this.minAngularSpeed = 0;
  59796. /**
  59797. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59798. */
  59799. this.maxAngularSpeed = 0;
  59800. /**
  59801. * The layer mask we are rendering the particles through.
  59802. */
  59803. this.layerMask = 0x0FFFFFFF;
  59804. /**
  59805. * This can help using your own shader to render the particle system.
  59806. * The according effect will be created
  59807. */
  59808. this.customShader = null;
  59809. /**
  59810. * By default particle system starts as soon as they are created. This prevents the
  59811. * automatic start to happen and let you decide when to start emitting particles.
  59812. */
  59813. this.preventAutoStart = false;
  59814. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59815. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59816. /**
  59817. * Callback triggered when the particle animation is ending.
  59818. */
  59819. this.onAnimationEnd = null;
  59820. /**
  59821. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59822. */
  59823. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59824. /**
  59825. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59826. * to override the particles.
  59827. */
  59828. this.forceDepthWrite = false;
  59829. /** 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 */
  59830. this.preWarmCycles = 0;
  59831. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59832. this.preWarmStepOffset = 1;
  59833. /**
  59834. * 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)
  59835. */
  59836. this.spriteCellChangeSpeed = 1;
  59837. /**
  59838. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59839. */
  59840. this.startSpriteCellID = 0;
  59841. /**
  59842. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59843. */
  59844. this.endSpriteCellID = 0;
  59845. /**
  59846. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59847. */
  59848. this.spriteCellWidth = 0;
  59849. /**
  59850. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59851. */
  59852. this.spriteCellHeight = 0;
  59853. /**
  59854. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  59855. */
  59856. this.spriteRandomStartCell = false;
  59857. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59858. this.translationPivot = new BABYLON.Vector2(0, 0);
  59859. /**
  59860. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  59861. */
  59862. this.beginAnimationOnStart = false;
  59863. /**
  59864. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  59865. */
  59866. this.beginAnimationFrom = 0;
  59867. /**
  59868. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  59869. */
  59870. this.beginAnimationTo = 60;
  59871. /**
  59872. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  59873. */
  59874. this.beginAnimationLoop = false;
  59875. /**
  59876. * You can use gravity if you want to give an orientation to your particles.
  59877. */
  59878. this.gravity = BABYLON.Vector3.Zero();
  59879. this._colorGradients = null;
  59880. this._sizeGradients = null;
  59881. this._lifeTimeGradients = null;
  59882. this._angularSpeedGradients = null;
  59883. this._velocityGradients = null;
  59884. this._limitVelocityGradients = null;
  59885. this._dragGradients = null;
  59886. this._emitRateGradients = null;
  59887. this._startSizeGradients = null;
  59888. this._rampGradients = null;
  59889. this._colorRemapGradients = null;
  59890. this._alphaRemapGradients = null;
  59891. /**
  59892. * Defines the delay in milliseconds before starting the system (0 by default)
  59893. */
  59894. this.startDelay = 0;
  59895. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  59896. this.limitVelocityDamping = 0.4;
  59897. /**
  59898. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59899. */
  59900. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59901. /**
  59902. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59903. */
  59904. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59905. /**
  59906. * Color the particle will have at the end of its lifetime
  59907. */
  59908. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  59909. /**
  59910. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  59911. */
  59912. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59913. /** @hidden */
  59914. this._isSubEmitter = false;
  59915. /**
  59916. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59917. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  59918. */
  59919. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  59920. this._isBillboardBased = true;
  59921. /**
  59922. * Local cache of defines for image processing.
  59923. */
  59924. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  59925. this.id = name;
  59926. this.name = name;
  59927. }
  59928. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  59929. /**
  59930. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  59931. */
  59932. get: function () {
  59933. return this._isAnimationSheetEnabled;
  59934. },
  59935. set: function (value) {
  59936. if (this._isAnimationSheetEnabled == value) {
  59937. return;
  59938. }
  59939. this._isAnimationSheetEnabled = value;
  59940. this._reset();
  59941. },
  59942. enumerable: true,
  59943. configurable: true
  59944. });
  59945. /**
  59946. * Get hosting scene
  59947. * @returns the scene
  59948. */
  59949. BaseParticleSystem.prototype.getScene = function () {
  59950. return this._scene;
  59951. };
  59952. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  59953. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  59954. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  59955. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  59956. };
  59957. /**
  59958. * Gets the current list of drag gradients.
  59959. * You must use addDragGradient and removeDragGradient to udpate this list
  59960. * @returns the list of drag gradients
  59961. */
  59962. BaseParticleSystem.prototype.getDragGradients = function () {
  59963. return this._dragGradients;
  59964. };
  59965. /**
  59966. * Gets the current list of limit velocity gradients.
  59967. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  59968. * @returns the list of limit velocity gradients
  59969. */
  59970. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  59971. return this._limitVelocityGradients;
  59972. };
  59973. /**
  59974. * Gets the current list of color gradients.
  59975. * You must use addColorGradient and removeColorGradient to udpate this list
  59976. * @returns the list of color gradients
  59977. */
  59978. BaseParticleSystem.prototype.getColorGradients = function () {
  59979. return this._colorGradients;
  59980. };
  59981. /**
  59982. * Gets the current list of size gradients.
  59983. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59984. * @returns the list of size gradients
  59985. */
  59986. BaseParticleSystem.prototype.getSizeGradients = function () {
  59987. return this._sizeGradients;
  59988. };
  59989. /**
  59990. * Gets the current list of color remap gradients.
  59991. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  59992. * @returns the list of color remap gradients
  59993. */
  59994. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  59995. return this._colorRemapGradients;
  59996. };
  59997. /**
  59998. * Gets the current list of alpha remap gradients.
  59999. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60000. * @returns the list of alpha remap gradients
  60001. */
  60002. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60003. return this._alphaRemapGradients;
  60004. };
  60005. /**
  60006. * Gets the current list of life time gradients.
  60007. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60008. * @returns the list of life time gradients
  60009. */
  60010. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60011. return this._lifeTimeGradients;
  60012. };
  60013. /**
  60014. * Gets the current list of angular speed gradients.
  60015. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60016. * @returns the list of angular speed gradients
  60017. */
  60018. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60019. return this._angularSpeedGradients;
  60020. };
  60021. /**
  60022. * Gets the current list of velocity gradients.
  60023. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60024. * @returns the list of velocity gradients
  60025. */
  60026. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60027. return this._velocityGradients;
  60028. };
  60029. /**
  60030. * Gets the current list of start size gradients.
  60031. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60032. * @returns the list of start size gradients
  60033. */
  60034. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60035. return this._startSizeGradients;
  60036. };
  60037. /**
  60038. * Gets the current list of emit rate gradients.
  60039. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60040. * @returns the list of emit rate gradients
  60041. */
  60042. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60043. return this._emitRateGradients;
  60044. };
  60045. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60046. /**
  60047. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60048. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60049. */
  60050. get: function () {
  60051. if (this.particleEmitterType.direction1) {
  60052. return this.particleEmitterType.direction1;
  60053. }
  60054. return BABYLON.Vector3.Zero();
  60055. },
  60056. set: function (value) {
  60057. if (this.particleEmitterType.direction1) {
  60058. this.particleEmitterType.direction1 = value;
  60059. }
  60060. },
  60061. enumerable: true,
  60062. configurable: true
  60063. });
  60064. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60065. /**
  60066. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60067. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60068. */
  60069. get: function () {
  60070. if (this.particleEmitterType.direction2) {
  60071. return this.particleEmitterType.direction2;
  60072. }
  60073. return BABYLON.Vector3.Zero();
  60074. },
  60075. set: function (value) {
  60076. if (this.particleEmitterType.direction2) {
  60077. this.particleEmitterType.direction2 = value;
  60078. }
  60079. },
  60080. enumerable: true,
  60081. configurable: true
  60082. });
  60083. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60084. /**
  60085. * 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.
  60086. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60087. */
  60088. get: function () {
  60089. if (this.particleEmitterType.minEmitBox) {
  60090. return this.particleEmitterType.minEmitBox;
  60091. }
  60092. return BABYLON.Vector3.Zero();
  60093. },
  60094. set: function (value) {
  60095. if (this.particleEmitterType.minEmitBox) {
  60096. this.particleEmitterType.minEmitBox = value;
  60097. }
  60098. },
  60099. enumerable: true,
  60100. configurable: true
  60101. });
  60102. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60103. /**
  60104. * 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.
  60105. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60106. */
  60107. get: function () {
  60108. if (this.particleEmitterType.maxEmitBox) {
  60109. return this.particleEmitterType.maxEmitBox;
  60110. }
  60111. return BABYLON.Vector3.Zero();
  60112. },
  60113. set: function (value) {
  60114. if (this.particleEmitterType.maxEmitBox) {
  60115. this.particleEmitterType.maxEmitBox = value;
  60116. }
  60117. },
  60118. enumerable: true,
  60119. configurable: true
  60120. });
  60121. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60122. /**
  60123. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60124. */
  60125. get: function () {
  60126. return this._isBillboardBased;
  60127. },
  60128. set: function (value) {
  60129. if (this._isBillboardBased === value) {
  60130. return;
  60131. }
  60132. this._isBillboardBased = value;
  60133. this._reset();
  60134. },
  60135. enumerable: true,
  60136. configurable: true
  60137. });
  60138. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60139. /**
  60140. * Gets the image processing configuration used either in this material.
  60141. */
  60142. get: function () {
  60143. return this._imageProcessingConfiguration;
  60144. },
  60145. /**
  60146. * Sets the Default image processing configuration used either in the this material.
  60147. *
  60148. * If sets to null, the scene one is in use.
  60149. */
  60150. set: function (value) {
  60151. this._attachImageProcessingConfiguration(value);
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. /**
  60157. * Attaches a new image processing configuration to the Standard Material.
  60158. * @param configuration
  60159. */
  60160. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60161. if (configuration === this._imageProcessingConfiguration) {
  60162. return;
  60163. }
  60164. // Pick the scene configuration if needed.
  60165. if (!configuration) {
  60166. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60167. }
  60168. else {
  60169. this._imageProcessingConfiguration = configuration;
  60170. }
  60171. };
  60172. /** @hidden */
  60173. BaseParticleSystem.prototype._reset = function () {
  60174. };
  60175. /** @hidden */
  60176. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60177. if (!gradients) {
  60178. return this;
  60179. }
  60180. var index = 0;
  60181. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60182. var valueGradient = gradients_1[_i];
  60183. if (valueGradient.gradient === gradient) {
  60184. gradients.splice(index, 1);
  60185. break;
  60186. }
  60187. index++;
  60188. }
  60189. if (texture) {
  60190. texture.dispose();
  60191. }
  60192. return this;
  60193. };
  60194. /**
  60195. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60196. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60197. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60198. * @returns the emitter
  60199. */
  60200. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60201. var particleEmitter = new BABYLON.PointParticleEmitter();
  60202. particleEmitter.direction1 = direction1;
  60203. particleEmitter.direction2 = direction2;
  60204. this.particleEmitterType = particleEmitter;
  60205. return particleEmitter;
  60206. };
  60207. /**
  60208. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60209. * @param radius The radius of the hemisphere to emit from
  60210. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60211. * @returns the emitter
  60212. */
  60213. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60214. if (radius === void 0) { radius = 1; }
  60215. if (radiusRange === void 0) { radiusRange = 1; }
  60216. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60217. this.particleEmitterType = particleEmitter;
  60218. return particleEmitter;
  60219. };
  60220. /**
  60221. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60222. * @param radius The radius of the sphere to emit from
  60223. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60224. * @returns the emitter
  60225. */
  60226. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60227. if (radius === void 0) { radius = 1; }
  60228. if (radiusRange === void 0) { radiusRange = 1; }
  60229. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60230. this.particleEmitterType = particleEmitter;
  60231. return particleEmitter;
  60232. };
  60233. /**
  60234. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60235. * @param radius The radius of the sphere to emit from
  60236. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60237. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60238. * @returns the emitter
  60239. */
  60240. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60241. if (radius === void 0) { radius = 1; }
  60242. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60243. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60244. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60245. this.particleEmitterType = particleEmitter;
  60246. return particleEmitter;
  60247. };
  60248. /**
  60249. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60250. * @param radius The radius of the emission cylinder
  60251. * @param height The height of the emission cylinder
  60252. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60253. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60254. * @returns the emitter
  60255. */
  60256. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60257. if (radius === void 0) { radius = 1; }
  60258. if (height === void 0) { height = 1; }
  60259. if (radiusRange === void 0) { radiusRange = 1; }
  60260. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60261. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60262. this.particleEmitterType = particleEmitter;
  60263. return particleEmitter;
  60264. };
  60265. /**
  60266. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60267. * @param radius The radius of the cylinder to emit from
  60268. * @param height The height of the emission cylinder
  60269. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60270. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60271. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60272. * @returns the emitter
  60273. */
  60274. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60275. if (radius === void 0) { radius = 1; }
  60276. if (height === void 0) { height = 1; }
  60277. if (radiusRange === void 0) { radiusRange = 1; }
  60278. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60279. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60280. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60281. this.particleEmitterType = particleEmitter;
  60282. return particleEmitter;
  60283. };
  60284. /**
  60285. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60286. * @param radius The radius of the cone to emit from
  60287. * @param angle The base angle of the cone
  60288. * @returns the emitter
  60289. */
  60290. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60291. if (radius === void 0) { radius = 1; }
  60292. if (angle === void 0) { angle = Math.PI / 4; }
  60293. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60294. this.particleEmitterType = particleEmitter;
  60295. return particleEmitter;
  60296. };
  60297. /**
  60298. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60299. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60300. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60301. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60302. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60303. * @returns the emitter
  60304. */
  60305. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60306. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60307. this.particleEmitterType = particleEmitter;
  60308. this.direction1 = direction1;
  60309. this.direction2 = direction2;
  60310. this.minEmitBox = minEmitBox;
  60311. this.maxEmitBox = maxEmitBox;
  60312. return particleEmitter;
  60313. };
  60314. /**
  60315. * Source color is added to the destination color without alpha affecting the result
  60316. */
  60317. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60318. /**
  60319. * Blend current color and particle color using particle’s alpha
  60320. */
  60321. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60322. /**
  60323. * Add current color and particle color multiplied by particle’s alpha
  60324. */
  60325. BaseParticleSystem.BLENDMODE_ADD = 2;
  60326. /**
  60327. * Multiply current color with particle color
  60328. */
  60329. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60330. /**
  60331. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60332. */
  60333. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60334. return BaseParticleSystem;
  60335. }());
  60336. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60337. })(BABYLON || (BABYLON = {}));
  60338. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  60339. var BABYLON;
  60340. (function (BABYLON) {
  60341. /**
  60342. * This represents a particle system in Babylon.
  60343. * 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.
  60344. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60345. * @example https://doc.babylonjs.com/babylon101/particles
  60346. */
  60347. var ParticleSystem = /** @class */ (function (_super) {
  60348. __extends(ParticleSystem, _super);
  60349. /**
  60350. * Instantiates a particle system.
  60351. * 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.
  60352. * @param name The name of the particle system
  60353. * @param capacity The max number of particles alive at the same time
  60354. * @param scene The scene the particle system belongs to
  60355. * @param customEffect a custom effect used to change the way particles are rendered by default
  60356. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60357. * @param epsilon Offset used to render the particles
  60358. */
  60359. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60360. if (customEffect === void 0) { customEffect = null; }
  60361. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60362. if (epsilon === void 0) { epsilon = 0.01; }
  60363. var _this = _super.call(this, name) || this;
  60364. /**
  60365. * @hidden
  60366. */
  60367. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60368. /**
  60369. * An event triggered when the system is disposed
  60370. */
  60371. _this.onDisposeObservable = new BABYLON.Observable();
  60372. _this._particles = new Array();
  60373. _this._stockParticles = new Array();
  60374. _this._newPartsExcess = 0;
  60375. _this._vertexBuffers = {};
  60376. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60377. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60378. _this._scaledDirection = BABYLON.Vector3.Zero();
  60379. _this._scaledGravity = BABYLON.Vector3.Zero();
  60380. _this._currentRenderId = -1;
  60381. _this._useInstancing = false;
  60382. _this._started = false;
  60383. _this._stopped = false;
  60384. _this._actualFrame = 0;
  60385. /** @hidden */
  60386. _this._currentEmitRate1 = 0;
  60387. /** @hidden */
  60388. _this._currentEmitRate2 = 0;
  60389. /** @hidden */
  60390. _this._currentStartSize1 = 0;
  60391. /** @hidden */
  60392. _this._currentStartSize2 = 0;
  60393. _this._rawTextureWidth = 256;
  60394. _this._useRampGradients = false;
  60395. /**
  60396. * @hidden
  60397. * If the particle systems emitter should be disposed when the particle system is disposed
  60398. */
  60399. _this._disposeEmitterOnDispose = false;
  60400. // start of sub system methods
  60401. /**
  60402. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60403. * Its lifetime will start back at 0.
  60404. */
  60405. _this.recycleParticle = function (particle) {
  60406. // move particle from activeParticle list to stock particles
  60407. var lastParticle = _this._particles.pop();
  60408. if (lastParticle !== particle) {
  60409. lastParticle.copyTo(particle);
  60410. }
  60411. _this._stockParticles.push(lastParticle);
  60412. };
  60413. _this._createParticle = function () {
  60414. var particle;
  60415. if (_this._stockParticles.length !== 0) {
  60416. particle = _this._stockParticles.pop();
  60417. particle._reset();
  60418. }
  60419. else {
  60420. particle = new BABYLON.Particle(_this);
  60421. }
  60422. // Attach emitters
  60423. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60424. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60425. particle._attachedSubEmitters = [];
  60426. subEmitters.forEach(function (subEmitter) {
  60427. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60428. var newEmitter = subEmitter.clone();
  60429. particle._attachedSubEmitters.push(newEmitter);
  60430. newEmitter.particleSystem.start();
  60431. }
  60432. });
  60433. }
  60434. return particle;
  60435. };
  60436. _this._emitFromParticle = function (particle) {
  60437. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60438. return;
  60439. }
  60440. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60441. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60442. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60443. var subSystem = subEmitter.clone();
  60444. particle._inheritParticleInfoToSubEmitter(subSystem);
  60445. subSystem.particleSystem._rootParticleSystem = _this;
  60446. _this.activeSubSystems.push(subSystem.particleSystem);
  60447. subSystem.particleSystem.start();
  60448. }
  60449. });
  60450. };
  60451. _this._capacity = capacity;
  60452. _this._epsilon = epsilon;
  60453. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60454. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60455. // Setup the default processing configuration to the scene.
  60456. _this._attachImageProcessingConfiguration(null);
  60457. _this._customEffect = customEffect;
  60458. _this._scene.particleSystems.push(_this);
  60459. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60460. _this._createIndexBuffer();
  60461. _this._createVertexBuffers();
  60462. // Default emitter type
  60463. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60464. // Update
  60465. _this.updateFunction = function (particles) {
  60466. var noiseTextureSize = null;
  60467. var noiseTextureData = null;
  60468. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60469. noiseTextureSize = _this.noiseTexture.getSize();
  60470. noiseTextureData = (_this.noiseTexture.getContent());
  60471. }
  60472. var _loop_1 = function () {
  60473. particle = particles[index];
  60474. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60475. var previousAge = particle.age;
  60476. particle.age += scaledUpdateSpeed;
  60477. // Evaluate step to death
  60478. if (particle.age > particle.lifeTime) {
  60479. var diff = particle.age - previousAge;
  60480. var oldDiff = particle.lifeTime - previousAge;
  60481. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60482. particle.age = particle.lifeTime;
  60483. }
  60484. var ratio = particle.age / particle.lifeTime;
  60485. // Color
  60486. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60487. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60488. if (currentGradient !== particle._currentColorGradient) {
  60489. particle._currentColor1.copyFrom(particle._currentColor2);
  60490. nextGradient.getColorToRef(particle._currentColor2);
  60491. particle._currentColorGradient = currentGradient;
  60492. }
  60493. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60494. });
  60495. }
  60496. else {
  60497. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60498. particle.color.addInPlace(_this._scaledColorStep);
  60499. if (particle.color.a < 0) {
  60500. particle.color.a = 0;
  60501. }
  60502. }
  60503. // Angular speed
  60504. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60505. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60506. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60507. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60508. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60509. particle._currentAngularSpeedGradient = currentGradient;
  60510. }
  60511. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60512. });
  60513. }
  60514. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60515. // Direction
  60516. var directionScale = scaledUpdateSpeed;
  60517. /// Velocity
  60518. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60519. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60520. if (currentGradient !== particle._currentVelocityGradient) {
  60521. particle._currentVelocity1 = particle._currentVelocity2;
  60522. particle._currentVelocity2 = nextGradient.getFactor();
  60523. particle._currentVelocityGradient = currentGradient;
  60524. }
  60525. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60526. });
  60527. }
  60528. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60529. /// Limit velocity
  60530. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60531. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60532. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60533. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60534. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60535. particle._currentLimitVelocityGradient = currentGradient;
  60536. }
  60537. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60538. var currentVelocity = particle.direction.length();
  60539. if (currentVelocity > limitVelocity) {
  60540. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  60541. }
  60542. });
  60543. }
  60544. /// Drag
  60545. if (_this._dragGradients && _this._dragGradients.length > 0) {
  60546. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  60547. if (currentGradient !== particle._currentDragGradient) {
  60548. particle._currentDrag1 = particle._currentDrag2;
  60549. particle._currentDrag2 = nextGradient.getFactor();
  60550. particle._currentDragGradient = currentGradient;
  60551. }
  60552. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  60553. _this._scaledDirection.scaleInPlace(1.0 - drag);
  60554. });
  60555. }
  60556. particle.position.addInPlace(_this._scaledDirection);
  60557. // Noise
  60558. if (noiseTextureData && noiseTextureSize) {
  60559. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60560. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60561. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60562. var force = BABYLON.Tmp.Vector3[0];
  60563. var scaledForce = BABYLON.Tmp.Vector3[1];
  60564. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  60565. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  60566. particle.direction.addInPlace(scaledForce);
  60567. }
  60568. // Gravity
  60569. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  60570. particle.direction.addInPlace(_this._scaledGravity);
  60571. // Size
  60572. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  60573. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  60574. if (currentGradient !== particle._currentSizeGradient) {
  60575. particle._currentSize1 = particle._currentSize2;
  60576. particle._currentSize2 = nextGradient.getFactor();
  60577. particle._currentSizeGradient = currentGradient;
  60578. }
  60579. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  60580. });
  60581. }
  60582. // Remap data
  60583. if (_this._useRampGradients) {
  60584. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  60585. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  60586. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60587. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60588. particle.remapData.x = min;
  60589. particle.remapData.y = max - min;
  60590. });
  60591. }
  60592. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  60593. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  60594. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60595. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60596. particle.remapData.z = min;
  60597. particle.remapData.w = max - min;
  60598. });
  60599. }
  60600. }
  60601. if (_this._isAnimationSheetEnabled) {
  60602. particle.updateCellIndex();
  60603. }
  60604. // Update the position of the attached sub-emitters to match their attached particle
  60605. particle._inheritParticleInfoToSubEmitters();
  60606. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  60607. _this._emitFromParticle(particle);
  60608. if (particle._attachedSubEmitters) {
  60609. particle._attachedSubEmitters.forEach(function (subEmitter) {
  60610. subEmitter.particleSystem.disposeOnStop = true;
  60611. subEmitter.particleSystem.stop();
  60612. });
  60613. particle._attachedSubEmitters = null;
  60614. }
  60615. _this.recycleParticle(particle);
  60616. index--;
  60617. return "continue";
  60618. }
  60619. };
  60620. var particle;
  60621. for (var index = 0; index < particles.length; index++) {
  60622. _loop_1();
  60623. }
  60624. };
  60625. return _this;
  60626. }
  60627. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  60628. /**
  60629. * Sets a callback that will be triggered when the system is disposed
  60630. */
  60631. set: function (callback) {
  60632. if (this._onDisposeObserver) {
  60633. this.onDisposeObservable.remove(this._onDisposeObserver);
  60634. }
  60635. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  60636. },
  60637. enumerable: true,
  60638. configurable: true
  60639. });
  60640. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  60641. /** Gets or sets a boolean indicating that ramp gradients must be used
  60642. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  60643. */
  60644. get: function () {
  60645. return this._useRampGradients;
  60646. },
  60647. set: function (value) {
  60648. if (this._useRampGradients === value) {
  60649. return;
  60650. }
  60651. this._useRampGradients = value;
  60652. this._resetEffect();
  60653. },
  60654. enumerable: true,
  60655. configurable: true
  60656. });
  60657. Object.defineProperty(ParticleSystem.prototype, "particles", {
  60658. //end of Sub-emitter
  60659. /**
  60660. * Gets the current list of active particles
  60661. */
  60662. get: function () {
  60663. return this._particles;
  60664. },
  60665. enumerable: true,
  60666. configurable: true
  60667. });
  60668. /**
  60669. * Returns the string "ParticleSystem"
  60670. * @returns a string containing the class name
  60671. */
  60672. ParticleSystem.prototype.getClassName = function () {
  60673. return "ParticleSystem";
  60674. };
  60675. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  60676. var newGradient = new BABYLON.FactorGradient();
  60677. newGradient.gradient = gradient;
  60678. newGradient.factor1 = factor;
  60679. newGradient.factor2 = factor2;
  60680. factorGradients.push(newGradient);
  60681. factorGradients.sort(function (a, b) {
  60682. if (a.gradient < b.gradient) {
  60683. return -1;
  60684. }
  60685. else if (a.gradient > b.gradient) {
  60686. return 1;
  60687. }
  60688. return 0;
  60689. });
  60690. };
  60691. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  60692. if (!factorGradients) {
  60693. return;
  60694. }
  60695. var index = 0;
  60696. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  60697. var factorGradient = factorGradients_1[_i];
  60698. if (factorGradient.gradient === gradient) {
  60699. factorGradients.splice(index, 1);
  60700. break;
  60701. }
  60702. index++;
  60703. }
  60704. };
  60705. /**
  60706. * Adds a new life time gradient
  60707. * @param gradient defines the gradient to use (between 0 and 1)
  60708. * @param factor defines the life time factor to affect to the specified gradient
  60709. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60710. * @returns the current particle system
  60711. */
  60712. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  60713. if (!this._lifeTimeGradients) {
  60714. this._lifeTimeGradients = [];
  60715. }
  60716. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  60717. return this;
  60718. };
  60719. /**
  60720. * Remove a specific life time gradient
  60721. * @param gradient defines the gradient to remove
  60722. * @returns the current particle system
  60723. */
  60724. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  60725. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  60726. return this;
  60727. };
  60728. /**
  60729. * Adds a new size gradient
  60730. * @param gradient defines the gradient to use (between 0 and 1)
  60731. * @param factor defines the size factor to affect to the specified gradient
  60732. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60733. * @returns the current particle system
  60734. */
  60735. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  60736. if (!this._sizeGradients) {
  60737. this._sizeGradients = [];
  60738. }
  60739. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  60740. return this;
  60741. };
  60742. /**
  60743. * Remove a specific size gradient
  60744. * @param gradient defines the gradient to remove
  60745. * @returns the current particle system
  60746. */
  60747. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60748. this._removeFactorGradient(this._sizeGradients, gradient);
  60749. return this;
  60750. };
  60751. /**
  60752. * Adds a new color remap gradient
  60753. * @param gradient defines the gradient to use (between 0 and 1)
  60754. * @param min defines the color remap minimal range
  60755. * @param max defines the color remap maximal range
  60756. * @returns the current particle system
  60757. */
  60758. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  60759. if (!this._colorRemapGradients) {
  60760. this._colorRemapGradients = [];
  60761. }
  60762. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  60763. return this;
  60764. };
  60765. /**
  60766. * Remove a specific color remap gradient
  60767. * @param gradient defines the gradient to remove
  60768. * @returns the current particle system
  60769. */
  60770. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  60771. this._removeFactorGradient(this._colorRemapGradients, gradient);
  60772. return this;
  60773. };
  60774. /**
  60775. * Adds a new alpha remap gradient
  60776. * @param gradient defines the gradient to use (between 0 and 1)
  60777. * @param min defines the alpha remap minimal range
  60778. * @param max defines the alpha remap maximal range
  60779. * @returns the current particle system
  60780. */
  60781. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  60782. if (!this._alphaRemapGradients) {
  60783. this._alphaRemapGradients = [];
  60784. }
  60785. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  60786. return this;
  60787. };
  60788. /**
  60789. * Remove a specific alpha remap gradient
  60790. * @param gradient defines the gradient to remove
  60791. * @returns the current particle system
  60792. */
  60793. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  60794. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  60795. return this;
  60796. };
  60797. /**
  60798. * Adds a new angular speed gradient
  60799. * @param gradient defines the gradient to use (between 0 and 1)
  60800. * @param factor defines the angular speed to affect to the specified gradient
  60801. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60802. * @returns the current particle system
  60803. */
  60804. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  60805. if (!this._angularSpeedGradients) {
  60806. this._angularSpeedGradients = [];
  60807. }
  60808. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  60809. return this;
  60810. };
  60811. /**
  60812. * Remove a specific angular speed gradient
  60813. * @param gradient defines the gradient to remove
  60814. * @returns the current particle system
  60815. */
  60816. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60817. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  60818. return this;
  60819. };
  60820. /**
  60821. * Adds a new velocity gradient
  60822. * @param gradient defines the gradient to use (between 0 and 1)
  60823. * @param factor defines the velocity to affect to the specified gradient
  60824. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60825. * @returns the current particle system
  60826. */
  60827. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  60828. if (!this._velocityGradients) {
  60829. this._velocityGradients = [];
  60830. }
  60831. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  60832. return this;
  60833. };
  60834. /**
  60835. * Remove a specific velocity gradient
  60836. * @param gradient defines the gradient to remove
  60837. * @returns the current particle system
  60838. */
  60839. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60840. this._removeFactorGradient(this._velocityGradients, gradient);
  60841. return this;
  60842. };
  60843. /**
  60844. * Adds a new limit velocity gradient
  60845. * @param gradient defines the gradient to use (between 0 and 1)
  60846. * @param factor defines the limit velocity value to affect to the specified gradient
  60847. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60848. * @returns the current particle system
  60849. */
  60850. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  60851. if (!this._limitVelocityGradients) {
  60852. this._limitVelocityGradients = [];
  60853. }
  60854. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  60855. return this;
  60856. };
  60857. /**
  60858. * Remove a specific limit velocity gradient
  60859. * @param gradient defines the gradient to remove
  60860. * @returns the current particle system
  60861. */
  60862. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60863. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  60864. return this;
  60865. };
  60866. /**
  60867. * Adds a new drag gradient
  60868. * @param gradient defines the gradient to use (between 0 and 1)
  60869. * @param factor defines the drag value to affect to the specified gradient
  60870. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60871. * @returns the current particle system
  60872. */
  60873. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  60874. if (!this._dragGradients) {
  60875. this._dragGradients = [];
  60876. }
  60877. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  60878. return this;
  60879. };
  60880. /**
  60881. * Remove a specific drag gradient
  60882. * @param gradient defines the gradient to remove
  60883. * @returns the current particle system
  60884. */
  60885. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  60886. this._removeFactorGradient(this._dragGradients, gradient);
  60887. return this;
  60888. };
  60889. /**
  60890. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  60891. * @param gradient defines the gradient to use (between 0 and 1)
  60892. * @param factor defines the emit rate value to affect to the specified gradient
  60893. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60894. * @returns the current particle system
  60895. */
  60896. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  60897. if (!this._emitRateGradients) {
  60898. this._emitRateGradients = [];
  60899. }
  60900. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  60901. return this;
  60902. };
  60903. /**
  60904. * Remove a specific emit rate gradient
  60905. * @param gradient defines the gradient to remove
  60906. * @returns the current particle system
  60907. */
  60908. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  60909. this._removeFactorGradient(this._emitRateGradients, gradient);
  60910. return this;
  60911. };
  60912. /**
  60913. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  60914. * @param gradient defines the gradient to use (between 0 and 1)
  60915. * @param factor defines the start size value to affect to the specified gradient
  60916. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60917. * @returns the current particle system
  60918. */
  60919. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  60920. if (!this._startSizeGradients) {
  60921. this._startSizeGradients = [];
  60922. }
  60923. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  60924. return this;
  60925. };
  60926. /**
  60927. * Remove a specific start size gradient
  60928. * @param gradient defines the gradient to remove
  60929. * @returns the current particle system
  60930. */
  60931. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  60932. this._removeFactorGradient(this._emitRateGradients, gradient);
  60933. return this;
  60934. };
  60935. ParticleSystem.prototype._createRampGradientTexture = function () {
  60936. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  60937. return;
  60938. }
  60939. var data = new Uint8Array(this._rawTextureWidth * 4);
  60940. var tmpColor = BABYLON.Tmp.Color3[0];
  60941. for (var x = 0; x < this._rawTextureWidth; x++) {
  60942. var ratio = x / this._rawTextureWidth;
  60943. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  60944. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  60945. data[x * 4] = tmpColor.r * 255;
  60946. data[x * 4 + 1] = tmpColor.g * 255;
  60947. data[x * 4 + 2] = tmpColor.b * 255;
  60948. data[x * 4 + 3] = 255;
  60949. });
  60950. }
  60951. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60952. };
  60953. /**
  60954. * Gets the current list of ramp gradients.
  60955. * You must use addRampGradient and removeRampGradient to udpate this list
  60956. * @returns the list of ramp gradients
  60957. */
  60958. ParticleSystem.prototype.getRampGradients = function () {
  60959. return this._rampGradients;
  60960. };
  60961. /**
  60962. * Adds a new ramp gradient used to remap particle colors
  60963. * @param gradient defines the gradient to use (between 0 and 1)
  60964. * @param color defines the color to affect to the specified gradient
  60965. * @returns the current particle system
  60966. */
  60967. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  60968. if (!this._rampGradients) {
  60969. this._rampGradients = [];
  60970. }
  60971. var rampGradient = new BABYLON.Color3Gradient();
  60972. rampGradient.gradient = gradient;
  60973. rampGradient.color = color;
  60974. this._rampGradients.push(rampGradient);
  60975. this._rampGradients.sort(function (a, b) {
  60976. if (a.gradient < b.gradient) {
  60977. return -1;
  60978. }
  60979. else if (a.gradient > b.gradient) {
  60980. return 1;
  60981. }
  60982. return 0;
  60983. });
  60984. if (this._rampGradientsTexture) {
  60985. this._rampGradientsTexture.dispose();
  60986. this._rampGradientsTexture = null;
  60987. }
  60988. this._createRampGradientTexture();
  60989. return this;
  60990. };
  60991. /**
  60992. * Remove a specific ramp gradient
  60993. * @param gradient defines the gradient to remove
  60994. * @returns the current particle system
  60995. */
  60996. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  60997. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  60998. this._rampGradientsTexture = null;
  60999. if (this._rampGradients && this._rampGradients.length > 0) {
  61000. this._createRampGradientTexture();
  61001. }
  61002. return this;
  61003. };
  61004. /**
  61005. * Adds a new color gradient
  61006. * @param gradient defines the gradient to use (between 0 and 1)
  61007. * @param color1 defines the color to affect to the specified gradient
  61008. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61009. * @returns this particle system
  61010. */
  61011. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61012. if (!this._colorGradients) {
  61013. this._colorGradients = [];
  61014. }
  61015. var colorGradient = new BABYLON.ColorGradient();
  61016. colorGradient.gradient = gradient;
  61017. colorGradient.color1 = color1;
  61018. colorGradient.color2 = color2;
  61019. this._colorGradients.push(colorGradient);
  61020. this._colorGradients.sort(function (a, b) {
  61021. if (a.gradient < b.gradient) {
  61022. return -1;
  61023. }
  61024. else if (a.gradient > b.gradient) {
  61025. return 1;
  61026. }
  61027. return 0;
  61028. });
  61029. return this;
  61030. };
  61031. /**
  61032. * Remove a specific color gradient
  61033. * @param gradient defines the gradient to remove
  61034. * @returns this particle system
  61035. */
  61036. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61037. if (!this._colorGradients) {
  61038. return this;
  61039. }
  61040. var index = 0;
  61041. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61042. var colorGradient = _a[_i];
  61043. if (colorGradient.gradient === gradient) {
  61044. this._colorGradients.splice(index, 1);
  61045. break;
  61046. }
  61047. index++;
  61048. }
  61049. return this;
  61050. };
  61051. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61052. u = Math.abs(u) * 0.5 + 0.5;
  61053. v = Math.abs(v) * 0.5 + 0.5;
  61054. var wrappedU = ((u * width) % width) | 0;
  61055. var wrappedV = ((v * height) % height) | 0;
  61056. var position = (wrappedU + wrappedV * width) * 4;
  61057. return pixels[position] / 255;
  61058. };
  61059. ParticleSystem.prototype._reset = function () {
  61060. this._resetEffect();
  61061. };
  61062. ParticleSystem.prototype._resetEffect = function () {
  61063. if (this._vertexBuffer) {
  61064. this._vertexBuffer.dispose();
  61065. this._vertexBuffer = null;
  61066. }
  61067. if (this._spriteBuffer) {
  61068. this._spriteBuffer.dispose();
  61069. this._spriteBuffer = null;
  61070. }
  61071. this._createVertexBuffers();
  61072. };
  61073. ParticleSystem.prototype._createVertexBuffers = function () {
  61074. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61075. if (this._isAnimationSheetEnabled) {
  61076. this._vertexBufferSize += 1;
  61077. }
  61078. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61079. this._vertexBufferSize += 3;
  61080. }
  61081. if (this._useRampGradients) {
  61082. this._vertexBufferSize += 4;
  61083. }
  61084. var engine = this._scene.getEngine();
  61085. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61086. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61087. var dataOffset = 0;
  61088. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61090. dataOffset += 3;
  61091. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61092. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61093. dataOffset += 4;
  61094. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61095. this._vertexBuffers["angle"] = options;
  61096. dataOffset += 1;
  61097. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61098. this._vertexBuffers["size"] = size;
  61099. dataOffset += 2;
  61100. if (this._isAnimationSheetEnabled) {
  61101. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61102. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61103. dataOffset += 1;
  61104. }
  61105. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61106. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61107. this._vertexBuffers["direction"] = directionBuffer;
  61108. dataOffset += 3;
  61109. }
  61110. if (this._useRampGradients) {
  61111. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61112. this._vertexBuffers["remapData"] = rampDataBuffer;
  61113. dataOffset += 4;
  61114. }
  61115. var offsets;
  61116. if (this._useInstancing) {
  61117. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61118. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61119. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61120. }
  61121. else {
  61122. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61123. dataOffset += 2;
  61124. }
  61125. this._vertexBuffers["offset"] = offsets;
  61126. };
  61127. ParticleSystem.prototype._createIndexBuffer = function () {
  61128. if (this._useInstancing) {
  61129. return;
  61130. }
  61131. var indices = [];
  61132. var index = 0;
  61133. for (var count = 0; count < this._capacity; count++) {
  61134. indices.push(index);
  61135. indices.push(index + 1);
  61136. indices.push(index + 2);
  61137. indices.push(index);
  61138. indices.push(index + 2);
  61139. indices.push(index + 3);
  61140. index += 4;
  61141. }
  61142. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61143. };
  61144. /**
  61145. * Gets the maximum number of particles active at the same time.
  61146. * @returns The max number of active particles.
  61147. */
  61148. ParticleSystem.prototype.getCapacity = function () {
  61149. return this._capacity;
  61150. };
  61151. /**
  61152. * Gets whether there are still active particles in the system.
  61153. * @returns True if it is alive, otherwise false.
  61154. */
  61155. ParticleSystem.prototype.isAlive = function () {
  61156. return this._alive;
  61157. };
  61158. /**
  61159. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61160. * @returns True if it has been started, otherwise false.
  61161. */
  61162. ParticleSystem.prototype.isStarted = function () {
  61163. return this._started;
  61164. };
  61165. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61166. var _this = this;
  61167. this._subEmitters = new Array();
  61168. if (this.subEmitters) {
  61169. this.subEmitters.forEach(function (subEmitter) {
  61170. if (subEmitter instanceof ParticleSystem) {
  61171. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61172. }
  61173. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61174. _this._subEmitters.push([subEmitter]);
  61175. }
  61176. else if (subEmitter instanceof Array) {
  61177. _this._subEmitters.push(subEmitter);
  61178. }
  61179. });
  61180. }
  61181. };
  61182. /**
  61183. * Starts the particle system and begins to emit
  61184. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61185. */
  61186. ParticleSystem.prototype.start = function (delay) {
  61187. var _this = this;
  61188. if (delay === void 0) { delay = this.startDelay; }
  61189. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61190. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61191. }
  61192. if (delay) {
  61193. setTimeout(function () {
  61194. _this.start(0);
  61195. }, delay);
  61196. return;
  61197. }
  61198. // Convert the subEmitters field to the constant type field _subEmitters
  61199. this._prepareSubEmitterInternalArray();
  61200. this._started = true;
  61201. this._stopped = false;
  61202. this._actualFrame = 0;
  61203. if (this._subEmitters && this._subEmitters.length != 0) {
  61204. this.activeSubSystems = new Array();
  61205. }
  61206. // Reset emit gradient so it acts the same on every start
  61207. if (this._emitRateGradients) {
  61208. if (this._emitRateGradients.length > 0) {
  61209. this._currentEmitRateGradient = this._emitRateGradients[0];
  61210. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61211. this._currentEmitRate2 = this._currentEmitRate1;
  61212. }
  61213. if (this._emitRateGradients.length > 1) {
  61214. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61215. }
  61216. }
  61217. // Reset start size gradient so it acts the same on every start
  61218. if (this._startSizeGradients) {
  61219. if (this._startSizeGradients.length > 0) {
  61220. this._currentStartSizeGradient = this._startSizeGradients[0];
  61221. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61222. this._currentStartSize2 = this._currentStartSize1;
  61223. }
  61224. if (this._startSizeGradients.length > 1) {
  61225. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61226. }
  61227. }
  61228. if (this.preWarmCycles) {
  61229. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61230. this.emitter.computeWorldMatrix(true);
  61231. }
  61232. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61233. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61234. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61235. setTimeout(function () {
  61236. for (var index = 0; index < _this.preWarmCycles; index++) {
  61237. _this.animate(true);
  61238. noiseTextureAsProcedural_1.render();
  61239. }
  61240. });
  61241. });
  61242. }
  61243. else {
  61244. for (var index = 0; index < this.preWarmCycles; index++) {
  61245. this.animate(true);
  61246. }
  61247. }
  61248. }
  61249. // Animations
  61250. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61251. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61252. }
  61253. };
  61254. /**
  61255. * Stops the particle system.
  61256. * @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.
  61257. */
  61258. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61259. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61260. this._stopped = true;
  61261. if (stopSubEmitters) {
  61262. this._stopSubEmitters();
  61263. }
  61264. };
  61265. // animation sheet
  61266. /**
  61267. * Remove all active particles
  61268. */
  61269. ParticleSystem.prototype.reset = function () {
  61270. this._stockParticles = [];
  61271. this._particles = [];
  61272. };
  61273. /**
  61274. * @hidden (for internal use only)
  61275. */
  61276. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61277. var offset = index * this._vertexBufferSize;
  61278. this._vertexData[offset++] = particle.position.x;
  61279. this._vertexData[offset++] = particle.position.y;
  61280. this._vertexData[offset++] = particle.position.z;
  61281. this._vertexData[offset++] = particle.color.r;
  61282. this._vertexData[offset++] = particle.color.g;
  61283. this._vertexData[offset++] = particle.color.b;
  61284. this._vertexData[offset++] = particle.color.a;
  61285. this._vertexData[offset++] = particle.angle;
  61286. this._vertexData[offset++] = particle.scale.x * particle.size;
  61287. this._vertexData[offset++] = particle.scale.y * particle.size;
  61288. if (this._isAnimationSheetEnabled) {
  61289. this._vertexData[offset++] = particle.cellIndex;
  61290. }
  61291. if (!this._isBillboardBased) {
  61292. if (particle._initialDirection) {
  61293. this._vertexData[offset++] = particle._initialDirection.x;
  61294. this._vertexData[offset++] = particle._initialDirection.y;
  61295. this._vertexData[offset++] = particle._initialDirection.z;
  61296. }
  61297. else {
  61298. this._vertexData[offset++] = particle.direction.x;
  61299. this._vertexData[offset++] = particle.direction.y;
  61300. this._vertexData[offset++] = particle.direction.z;
  61301. }
  61302. }
  61303. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61304. this._vertexData[offset++] = particle.direction.x;
  61305. this._vertexData[offset++] = particle.direction.y;
  61306. this._vertexData[offset++] = particle.direction.z;
  61307. }
  61308. if (this._useRampGradients) {
  61309. this._vertexData[offset++] = particle.remapData.x;
  61310. this._vertexData[offset++] = particle.remapData.y;
  61311. this._vertexData[offset++] = particle.remapData.z;
  61312. this._vertexData[offset++] = particle.remapData.w;
  61313. }
  61314. if (!this._useInstancing) {
  61315. if (this._isAnimationSheetEnabled) {
  61316. if (offsetX === 0) {
  61317. offsetX = this._epsilon;
  61318. }
  61319. else if (offsetX === 1) {
  61320. offsetX = 1 - this._epsilon;
  61321. }
  61322. if (offsetY === 0) {
  61323. offsetY = this._epsilon;
  61324. }
  61325. else if (offsetY === 1) {
  61326. offsetY = 1 - this._epsilon;
  61327. }
  61328. }
  61329. this._vertexData[offset++] = offsetX;
  61330. this._vertexData[offset++] = offsetY;
  61331. }
  61332. };
  61333. ParticleSystem.prototype._stopSubEmitters = function () {
  61334. if (!this.activeSubSystems) {
  61335. return;
  61336. }
  61337. this.activeSubSystems.forEach(function (subSystem) {
  61338. subSystem.stop(true);
  61339. });
  61340. this.activeSubSystems = new Array();
  61341. };
  61342. ParticleSystem.prototype._removeFromRoot = function () {
  61343. if (!this._rootParticleSystem) {
  61344. return;
  61345. }
  61346. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61347. if (index !== -1) {
  61348. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61349. }
  61350. this._rootParticleSystem = null;
  61351. };
  61352. // End of sub system methods
  61353. ParticleSystem.prototype._update = function (newParticles) {
  61354. var _this = this;
  61355. // Update current
  61356. this._alive = this._particles.length > 0;
  61357. if (this.emitter.position) {
  61358. var emitterMesh = this.emitter;
  61359. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61360. }
  61361. else {
  61362. var emitterPosition = this.emitter;
  61363. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61364. }
  61365. this.updateFunction(this._particles);
  61366. // Add new ones
  61367. var particle;
  61368. var _loop_2 = function () {
  61369. if (this_1._particles.length === this_1._capacity) {
  61370. return "break";
  61371. }
  61372. particle = this_1._createParticle();
  61373. this_1._particles.push(particle);
  61374. // Emitter
  61375. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61376. if (this_1.startPositionFunction) {
  61377. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61378. }
  61379. else {
  61380. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61381. }
  61382. if (this_1.startDirectionFunction) {
  61383. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61384. }
  61385. else {
  61386. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61387. }
  61388. if (emitPower === 0) {
  61389. if (!particle._initialDirection) {
  61390. particle._initialDirection = particle.direction.clone();
  61391. }
  61392. else {
  61393. particle._initialDirection.copyFrom(particle.direction);
  61394. }
  61395. }
  61396. else {
  61397. particle._initialDirection = null;
  61398. }
  61399. particle.direction.scaleInPlace(emitPower);
  61400. // Life time
  61401. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61402. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61403. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61404. var factorGradient1 = currentGradient;
  61405. var factorGradient2 = nextGradient;
  61406. var lifeTime1 = factorGradient1.getFactor();
  61407. var lifeTime2 = factorGradient2.getFactor();
  61408. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61409. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61410. });
  61411. }
  61412. else {
  61413. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61414. }
  61415. // Size
  61416. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61417. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61418. }
  61419. else {
  61420. particle._currentSizeGradient = this_1._sizeGradients[0];
  61421. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61422. particle.size = particle._currentSize1;
  61423. if (this_1._sizeGradients.length > 1) {
  61424. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61425. }
  61426. else {
  61427. particle._currentSize2 = particle._currentSize1;
  61428. }
  61429. }
  61430. // Size and scale
  61431. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61432. // Adjust scale by start size
  61433. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61434. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61435. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61436. if (currentGradient !== _this._currentStartSizeGradient) {
  61437. _this._currentStartSize1 = _this._currentStartSize2;
  61438. _this._currentStartSize2 = nextGradient.getFactor();
  61439. _this._currentStartSizeGradient = currentGradient;
  61440. }
  61441. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61442. particle.scale.scaleInPlace(value);
  61443. });
  61444. }
  61445. // Angle
  61446. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61447. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61448. }
  61449. else {
  61450. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61451. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61452. particle._currentAngularSpeed1 = particle.angularSpeed;
  61453. if (this_1._angularSpeedGradients.length > 1) {
  61454. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61455. }
  61456. else {
  61457. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61458. }
  61459. }
  61460. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61461. // Velocity
  61462. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61463. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61464. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61465. if (this_1._velocityGradients.length > 1) {
  61466. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61467. }
  61468. else {
  61469. particle._currentVelocity2 = particle._currentVelocity1;
  61470. }
  61471. }
  61472. // Limit velocity
  61473. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61474. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61475. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61476. if (this_1._limitVelocityGradients.length > 1) {
  61477. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61478. }
  61479. else {
  61480. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61481. }
  61482. }
  61483. // Drag
  61484. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61485. particle._currentDragGradient = this_1._dragGradients[0];
  61486. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61487. if (this_1._dragGradients.length > 1) {
  61488. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61489. }
  61490. else {
  61491. particle._currentDrag2 = particle._currentDrag1;
  61492. }
  61493. }
  61494. // Color
  61495. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61496. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61497. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61498. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61499. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61500. }
  61501. else {
  61502. particle._currentColorGradient = this_1._colorGradients[0];
  61503. particle._currentColorGradient.getColorToRef(particle.color);
  61504. particle._currentColor1.copyFrom(particle.color);
  61505. if (this_1._colorGradients.length > 1) {
  61506. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61507. }
  61508. else {
  61509. particle._currentColor2.copyFrom(particle.color);
  61510. }
  61511. }
  61512. // Sheet
  61513. if (this_1._isAnimationSheetEnabled) {
  61514. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61515. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61516. }
  61517. // Inherited Velocity
  61518. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61519. // Ramp
  61520. if (this_1._useRampGradients) {
  61521. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61522. }
  61523. // Noise texture coordinates
  61524. if (this_1.noiseTexture) {
  61525. if (particle._randomNoiseCoordinates1) {
  61526. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61527. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61528. }
  61529. else {
  61530. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61531. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61532. }
  61533. }
  61534. // Update the position of the attached sub-emitters to match their attached particle
  61535. particle._inheritParticleInfoToSubEmitters();
  61536. };
  61537. var this_1 = this, step;
  61538. for (var index = 0; index < newParticles; index++) {
  61539. var state_1 = _loop_2();
  61540. if (state_1 === "break")
  61541. break;
  61542. }
  61543. };
  61544. /** @hidden */
  61545. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  61546. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61547. if (isBillboardBased === void 0) { isBillboardBased = false; }
  61548. if (useRampGradients === void 0) { useRampGradients = false; }
  61549. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  61550. if (isAnimationSheetEnabled) {
  61551. attributeNamesOrOptions.push("cellIndex");
  61552. }
  61553. if (!isBillboardBased) {
  61554. attributeNamesOrOptions.push("direction");
  61555. }
  61556. if (useRampGradients) {
  61557. attributeNamesOrOptions.push("remapData");
  61558. }
  61559. return attributeNamesOrOptions;
  61560. };
  61561. /** @hidden */
  61562. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  61563. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61564. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  61565. if (isAnimationSheetEnabled) {
  61566. effectCreationOption.push("particlesInfos");
  61567. }
  61568. return effectCreationOption;
  61569. };
  61570. /** @hidden */
  61571. ParticleSystem.prototype._getEffect = function (blendMode) {
  61572. if (this._customEffect) {
  61573. return this._customEffect;
  61574. }
  61575. var defines = [];
  61576. if (this._scene.clipPlane) {
  61577. defines.push("#define CLIPPLANE");
  61578. }
  61579. if (this._scene.clipPlane2) {
  61580. defines.push("#define CLIPPLANE2");
  61581. }
  61582. if (this._scene.clipPlane3) {
  61583. defines.push("#define CLIPPLANE3");
  61584. }
  61585. if (this._scene.clipPlane4) {
  61586. defines.push("#define CLIPPLANE4");
  61587. }
  61588. if (this._isAnimationSheetEnabled) {
  61589. defines.push("#define ANIMATESHEET");
  61590. }
  61591. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  61592. defines.push("#define BLENDMULTIPLYMODE");
  61593. }
  61594. if (this._useRampGradients) {
  61595. defines.push("#define RAMPGRADIENT");
  61596. }
  61597. if (this._isBillboardBased) {
  61598. defines.push("#define BILLBOARD");
  61599. switch (this.billboardMode) {
  61600. case ParticleSystem.BILLBOARDMODE_Y:
  61601. defines.push("#define BILLBOARDY");
  61602. break;
  61603. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  61604. defines.push("#define BILLBOARDSTRETCHED");
  61605. break;
  61606. case ParticleSystem.BILLBOARDMODE_ALL:
  61607. default:
  61608. break;
  61609. }
  61610. }
  61611. if (this._imageProcessingConfiguration) {
  61612. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61613. defines.push(this._imageProcessingConfigurationDefines.toString());
  61614. }
  61615. // Effect
  61616. var join = defines.join("\n");
  61617. if (this._cachedDefines !== join) {
  61618. this._cachedDefines = join;
  61619. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  61620. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  61621. var samplers = ["diffuseSampler", "rampSampler"];
  61622. if (BABYLON.ImageProcessingConfiguration) {
  61623. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  61624. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61625. }
  61626. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  61627. }
  61628. return this._effect;
  61629. };
  61630. /**
  61631. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61632. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  61633. */
  61634. ParticleSystem.prototype.animate = function (preWarmOnly) {
  61635. var _this = this;
  61636. if (preWarmOnly === void 0) { preWarmOnly = false; }
  61637. if (!this._started) {
  61638. return;
  61639. }
  61640. if (!preWarmOnly) {
  61641. // Check
  61642. if (!this.isReady()) {
  61643. return;
  61644. }
  61645. if (this._currentRenderId === this._scene.getFrameId()) {
  61646. return;
  61647. }
  61648. this._currentRenderId = this._scene.getFrameId();
  61649. }
  61650. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61651. // Determine the number of particles we need to create
  61652. var newParticles;
  61653. if (this.manualEmitCount > -1) {
  61654. newParticles = this.manualEmitCount;
  61655. this._newPartsExcess = 0;
  61656. this.manualEmitCount = 0;
  61657. }
  61658. else {
  61659. var rate_1 = this.emitRate;
  61660. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  61661. var ratio = this._actualFrame / this.targetStopDuration;
  61662. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  61663. if (currentGradient !== _this._currentEmitRateGradient) {
  61664. _this._currentEmitRate1 = _this._currentEmitRate2;
  61665. _this._currentEmitRate2 = nextGradient.getFactor();
  61666. _this._currentEmitRateGradient = currentGradient;
  61667. }
  61668. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  61669. });
  61670. }
  61671. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  61672. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  61673. }
  61674. if (this._newPartsExcess > 1.0) {
  61675. newParticles += this._newPartsExcess >> 0;
  61676. this._newPartsExcess -= this._newPartsExcess >> 0;
  61677. }
  61678. this._alive = false;
  61679. if (!this._stopped) {
  61680. this._actualFrame += this._scaledUpdateSpeed;
  61681. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61682. this.stop();
  61683. }
  61684. }
  61685. else {
  61686. newParticles = 0;
  61687. }
  61688. this._update(newParticles);
  61689. // Stopped?
  61690. if (this._stopped) {
  61691. if (!this._alive) {
  61692. this._started = false;
  61693. if (this.onAnimationEnd) {
  61694. this.onAnimationEnd();
  61695. }
  61696. if (this.disposeOnStop) {
  61697. this._scene._toBeDisposed.push(this);
  61698. }
  61699. }
  61700. }
  61701. if (!preWarmOnly) {
  61702. // Update VBO
  61703. var offset = 0;
  61704. for (var index = 0; index < this._particles.length; index++) {
  61705. var particle = this._particles[index];
  61706. this._appendParticleVertices(offset, particle);
  61707. offset += this._useInstancing ? 1 : 4;
  61708. }
  61709. if (this._vertexBuffer) {
  61710. this._vertexBuffer.update(this._vertexData);
  61711. }
  61712. }
  61713. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  61714. this.stop();
  61715. }
  61716. };
  61717. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  61718. this._appendParticleVertex(offset++, particle, 0, 0);
  61719. if (!this._useInstancing) {
  61720. this._appendParticleVertex(offset++, particle, 1, 0);
  61721. this._appendParticleVertex(offset++, particle, 1, 1);
  61722. this._appendParticleVertex(offset++, particle, 0, 1);
  61723. }
  61724. };
  61725. /**
  61726. * Rebuilds the particle system.
  61727. */
  61728. ParticleSystem.prototype.rebuild = function () {
  61729. this._createIndexBuffer();
  61730. if (this._vertexBuffer) {
  61731. this._vertexBuffer._rebuild();
  61732. }
  61733. };
  61734. /**
  61735. * Is this system ready to be used/rendered
  61736. * @return true if the system is ready
  61737. */
  61738. ParticleSystem.prototype.isReady = function () {
  61739. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61740. return false;
  61741. }
  61742. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61743. if (!this._getEffect(this.blendMode).isReady()) {
  61744. return false;
  61745. }
  61746. }
  61747. else {
  61748. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  61749. return false;
  61750. }
  61751. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  61752. return false;
  61753. }
  61754. }
  61755. return true;
  61756. };
  61757. ParticleSystem.prototype._render = function (blendMode) {
  61758. var effect = this._getEffect(blendMode);
  61759. var engine = this._scene.getEngine();
  61760. // Render
  61761. engine.enableEffect(effect);
  61762. var viewMatrix = this._scene.getViewMatrix();
  61763. effect.setTexture("diffuseSampler", this.particleTexture);
  61764. effect.setMatrix("view", viewMatrix);
  61765. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  61766. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61767. var baseSize = this.particleTexture.getBaseSize();
  61768. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61769. }
  61770. effect.setVector2("translationPivot", this.translationPivot);
  61771. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  61772. if (this._isBillboardBased) {
  61773. var camera = this._scene.activeCamera;
  61774. effect.setVector3("eyePosition", camera.globalPosition);
  61775. }
  61776. if (this._rampGradientsTexture) {
  61777. effect.setTexture("rampSampler", this._rampGradientsTexture);
  61778. }
  61779. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61780. var invView = viewMatrix.clone();
  61781. invView.invert();
  61782. effect.setMatrix("invView", invView);
  61783. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  61784. }
  61785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  61786. // image processing
  61787. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61788. this._imageProcessingConfiguration.bind(effect);
  61789. }
  61790. // Draw order
  61791. switch (blendMode) {
  61792. case ParticleSystem.BLENDMODE_ADD:
  61793. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61794. break;
  61795. case ParticleSystem.BLENDMODE_ONEONE:
  61796. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61797. break;
  61798. case ParticleSystem.BLENDMODE_STANDARD:
  61799. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61800. break;
  61801. case ParticleSystem.BLENDMODE_MULTIPLY:
  61802. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61803. break;
  61804. }
  61805. if (this._useInstancing) {
  61806. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  61807. }
  61808. else {
  61809. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  61810. }
  61811. return this._particles.length;
  61812. };
  61813. /**
  61814. * Renders the particle system in its current state.
  61815. * @returns the current number of particles
  61816. */
  61817. ParticleSystem.prototype.render = function () {
  61818. // Check
  61819. if (!this.isReady() || !this._particles.length) {
  61820. return 0;
  61821. }
  61822. var engine = this._scene.getEngine();
  61823. engine.setState(false);
  61824. if (this.forceDepthWrite) {
  61825. engine.setDepthWrite(true);
  61826. }
  61827. var outparticles = 0;
  61828. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61829. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  61830. }
  61831. outparticles = this._render(this.blendMode);
  61832. engine.unbindInstanceAttributes();
  61833. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61834. return outparticles;
  61835. };
  61836. /**
  61837. * Disposes the particle system and free the associated resources
  61838. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61839. */
  61840. ParticleSystem.prototype.dispose = function (disposeTexture) {
  61841. if (disposeTexture === void 0) { disposeTexture = true; }
  61842. if (this._vertexBuffer) {
  61843. this._vertexBuffer.dispose();
  61844. this._vertexBuffer = null;
  61845. }
  61846. if (this._spriteBuffer) {
  61847. this._spriteBuffer.dispose();
  61848. this._spriteBuffer = null;
  61849. }
  61850. if (this._indexBuffer) {
  61851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61852. this._indexBuffer = null;
  61853. }
  61854. if (disposeTexture && this.particleTexture) {
  61855. this.particleTexture.dispose();
  61856. this.particleTexture = null;
  61857. }
  61858. if (disposeTexture && this.noiseTexture) {
  61859. this.noiseTexture.dispose();
  61860. this.noiseTexture = null;
  61861. }
  61862. if (this._rampGradientsTexture) {
  61863. this._rampGradientsTexture.dispose();
  61864. this._rampGradientsTexture = null;
  61865. }
  61866. this._removeFromRoot();
  61867. if (this._subEmitters && this._subEmitters.length) {
  61868. for (var index = 0; index < this._subEmitters.length; index++) {
  61869. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  61870. var subEmitter = _a[_i];
  61871. subEmitter.dispose();
  61872. }
  61873. }
  61874. this._subEmitters = [];
  61875. this.subEmitters = [];
  61876. }
  61877. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  61878. this.emitter.dispose(true);
  61879. }
  61880. // Remove from scene
  61881. var index = this._scene.particleSystems.indexOf(this);
  61882. if (index > -1) {
  61883. this._scene.particleSystems.splice(index, 1);
  61884. }
  61885. this._scene._activeParticleSystems.dispose();
  61886. // Callback
  61887. this.onDisposeObservable.notifyObservers(this);
  61888. this.onDisposeObservable.clear();
  61889. this.reset();
  61890. };
  61891. // Clone
  61892. /**
  61893. * Clones the particle system.
  61894. * @param name The name of the cloned object
  61895. * @param newEmitter The new emitter to use
  61896. * @returns the cloned particle system
  61897. */
  61898. ParticleSystem.prototype.clone = function (name, newEmitter) {
  61899. var custom = null;
  61900. var program = null;
  61901. if (this.customShader != null) {
  61902. program = this.customShader;
  61903. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61904. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61905. }
  61906. else if (this._customEffect) {
  61907. custom = this._customEffect;
  61908. }
  61909. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  61910. result.customShader = program;
  61911. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  61912. if (newEmitter === undefined) {
  61913. newEmitter = this.emitter;
  61914. }
  61915. result.noiseTexture = this.noiseTexture;
  61916. result.emitter = newEmitter;
  61917. if (this.particleTexture) {
  61918. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61919. }
  61920. // Clone gradients
  61921. if (this._colorGradients) {
  61922. this._colorGradients.forEach(function (v) {
  61923. result.addColorGradient(v.gradient, v.color1, v.color2);
  61924. });
  61925. }
  61926. if (this._dragGradients) {
  61927. this._dragGradients.forEach(function (v) {
  61928. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  61929. });
  61930. }
  61931. if (this._angularSpeedGradients) {
  61932. this._angularSpeedGradients.forEach(function (v) {
  61933. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  61934. });
  61935. }
  61936. if (this._emitRateGradients) {
  61937. this._emitRateGradients.forEach(function (v) {
  61938. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  61939. });
  61940. }
  61941. if (this._lifeTimeGradients) {
  61942. this._lifeTimeGradients.forEach(function (v) {
  61943. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  61944. });
  61945. }
  61946. if (this._limitVelocityGradients) {
  61947. this._limitVelocityGradients.forEach(function (v) {
  61948. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  61949. });
  61950. }
  61951. if (this._sizeGradients) {
  61952. this._sizeGradients.forEach(function (v) {
  61953. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  61954. });
  61955. }
  61956. if (this._startSizeGradients) {
  61957. this._startSizeGradients.forEach(function (v) {
  61958. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  61959. });
  61960. }
  61961. if (this._velocityGradients) {
  61962. this._velocityGradients.forEach(function (v) {
  61963. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  61964. });
  61965. }
  61966. if (this._rampGradients) {
  61967. this._rampGradients.forEach(function (v) {
  61968. result.addRampGradient(v.gradient, v.color);
  61969. });
  61970. }
  61971. if (this._colorRemapGradients) {
  61972. this._colorRemapGradients.forEach(function (v) {
  61973. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  61974. });
  61975. }
  61976. if (this._alphaRemapGradients) {
  61977. this._alphaRemapGradients.forEach(function (v) {
  61978. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  61979. });
  61980. }
  61981. if (!this.preventAutoStart) {
  61982. result.start();
  61983. }
  61984. return result;
  61985. };
  61986. /**
  61987. * Serializes the particle system to a JSON object.
  61988. * @returns the JSON object
  61989. */
  61990. ParticleSystem.prototype.serialize = function () {
  61991. var serializationObject = {};
  61992. ParticleSystem._Serialize(serializationObject, this);
  61993. serializationObject.textureMask = this.textureMask.asArray();
  61994. serializationObject.customShader = this.customShader;
  61995. serializationObject.preventAutoStart = this.preventAutoStart;
  61996. // SubEmitters
  61997. if (this.subEmitters) {
  61998. serializationObject.subEmitters = [];
  61999. if (!this._subEmitters) {
  62000. this._prepareSubEmitterInternalArray();
  62001. }
  62002. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62003. var subs = _a[_i];
  62004. var cell = [];
  62005. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62006. var sub = subs_1[_b];
  62007. cell.push(sub.serialize());
  62008. }
  62009. serializationObject.subEmitters.push(cell);
  62010. }
  62011. }
  62012. return serializationObject;
  62013. };
  62014. /** @hidden */
  62015. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62016. serializationObject.name = particleSystem.name;
  62017. serializationObject.id = particleSystem.id;
  62018. serializationObject.capacity = particleSystem.getCapacity();
  62019. // Emitter
  62020. if (particleSystem.emitter.position) {
  62021. var emitterMesh = particleSystem.emitter;
  62022. serializationObject.emitterId = emitterMesh.id;
  62023. }
  62024. else {
  62025. var emitterPosition = particleSystem.emitter;
  62026. serializationObject.emitter = emitterPosition.asArray();
  62027. }
  62028. // Emitter
  62029. if (particleSystem.particleEmitterType) {
  62030. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62031. }
  62032. if (particleSystem.particleTexture) {
  62033. serializationObject.textureName = particleSystem.particleTexture.name;
  62034. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62035. }
  62036. // Animations
  62037. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62038. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62039. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62040. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62041. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62042. // Particle system
  62043. serializationObject.startDelay = particleSystem.startDelay;
  62044. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62045. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62046. serializationObject.billboardMode = particleSystem.billboardMode;
  62047. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62048. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62049. serializationObject.minSize = particleSystem.minSize;
  62050. serializationObject.maxSize = particleSystem.maxSize;
  62051. serializationObject.minScaleX = particleSystem.minScaleX;
  62052. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62053. serializationObject.minScaleY = particleSystem.minScaleY;
  62054. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62055. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62056. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62057. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62058. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62059. serializationObject.emitRate = particleSystem.emitRate;
  62060. serializationObject.gravity = particleSystem.gravity.asArray();
  62061. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62062. serializationObject.color1 = particleSystem.color1.asArray();
  62063. serializationObject.color2 = particleSystem.color2.asArray();
  62064. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62065. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62066. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62067. serializationObject.blendMode = particleSystem.blendMode;
  62068. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62069. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62070. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62071. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62072. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62073. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62074. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62075. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62076. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62077. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62078. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62079. var colorGradients = particleSystem.getColorGradients();
  62080. if (colorGradients) {
  62081. serializationObject.colorGradients = [];
  62082. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62083. var colorGradient = colorGradients_1[_i];
  62084. var serializedGradient = {
  62085. gradient: colorGradient.gradient,
  62086. color1: colorGradient.color1.asArray()
  62087. };
  62088. if (colorGradient.color2) {
  62089. serializedGradient.color2 = colorGradient.color2.asArray();
  62090. }
  62091. serializationObject.colorGradients.push(serializedGradient);
  62092. }
  62093. }
  62094. var rampGradients = particleSystem.getRampGradients();
  62095. if (rampGradients) {
  62096. serializationObject.rampGradients = [];
  62097. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62098. var rampGradient = rampGradients_1[_a];
  62099. var serializedGradient = {
  62100. gradient: rampGradient.gradient,
  62101. color: rampGradient.color.asArray()
  62102. };
  62103. serializationObject.rampGradients.push(serializedGradient);
  62104. }
  62105. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62106. }
  62107. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62108. if (colorRemapGradients) {
  62109. serializationObject.colorRemapGradients = [];
  62110. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62111. var colorRemapGradient = colorRemapGradients_1[_b];
  62112. var serializedGradient = {
  62113. gradient: colorRemapGradient.gradient,
  62114. factor1: colorRemapGradient.factor1
  62115. };
  62116. if (colorRemapGradient.factor2 !== undefined) {
  62117. serializedGradient.factor2 = colorRemapGradient.factor2;
  62118. }
  62119. serializationObject.colorRemapGradients.push(serializedGradient);
  62120. }
  62121. }
  62122. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62123. if (alphaRemapGradients) {
  62124. serializationObject.alphaRemapGradients = [];
  62125. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62126. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62127. var serializedGradient = {
  62128. gradient: alphaRemapGradient.gradient,
  62129. factor1: alphaRemapGradient.factor1
  62130. };
  62131. if (alphaRemapGradient.factor2 !== undefined) {
  62132. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62133. }
  62134. serializationObject.alphaRemapGradients.push(serializedGradient);
  62135. }
  62136. }
  62137. var sizeGradients = particleSystem.getSizeGradients();
  62138. if (sizeGradients) {
  62139. serializationObject.sizeGradients = [];
  62140. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62141. var sizeGradient = sizeGradients_1[_d];
  62142. var serializedGradient = {
  62143. gradient: sizeGradient.gradient,
  62144. factor1: sizeGradient.factor1
  62145. };
  62146. if (sizeGradient.factor2 !== undefined) {
  62147. serializedGradient.factor2 = sizeGradient.factor2;
  62148. }
  62149. serializationObject.sizeGradients.push(serializedGradient);
  62150. }
  62151. }
  62152. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62153. if (angularSpeedGradients) {
  62154. serializationObject.angularSpeedGradients = [];
  62155. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62156. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62157. var serializedGradient = {
  62158. gradient: angularSpeedGradient.gradient,
  62159. factor1: angularSpeedGradient.factor1
  62160. };
  62161. if (angularSpeedGradient.factor2 !== undefined) {
  62162. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62163. }
  62164. serializationObject.angularSpeedGradients.push(serializedGradient);
  62165. }
  62166. }
  62167. var velocityGradients = particleSystem.getVelocityGradients();
  62168. if (velocityGradients) {
  62169. serializationObject.velocityGradients = [];
  62170. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62171. var velocityGradient = velocityGradients_1[_f];
  62172. var serializedGradient = {
  62173. gradient: velocityGradient.gradient,
  62174. factor1: velocityGradient.factor1
  62175. };
  62176. if (velocityGradient.factor2 !== undefined) {
  62177. serializedGradient.factor2 = velocityGradient.factor2;
  62178. }
  62179. serializationObject.velocityGradients.push(serializedGradient);
  62180. }
  62181. }
  62182. var dragGradients = particleSystem.getDragGradients();
  62183. if (dragGradients) {
  62184. serializationObject.dragyGradients = [];
  62185. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62186. var dragGradient = dragGradients_1[_g];
  62187. var serializedGradient = {
  62188. gradient: dragGradient.gradient,
  62189. factor1: dragGradient.factor1
  62190. };
  62191. if (dragGradient.factor2 !== undefined) {
  62192. serializedGradient.factor2 = dragGradient.factor2;
  62193. }
  62194. serializationObject.dragGradients.push(serializedGradient);
  62195. }
  62196. }
  62197. var emitRateGradients = particleSystem.getEmitRateGradients();
  62198. if (emitRateGradients) {
  62199. serializationObject.emitRateGradients = [];
  62200. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62201. var emitRateGradient = emitRateGradients_1[_h];
  62202. var serializedGradient = {
  62203. gradient: emitRateGradient.gradient,
  62204. factor1: emitRateGradient.factor1
  62205. };
  62206. if (emitRateGradient.factor2 !== undefined) {
  62207. serializedGradient.factor2 = emitRateGradient.factor2;
  62208. }
  62209. serializationObject.emitRateGradients.push(serializedGradient);
  62210. }
  62211. }
  62212. var startSizeGradients = particleSystem.getStartSizeGradients();
  62213. if (startSizeGradients) {
  62214. serializationObject.startSizeGradients = [];
  62215. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62216. var startSizeGradient = startSizeGradients_1[_j];
  62217. var serializedGradient = {
  62218. gradient: startSizeGradient.gradient,
  62219. factor1: startSizeGradient.factor1
  62220. };
  62221. if (startSizeGradient.factor2 !== undefined) {
  62222. serializedGradient.factor2 = startSizeGradient.factor2;
  62223. }
  62224. serializationObject.startSizeGradients.push(serializedGradient);
  62225. }
  62226. }
  62227. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62228. if (lifeTimeGradients) {
  62229. serializationObject.lifeTimeGradients = [];
  62230. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62231. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62232. var serializedGradient = {
  62233. gradient: lifeTimeGradient.gradient,
  62234. factor1: lifeTimeGradient.factor1
  62235. };
  62236. if (lifeTimeGradient.factor2 !== undefined) {
  62237. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62238. }
  62239. serializationObject.lifeTimeGradients.push(serializedGradient);
  62240. }
  62241. }
  62242. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62243. if (limitVelocityGradients) {
  62244. serializationObject.limitVelocityGradients = [];
  62245. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62246. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62247. var serializedGradient = {
  62248. gradient: limitVelocityGradient.gradient,
  62249. factor1: limitVelocityGradient.factor1
  62250. };
  62251. if (limitVelocityGradient.factor2 !== undefined) {
  62252. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62253. }
  62254. serializationObject.limitVelocityGradients.push(serializedGradient);
  62255. }
  62256. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62257. }
  62258. if (particleSystem.noiseTexture) {
  62259. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62260. }
  62261. };
  62262. /** @hidden */
  62263. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62264. // Texture
  62265. if (parsedParticleSystem.textureName) {
  62266. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62267. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62268. }
  62269. // Emitter
  62270. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62271. particleSystem.emitter = BABYLON.Vector3.Zero();
  62272. }
  62273. else if (parsedParticleSystem.emitterId) {
  62274. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62275. }
  62276. else {
  62277. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62278. }
  62279. // Misc.
  62280. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62281. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62282. }
  62283. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62284. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62285. }
  62286. if (parsedParticleSystem.billboardMode !== undefined) {
  62287. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62288. }
  62289. // Animations
  62290. if (parsedParticleSystem.animations) {
  62291. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62292. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62293. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62294. }
  62295. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62296. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62297. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62298. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62299. }
  62300. if (parsedParticleSystem.autoAnimate) {
  62301. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62302. }
  62303. // Particle system
  62304. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62305. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62306. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62307. particleSystem.minSize = parsedParticleSystem.minSize;
  62308. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62309. if (parsedParticleSystem.minScaleX) {
  62310. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62311. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62312. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62313. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62314. }
  62315. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62316. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62317. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62318. }
  62319. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62320. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62321. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62322. }
  62323. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62324. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62325. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62326. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62327. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62328. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62329. if (parsedParticleSystem.noiseStrength) {
  62330. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62331. }
  62332. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62333. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62334. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62335. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62336. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62337. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62338. if (parsedParticleSystem.colorGradients) {
  62339. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62340. var colorGradient = _a[_i];
  62341. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62342. }
  62343. }
  62344. if (parsedParticleSystem.rampGradients) {
  62345. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62346. var rampGradient = _c[_b];
  62347. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62348. }
  62349. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62350. }
  62351. if (parsedParticleSystem.colorRemapGradients) {
  62352. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62353. var colorRemapGradient = _e[_d];
  62354. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62355. }
  62356. }
  62357. if (parsedParticleSystem.alphaRemapGradients) {
  62358. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62359. var alphaRemapGradient = _g[_f];
  62360. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62361. }
  62362. }
  62363. if (parsedParticleSystem.sizeGradients) {
  62364. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62365. var sizeGradient = _j[_h];
  62366. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62367. }
  62368. }
  62369. if (parsedParticleSystem.sizeGradients) {
  62370. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62371. var sizeGradient = _l[_k];
  62372. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62373. }
  62374. }
  62375. if (parsedParticleSystem.angularSpeedGradients) {
  62376. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62377. var angularSpeedGradient = _o[_m];
  62378. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62379. }
  62380. }
  62381. if (parsedParticleSystem.velocityGradients) {
  62382. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62383. var velocityGradient = _q[_p];
  62384. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62385. }
  62386. }
  62387. if (parsedParticleSystem.dragGradients) {
  62388. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62389. var dragGradient = _s[_r];
  62390. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62391. }
  62392. }
  62393. if (parsedParticleSystem.emitRateGradients) {
  62394. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62395. var emitRateGradient = _u[_t];
  62396. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62397. }
  62398. }
  62399. if (parsedParticleSystem.startSizeGradients) {
  62400. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62401. var startSizeGradient = _w[_v];
  62402. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62403. }
  62404. }
  62405. if (parsedParticleSystem.lifeTimeGradients) {
  62406. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62407. var lifeTimeGradient = _y[_x];
  62408. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62409. }
  62410. }
  62411. if (parsedParticleSystem.limitVelocityGradients) {
  62412. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62413. var limitVelocityGradient = _0[_z];
  62414. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62415. }
  62416. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62417. }
  62418. if (parsedParticleSystem.noiseTexture) {
  62419. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62420. }
  62421. // Emitter
  62422. var emitterType;
  62423. if (parsedParticleSystem.particleEmitterType) {
  62424. switch (parsedParticleSystem.particleEmitterType.type) {
  62425. case "SphereParticleEmitter":
  62426. emitterType = new BABYLON.SphereParticleEmitter();
  62427. break;
  62428. case "SphereDirectedParticleEmitter":
  62429. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62430. break;
  62431. case "ConeEmitter":
  62432. case "ConeParticleEmitter":
  62433. emitterType = new BABYLON.ConeParticleEmitter();
  62434. break;
  62435. case "CylinderParticleEmitter":
  62436. emitterType = new BABYLON.CylinderParticleEmitter();
  62437. break;
  62438. case "HemisphericParticleEmitter":
  62439. emitterType = new BABYLON.HemisphericParticleEmitter();
  62440. break;
  62441. case "BoxEmitter":
  62442. case "BoxParticleEmitter":
  62443. default:
  62444. emitterType = new BABYLON.BoxParticleEmitter();
  62445. break;
  62446. }
  62447. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62448. }
  62449. else {
  62450. emitterType = new BABYLON.BoxParticleEmitter();
  62451. emitterType.parse(parsedParticleSystem);
  62452. }
  62453. particleSystem.particleEmitterType = emitterType;
  62454. // Animation sheet
  62455. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62456. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62457. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62458. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62459. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62460. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62461. };
  62462. /**
  62463. * Parses a JSON object to create a particle system.
  62464. * @param parsedParticleSystem The JSON object to parse
  62465. * @param scene The scene to create the particle system in
  62466. * @param rootUrl The root url to use to load external dependencies like texture
  62467. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62468. * @returns the Parsed particle system
  62469. */
  62470. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62471. if (doNotStart === void 0) { doNotStart = false; }
  62472. var name = parsedParticleSystem.name;
  62473. var custom = null;
  62474. var program = null;
  62475. if (parsedParticleSystem.customShader) {
  62476. program = parsedParticleSystem.customShader;
  62477. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62478. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62479. }
  62480. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62481. particleSystem.customShader = program;
  62482. if (parsedParticleSystem.id) {
  62483. particleSystem.id = parsedParticleSystem.id;
  62484. }
  62485. // SubEmitters
  62486. if (parsedParticleSystem.subEmitters) {
  62487. particleSystem.subEmitters = [];
  62488. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62489. var cell = _a[_i];
  62490. var cellArray = [];
  62491. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62492. var sub = cell_1[_b];
  62493. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62494. }
  62495. particleSystem.subEmitters.push(cellArray);
  62496. }
  62497. }
  62498. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62499. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62500. // Auto start
  62501. if (parsedParticleSystem.preventAutoStart) {
  62502. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62503. }
  62504. if (!doNotStart && !particleSystem.preventAutoStart) {
  62505. particleSystem.start();
  62506. }
  62507. return particleSystem;
  62508. };
  62509. /**
  62510. * Billboard mode will only apply to Y axis
  62511. */
  62512. ParticleSystem.BILLBOARDMODE_Y = 2;
  62513. /**
  62514. * Billboard mode will apply to all axes
  62515. */
  62516. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62517. /**
  62518. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62519. */
  62520. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62521. return ParticleSystem;
  62522. }(BABYLON.BaseParticleSystem));
  62523. BABYLON.ParticleSystem = ParticleSystem;
  62524. })(BABYLON || (BABYLON = {}));
  62525. //# sourceMappingURL=babylon.particleSystem.js.map
  62526. var BABYLON;
  62527. (function (BABYLON) {
  62528. /**
  62529. * Particle emitter emitting particles from the inside of a box.
  62530. * It emits the particles randomly between 2 given directions.
  62531. */
  62532. var BoxParticleEmitter = /** @class */ (function () {
  62533. /**
  62534. * Creates a new instance BoxParticleEmitter
  62535. */
  62536. function BoxParticleEmitter() {
  62537. /**
  62538. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62539. */
  62540. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62541. /**
  62542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62543. */
  62544. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62545. /**
  62546. * 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.
  62547. */
  62548. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  62549. /**
  62550. * 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.
  62551. */
  62552. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  62553. }
  62554. /**
  62555. * Called by the particle System when the direction is computed for the created particle.
  62556. * @param worldMatrix is the world matrix of the particle system
  62557. * @param directionToUpdate is the direction vector to update with the result
  62558. * @param particle is the particle we are computed the direction for
  62559. */
  62560. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62561. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62562. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62563. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62564. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62565. };
  62566. /**
  62567. * Called by the particle System when the position is computed for the created particle.
  62568. * @param worldMatrix is the world matrix of the particle system
  62569. * @param positionToUpdate is the position vector to update with the result
  62570. * @param particle is the particle we are computed the position for
  62571. */
  62572. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62573. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  62574. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  62575. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  62576. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62577. };
  62578. /**
  62579. * Clones the current emitter and returns a copy of it
  62580. * @returns the new emitter
  62581. */
  62582. BoxParticleEmitter.prototype.clone = function () {
  62583. var newOne = new BoxParticleEmitter();
  62584. BABYLON.Tools.DeepCopy(this, newOne);
  62585. return newOne;
  62586. };
  62587. /**
  62588. * Called by the GPUParticleSystem to setup the update shader
  62589. * @param effect defines the update shader
  62590. */
  62591. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  62592. effect.setVector3("direction1", this.direction1);
  62593. effect.setVector3("direction2", this.direction2);
  62594. effect.setVector3("minEmitBox", this.minEmitBox);
  62595. effect.setVector3("maxEmitBox", this.maxEmitBox);
  62596. };
  62597. /**
  62598. * Returns a string to use to update the GPU particles update shader
  62599. * @returns a string containng the defines string
  62600. */
  62601. BoxParticleEmitter.prototype.getEffectDefines = function () {
  62602. return "#define BOXEMITTER";
  62603. };
  62604. /**
  62605. * Returns the string "BoxParticleEmitter"
  62606. * @returns a string containing the class name
  62607. */
  62608. BoxParticleEmitter.prototype.getClassName = function () {
  62609. return "BoxParticleEmitter";
  62610. };
  62611. /**
  62612. * Serializes the particle system to a JSON object.
  62613. * @returns the JSON object
  62614. */
  62615. BoxParticleEmitter.prototype.serialize = function () {
  62616. var serializationObject = {};
  62617. serializationObject.type = this.getClassName();
  62618. serializationObject.direction1 = this.direction1.asArray();
  62619. serializationObject.direction2 = this.direction2.asArray();
  62620. serializationObject.minEmitBox = this.minEmitBox.asArray();
  62621. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  62622. return serializationObject;
  62623. };
  62624. /**
  62625. * Parse properties from a JSON object
  62626. * @param serializationObject defines the JSON object
  62627. */
  62628. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  62629. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62630. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62631. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  62632. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  62633. };
  62634. return BoxParticleEmitter;
  62635. }());
  62636. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  62637. })(BABYLON || (BABYLON = {}));
  62638. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  62639. var BABYLON;
  62640. (function (BABYLON) {
  62641. /**
  62642. * Particle emitter emitting particles from the inside of a cylinder.
  62643. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  62644. */
  62645. var CylinderParticleEmitter = /** @class */ (function () {
  62646. /**
  62647. * Creates a new instance CylinderParticleEmitter
  62648. * @param radius the radius of the emission cylinder (1 by default)
  62649. * @param height the height of the emission cylinder (1 by default)
  62650. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62651. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62652. */
  62653. function CylinderParticleEmitter(
  62654. /**
  62655. * The radius of the emission cylinder.
  62656. */
  62657. radius,
  62658. /**
  62659. * The height of the emission cylinder.
  62660. */
  62661. height,
  62662. /**
  62663. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62664. */
  62665. radiusRange,
  62666. /**
  62667. * How much to randomize the particle direction [0-1].
  62668. */
  62669. directionRandomizer) {
  62670. if (radius === void 0) { radius = 1; }
  62671. if (height === void 0) { height = 1; }
  62672. if (radiusRange === void 0) { radiusRange = 1; }
  62673. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62674. this.radius = radius;
  62675. this.height = height;
  62676. this.radiusRange = radiusRange;
  62677. this.directionRandomizer = directionRandomizer;
  62678. }
  62679. /**
  62680. * Called by the particle System when the direction is computed for the created particle.
  62681. * @param worldMatrix is the world matrix of the particle system
  62682. * @param directionToUpdate is the direction vector to update with the result
  62683. * @param particle is the particle we are computed the direction for
  62684. */
  62685. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62686. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62687. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  62688. var angle = Math.atan2(direction.x, direction.z);
  62689. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  62690. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  62691. direction.x = Math.sin(angle);
  62692. direction.z = Math.cos(angle);
  62693. direction.normalize();
  62694. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62695. };
  62696. /**
  62697. * Called by the particle System when the position is computed for the created particle.
  62698. * @param worldMatrix is the world matrix of the particle system
  62699. * @param positionToUpdate is the position vector to update with the result
  62700. * @param particle is the particle we are computed the position for
  62701. */
  62702. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62703. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  62704. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62705. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  62706. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  62707. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  62708. var xPos = positionRadius * Math.cos(angle);
  62709. var zPos = positionRadius * Math.sin(angle);
  62710. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  62711. };
  62712. /**
  62713. * Clones the current emitter and returns a copy of it
  62714. * @returns the new emitter
  62715. */
  62716. CylinderParticleEmitter.prototype.clone = function () {
  62717. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  62718. BABYLON.Tools.DeepCopy(this, newOne);
  62719. return newOne;
  62720. };
  62721. /**
  62722. * Called by the GPUParticleSystem to setup the update shader
  62723. * @param effect defines the update shader
  62724. */
  62725. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  62726. effect.setFloat("radius", this.radius);
  62727. effect.setFloat("height", this.height);
  62728. effect.setFloat("radiusRange", this.radiusRange);
  62729. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62730. };
  62731. /**
  62732. * Returns a string to use to update the GPU particles update shader
  62733. * @returns a string containng the defines string
  62734. */
  62735. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  62736. return "#define CYLINDEREMITTER";
  62737. };
  62738. /**
  62739. * Returns the string "CylinderParticleEmitter"
  62740. * @returns a string containing the class name
  62741. */
  62742. CylinderParticleEmitter.prototype.getClassName = function () {
  62743. return "CylinderParticleEmitter";
  62744. };
  62745. /**
  62746. * Serializes the particle system to a JSON object.
  62747. * @returns the JSON object
  62748. */
  62749. CylinderParticleEmitter.prototype.serialize = function () {
  62750. var serializationObject = {};
  62751. serializationObject.type = this.getClassName();
  62752. serializationObject.radius = this.radius;
  62753. serializationObject.height = this.height;
  62754. serializationObject.radiusRange = this.radiusRange;
  62755. serializationObject.directionRandomizer = this.directionRandomizer;
  62756. return serializationObject;
  62757. };
  62758. /**
  62759. * Parse properties from a JSON object
  62760. * @param serializationObject defines the JSON object
  62761. */
  62762. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  62763. this.radius = serializationObject.radius;
  62764. this.height = serializationObject.height;
  62765. this.radiusRange = serializationObject.radiusRange;
  62766. this.directionRandomizer = serializationObject.directionRandomizer;
  62767. };
  62768. return CylinderParticleEmitter;
  62769. }());
  62770. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  62771. /**
  62772. * Particle emitter emitting particles from the inside of a cylinder.
  62773. * It emits the particles randomly between two vectors.
  62774. */
  62775. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  62776. __extends(CylinderDirectedParticleEmitter, _super);
  62777. /**
  62778. * Creates a new instance CylinderDirectedParticleEmitter
  62779. * @param radius the radius of the emission cylinder (1 by default)
  62780. * @param height the height of the emission cylinder (1 by default)
  62781. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62782. * @param direction1 the min limit of the emission direction (up vector by default)
  62783. * @param direction2 the max limit of the emission direction (up vector by default)
  62784. */
  62785. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  62786. /**
  62787. * The min limit of the emission direction.
  62788. */
  62789. direction1,
  62790. /**
  62791. * The max limit of the emission direction.
  62792. */
  62793. direction2) {
  62794. if (radius === void 0) { radius = 1; }
  62795. if (height === void 0) { height = 1; }
  62796. if (radiusRange === void 0) { radiusRange = 1; }
  62797. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62798. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62799. var _this = _super.call(this, radius, height, radiusRange) || this;
  62800. _this.direction1 = direction1;
  62801. _this.direction2 = direction2;
  62802. return _this;
  62803. }
  62804. /**
  62805. * Called by the particle System when the direction is computed for the created particle.
  62806. * @param worldMatrix is the world matrix of the particle system
  62807. * @param directionToUpdate is the direction vector to update with the result
  62808. * @param particle is the particle we are computed the direction for
  62809. */
  62810. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62811. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62812. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62813. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62814. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62815. };
  62816. /**
  62817. * Clones the current emitter and returns a copy of it
  62818. * @returns the new emitter
  62819. */
  62820. CylinderDirectedParticleEmitter.prototype.clone = function () {
  62821. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  62822. BABYLON.Tools.DeepCopy(this, newOne);
  62823. return newOne;
  62824. };
  62825. /**
  62826. * Called by the GPUParticleSystem to setup the update shader
  62827. * @param effect defines the update shader
  62828. */
  62829. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62830. effect.setFloat("radius", this.radius);
  62831. effect.setFloat("height", this.height);
  62832. effect.setFloat("radiusRange", this.radiusRange);
  62833. effect.setVector3("direction1", this.direction1);
  62834. effect.setVector3("direction2", this.direction2);
  62835. };
  62836. /**
  62837. * Returns a string to use to update the GPU particles update shader
  62838. * @returns a string containng the defines string
  62839. */
  62840. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62841. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  62842. };
  62843. /**
  62844. * Returns the string "CylinderDirectedParticleEmitter"
  62845. * @returns a string containing the class name
  62846. */
  62847. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  62848. return "CylinderDirectedParticleEmitter";
  62849. };
  62850. /**
  62851. * Serializes the particle system to a JSON object.
  62852. * @returns the JSON object
  62853. */
  62854. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  62855. var serializationObject = _super.prototype.serialize.call(this);
  62856. serializationObject.direction1 = this.direction1.asArray();
  62857. serializationObject.direction2 = this.direction2.asArray();
  62858. return serializationObject;
  62859. };
  62860. /**
  62861. * Parse properties from a JSON object
  62862. * @param serializationObject defines the JSON object
  62863. */
  62864. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62865. _super.prototype.parse.call(this, serializationObject);
  62866. this.direction1.copyFrom(serializationObject.direction1);
  62867. this.direction2.copyFrom(serializationObject.direction2);
  62868. };
  62869. return CylinderDirectedParticleEmitter;
  62870. }(CylinderParticleEmitter));
  62871. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  62872. })(BABYLON || (BABYLON = {}));
  62873. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  62874. var BABYLON;
  62875. (function (BABYLON) {
  62876. /**
  62877. * Particle emitter emitting particles from the inside of a cone.
  62878. * It emits the particles alongside the cone volume from the base to the particle.
  62879. * The emission direction might be randomized.
  62880. */
  62881. var ConeParticleEmitter = /** @class */ (function () {
  62882. /**
  62883. * Creates a new instance ConeParticleEmitter
  62884. * @param radius the radius of the emission cone (1 by default)
  62885. * @param angles the cone base angle (PI by default)
  62886. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  62887. */
  62888. function ConeParticleEmitter(radius, angle,
  62889. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  62890. directionRandomizer) {
  62891. if (radius === void 0) { radius = 1; }
  62892. if (angle === void 0) { angle = Math.PI; }
  62893. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62894. this.directionRandomizer = directionRandomizer;
  62895. /**
  62896. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  62897. */
  62898. this.radiusRange = 1;
  62899. /**
  62900. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  62901. */
  62902. this.heightRange = 1;
  62903. /**
  62904. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  62905. */
  62906. this.emitFromSpawnPointOnly = false;
  62907. this.angle = angle;
  62908. this.radius = radius;
  62909. }
  62910. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  62911. /**
  62912. * Gets or sets the radius of the emission cone
  62913. */
  62914. get: function () {
  62915. return this._radius;
  62916. },
  62917. set: function (value) {
  62918. this._radius = value;
  62919. this._buildHeight();
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  62925. /**
  62926. * Gets or sets the angle of the emission cone
  62927. */
  62928. get: function () {
  62929. return this._angle;
  62930. },
  62931. set: function (value) {
  62932. this._angle = value;
  62933. this._buildHeight();
  62934. },
  62935. enumerable: true,
  62936. configurable: true
  62937. });
  62938. ConeParticleEmitter.prototype._buildHeight = function () {
  62939. if (this._angle !== 0) {
  62940. this._height = this._radius / Math.tan(this._angle / 2);
  62941. }
  62942. else {
  62943. this._height = 1;
  62944. }
  62945. };
  62946. /**
  62947. * Called by the particle System when the direction is computed for the created particle.
  62948. * @param worldMatrix is the world matrix of the particle system
  62949. * @param directionToUpdate is the direction vector to update with the result
  62950. * @param particle is the particle we are computed the direction for
  62951. */
  62952. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62953. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  62954. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  62955. }
  62956. else {
  62957. // measure the direction Vector from the emitter to the particle.
  62958. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62959. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62960. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62961. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62962. direction.x += randX;
  62963. direction.y += randY;
  62964. direction.z += randZ;
  62965. direction.normalize();
  62966. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62967. }
  62968. };
  62969. /**
  62970. * Called by the particle System when the position is computed for the created particle.
  62971. * @param worldMatrix is the world matrix of the particle system
  62972. * @param positionToUpdate is the position vector to update with the result
  62973. * @param particle is the particle we are computed the position for
  62974. */
  62975. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62976. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  62977. var h;
  62978. if (!this.emitFromSpawnPointOnly) {
  62979. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  62980. // Better distribution in a cone at normal angles.
  62981. h = 1 - h * h;
  62982. }
  62983. else {
  62984. h = 0.0001;
  62985. }
  62986. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  62987. radius = radius * h;
  62988. var randX = radius * Math.sin(s);
  62989. var randZ = radius * Math.cos(s);
  62990. var randY = h * this._height;
  62991. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62992. };
  62993. /**
  62994. * Clones the current emitter and returns a copy of it
  62995. * @returns the new emitter
  62996. */
  62997. ConeParticleEmitter.prototype.clone = function () {
  62998. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  62999. BABYLON.Tools.DeepCopy(this, newOne);
  63000. return newOne;
  63001. };
  63002. /**
  63003. * Called by the GPUParticleSystem to setup the update shader
  63004. * @param effect defines the update shader
  63005. */
  63006. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63007. effect.setFloat2("radius", this._radius, this.radiusRange);
  63008. effect.setFloat("coneAngle", this._angle);
  63009. effect.setFloat2("height", this._height, this.heightRange);
  63010. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63011. };
  63012. /**
  63013. * Returns a string to use to update the GPU particles update shader
  63014. * @returns a string containng the defines string
  63015. */
  63016. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63017. var defines = "#define CONEEMITTER";
  63018. if (this.emitFromSpawnPointOnly) {
  63019. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63020. }
  63021. return defines;
  63022. };
  63023. /**
  63024. * Returns the string "ConeParticleEmitter"
  63025. * @returns a string containing the class name
  63026. */
  63027. ConeParticleEmitter.prototype.getClassName = function () {
  63028. return "ConeParticleEmitter";
  63029. };
  63030. /**
  63031. * Serializes the particle system to a JSON object.
  63032. * @returns the JSON object
  63033. */
  63034. ConeParticleEmitter.prototype.serialize = function () {
  63035. var serializationObject = {};
  63036. serializationObject.type = this.getClassName();
  63037. serializationObject.radius = this._radius;
  63038. serializationObject.angle = this._angle;
  63039. serializationObject.directionRandomizer = this.directionRandomizer;
  63040. return serializationObject;
  63041. };
  63042. /**
  63043. * Parse properties from a JSON object
  63044. * @param serializationObject defines the JSON object
  63045. */
  63046. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63047. this.radius = serializationObject.radius;
  63048. this.angle = serializationObject.angle;
  63049. this.directionRandomizer = serializationObject.directionRandomizer;
  63050. };
  63051. return ConeParticleEmitter;
  63052. }());
  63053. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63054. })(BABYLON || (BABYLON = {}));
  63055. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63056. var BABYLON;
  63057. (function (BABYLON) {
  63058. /**
  63059. * Particle emitter emitting particles from the inside of a sphere.
  63060. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63061. */
  63062. var SphereParticleEmitter = /** @class */ (function () {
  63063. /**
  63064. * Creates a new instance SphereParticleEmitter
  63065. * @param radius the radius of the emission sphere (1 by default)
  63066. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63067. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63068. */
  63069. function SphereParticleEmitter(
  63070. /**
  63071. * The radius of the emission sphere.
  63072. */
  63073. radius,
  63074. /**
  63075. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63076. */
  63077. radiusRange,
  63078. /**
  63079. * How much to randomize the particle direction [0-1].
  63080. */
  63081. directionRandomizer) {
  63082. if (radius === void 0) { radius = 1; }
  63083. if (radiusRange === void 0) { radiusRange = 1; }
  63084. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63085. this.radius = radius;
  63086. this.radiusRange = radiusRange;
  63087. this.directionRandomizer = directionRandomizer;
  63088. }
  63089. /**
  63090. * Called by the particle System when the direction is computed for the created particle.
  63091. * @param worldMatrix is the world matrix of the particle system
  63092. * @param directionToUpdate is the direction vector to update with the result
  63093. * @param particle is the particle we are computed the direction for
  63094. */
  63095. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63096. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63097. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63098. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63099. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63100. direction.x += randX;
  63101. direction.y += randY;
  63102. direction.z += randZ;
  63103. direction.normalize();
  63104. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63105. };
  63106. /**
  63107. * Called by the particle System when the position is computed for the created particle.
  63108. * @param worldMatrix is the world matrix of the particle system
  63109. * @param positionToUpdate is the position vector to update with the result
  63110. * @param particle is the particle we are computed the position for
  63111. */
  63112. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63113. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63114. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63115. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63116. var theta = Math.acos(2 * v - 1);
  63117. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63118. var randY = randRadius * Math.cos(theta);
  63119. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63120. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63121. };
  63122. /**
  63123. * Clones the current emitter and returns a copy of it
  63124. * @returns the new emitter
  63125. */
  63126. SphereParticleEmitter.prototype.clone = function () {
  63127. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63128. BABYLON.Tools.DeepCopy(this, newOne);
  63129. return newOne;
  63130. };
  63131. /**
  63132. * Called by the GPUParticleSystem to setup the update shader
  63133. * @param effect defines the update shader
  63134. */
  63135. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63136. effect.setFloat("radius", this.radius);
  63137. effect.setFloat("radiusRange", this.radiusRange);
  63138. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63139. };
  63140. /**
  63141. * Returns a string to use to update the GPU particles update shader
  63142. * @returns a string containng the defines string
  63143. */
  63144. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63145. return "#define SPHEREEMITTER";
  63146. };
  63147. /**
  63148. * Returns the string "SphereParticleEmitter"
  63149. * @returns a string containing the class name
  63150. */
  63151. SphereParticleEmitter.prototype.getClassName = function () {
  63152. return "SphereParticleEmitter";
  63153. };
  63154. /**
  63155. * Serializes the particle system to a JSON object.
  63156. * @returns the JSON object
  63157. */
  63158. SphereParticleEmitter.prototype.serialize = function () {
  63159. var serializationObject = {};
  63160. serializationObject.type = this.getClassName();
  63161. serializationObject.radius = this.radius;
  63162. serializationObject.radiusRange = this.radiusRange;
  63163. serializationObject.directionRandomizer = this.directionRandomizer;
  63164. return serializationObject;
  63165. };
  63166. /**
  63167. * Parse properties from a JSON object
  63168. * @param serializationObject defines the JSON object
  63169. */
  63170. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63171. this.radius = serializationObject.radius;
  63172. this.radiusRange = serializationObject.radiusRange;
  63173. this.directionRandomizer = serializationObject.directionRandomizer;
  63174. };
  63175. return SphereParticleEmitter;
  63176. }());
  63177. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63178. /**
  63179. * Particle emitter emitting particles from the inside of a sphere.
  63180. * It emits the particles randomly between two vectors.
  63181. */
  63182. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63183. __extends(SphereDirectedParticleEmitter, _super);
  63184. /**
  63185. * Creates a new instance SphereDirectedParticleEmitter
  63186. * @param radius the radius of the emission sphere (1 by default)
  63187. * @param direction1 the min limit of the emission direction (up vector by default)
  63188. * @param direction2 the max limit of the emission direction (up vector by default)
  63189. */
  63190. function SphereDirectedParticleEmitter(radius,
  63191. /**
  63192. * The min limit of the emission direction.
  63193. */
  63194. direction1,
  63195. /**
  63196. * The max limit of the emission direction.
  63197. */
  63198. direction2) {
  63199. if (radius === void 0) { radius = 1; }
  63200. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63201. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63202. var _this = _super.call(this, radius) || this;
  63203. _this.direction1 = direction1;
  63204. _this.direction2 = direction2;
  63205. return _this;
  63206. }
  63207. /**
  63208. * Called by the particle System when the direction is computed for the created particle.
  63209. * @param worldMatrix is the world matrix of the particle system
  63210. * @param directionToUpdate is the direction vector to update with the result
  63211. * @param particle is the particle we are computed the direction for
  63212. */
  63213. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63214. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63215. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63216. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63217. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63218. };
  63219. /**
  63220. * Clones the current emitter and returns a copy of it
  63221. * @returns the new emitter
  63222. */
  63223. SphereDirectedParticleEmitter.prototype.clone = function () {
  63224. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63225. BABYLON.Tools.DeepCopy(this, newOne);
  63226. return newOne;
  63227. };
  63228. /**
  63229. * Called by the GPUParticleSystem to setup the update shader
  63230. * @param effect defines the update shader
  63231. */
  63232. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63233. effect.setFloat("radius", this.radius);
  63234. effect.setFloat("radiusRange", this.radiusRange);
  63235. effect.setVector3("direction1", this.direction1);
  63236. effect.setVector3("direction2", this.direction2);
  63237. };
  63238. /**
  63239. * Returns a string to use to update the GPU particles update shader
  63240. * @returns a string containng the defines string
  63241. */
  63242. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63243. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63244. };
  63245. /**
  63246. * Returns the string "SphereDirectedParticleEmitter"
  63247. * @returns a string containing the class name
  63248. */
  63249. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63250. return "SphereDirectedParticleEmitter";
  63251. };
  63252. /**
  63253. * Serializes the particle system to a JSON object.
  63254. * @returns the JSON object
  63255. */
  63256. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63257. var serializationObject = _super.prototype.serialize.call(this);
  63258. serializationObject.direction1 = this.direction1.asArray();
  63259. serializationObject.direction2 = this.direction2.asArray();
  63260. return serializationObject;
  63261. };
  63262. /**
  63263. * Parse properties from a JSON object
  63264. * @param serializationObject defines the JSON object
  63265. */
  63266. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63267. _super.prototype.parse.call(this, serializationObject);
  63268. this.direction1.copyFrom(serializationObject.direction1);
  63269. this.direction2.copyFrom(serializationObject.direction2);
  63270. };
  63271. return SphereDirectedParticleEmitter;
  63272. }(SphereParticleEmitter));
  63273. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63274. })(BABYLON || (BABYLON = {}));
  63275. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  63276. var BABYLON;
  63277. (function (BABYLON) {
  63278. /**
  63279. * Particle emitter emitting particles from the inside of a hemisphere.
  63280. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63281. */
  63282. var HemisphericParticleEmitter = /** @class */ (function () {
  63283. /**
  63284. * Creates a new instance HemisphericParticleEmitter
  63285. * @param radius the radius of the emission hemisphere (1 by default)
  63286. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63287. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63288. */
  63289. function HemisphericParticleEmitter(
  63290. /**
  63291. * The radius of the emission hemisphere.
  63292. */
  63293. radius,
  63294. /**
  63295. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63296. */
  63297. radiusRange,
  63298. /**
  63299. * How much to randomize the particle direction [0-1].
  63300. */
  63301. directionRandomizer) {
  63302. if (radius === void 0) { radius = 1; }
  63303. if (radiusRange === void 0) { radiusRange = 1; }
  63304. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63305. this.radius = radius;
  63306. this.radiusRange = radiusRange;
  63307. this.directionRandomizer = directionRandomizer;
  63308. }
  63309. /**
  63310. * Called by the particle System when the direction is computed for the created particle.
  63311. * @param worldMatrix is the world matrix of the particle system
  63312. * @param directionToUpdate is the direction vector to update with the result
  63313. * @param particle is the particle we are computed the direction for
  63314. */
  63315. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63316. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63317. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63318. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63319. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63320. direction.x += randX;
  63321. direction.y += randY;
  63322. direction.z += randZ;
  63323. direction.normalize();
  63324. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63325. };
  63326. /**
  63327. * Called by the particle System when the position is computed for the created particle.
  63328. * @param worldMatrix is the world matrix of the particle system
  63329. * @param positionToUpdate is the position vector to update with the result
  63330. * @param particle is the particle we are computed the position for
  63331. */
  63332. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63333. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63334. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63335. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63336. var theta = Math.acos(2 * v - 1);
  63337. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63338. var randY = randRadius * Math.cos(theta);
  63339. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63341. };
  63342. /**
  63343. * Clones the current emitter and returns a copy of it
  63344. * @returns the new emitter
  63345. */
  63346. HemisphericParticleEmitter.prototype.clone = function () {
  63347. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63348. BABYLON.Tools.DeepCopy(this, newOne);
  63349. return newOne;
  63350. };
  63351. /**
  63352. * Called by the GPUParticleSystem to setup the update shader
  63353. * @param effect defines the update shader
  63354. */
  63355. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63356. effect.setFloat("radius", this.radius);
  63357. effect.setFloat("radiusRange", this.radiusRange);
  63358. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63359. };
  63360. /**
  63361. * Returns a string to use to update the GPU particles update shader
  63362. * @returns a string containng the defines string
  63363. */
  63364. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63365. return "#define HEMISPHERICEMITTER";
  63366. };
  63367. /**
  63368. * Returns the string "HemisphericParticleEmitter"
  63369. * @returns a string containing the class name
  63370. */
  63371. HemisphericParticleEmitter.prototype.getClassName = function () {
  63372. return "HemisphericParticleEmitter";
  63373. };
  63374. /**
  63375. * Serializes the particle system to a JSON object.
  63376. * @returns the JSON object
  63377. */
  63378. HemisphericParticleEmitter.prototype.serialize = function () {
  63379. var serializationObject = {};
  63380. serializationObject.type = this.getClassName();
  63381. serializationObject.radius = this.radius;
  63382. serializationObject.radiusRange = this.radiusRange;
  63383. serializationObject.directionRandomizer = this.directionRandomizer;
  63384. return serializationObject;
  63385. };
  63386. /**
  63387. * Parse properties from a JSON object
  63388. * @param serializationObject defines the JSON object
  63389. */
  63390. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63391. this.radius = serializationObject.radius;
  63392. this.radiusRange = serializationObject.radiusRange;
  63393. this.directionRandomizer = serializationObject.directionRandomizer;
  63394. };
  63395. return HemisphericParticleEmitter;
  63396. }());
  63397. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63398. })(BABYLON || (BABYLON = {}));
  63399. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  63400. var BABYLON;
  63401. (function (BABYLON) {
  63402. /**
  63403. * Particle emitter emitting particles from a point.
  63404. * It emits the particles randomly between 2 given directions.
  63405. */
  63406. var PointParticleEmitter = /** @class */ (function () {
  63407. /**
  63408. * Creates a new instance PointParticleEmitter
  63409. */
  63410. function PointParticleEmitter() {
  63411. /**
  63412. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63413. */
  63414. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63415. /**
  63416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63417. */
  63418. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63419. }
  63420. /**
  63421. * Called by the particle System when the direction is computed for the created particle.
  63422. * @param worldMatrix is the world matrix of the particle system
  63423. * @param directionToUpdate is the direction vector to update with the result
  63424. * @param particle is the particle we are computed the direction for
  63425. */
  63426. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63427. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63428. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63429. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63430. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63431. };
  63432. /**
  63433. * Called by the particle System when the position is computed for the created particle.
  63434. * @param worldMatrix is the world matrix of the particle system
  63435. * @param positionToUpdate is the position vector to update with the result
  63436. * @param particle is the particle we are computed the position for
  63437. */
  63438. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63439. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63440. };
  63441. /**
  63442. * Clones the current emitter and returns a copy of it
  63443. * @returns the new emitter
  63444. */
  63445. PointParticleEmitter.prototype.clone = function () {
  63446. var newOne = new PointParticleEmitter();
  63447. BABYLON.Tools.DeepCopy(this, newOne);
  63448. return newOne;
  63449. };
  63450. /**
  63451. * Called by the GPUParticleSystem to setup the update shader
  63452. * @param effect defines the update shader
  63453. */
  63454. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63455. effect.setVector3("direction1", this.direction1);
  63456. effect.setVector3("direction2", this.direction2);
  63457. };
  63458. /**
  63459. * Returns a string to use to update the GPU particles update shader
  63460. * @returns a string containng the defines string
  63461. */
  63462. PointParticleEmitter.prototype.getEffectDefines = function () {
  63463. return "#define POINTEMITTER";
  63464. };
  63465. /**
  63466. * Returns the string "PointParticleEmitter"
  63467. * @returns a string containing the class name
  63468. */
  63469. PointParticleEmitter.prototype.getClassName = function () {
  63470. return "PointParticleEmitter";
  63471. };
  63472. /**
  63473. * Serializes the particle system to a JSON object.
  63474. * @returns the JSON object
  63475. */
  63476. PointParticleEmitter.prototype.serialize = function () {
  63477. var serializationObject = {};
  63478. serializationObject.type = this.getClassName();
  63479. serializationObject.direction1 = this.direction1.asArray();
  63480. serializationObject.direction2 = this.direction2.asArray();
  63481. return serializationObject;
  63482. };
  63483. /**
  63484. * Parse properties from a JSON object
  63485. * @param serializationObject defines the JSON object
  63486. */
  63487. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63488. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63489. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63490. };
  63491. return PointParticleEmitter;
  63492. }());
  63493. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63494. })(BABYLON || (BABYLON = {}));
  63495. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  63496. var BABYLON;
  63497. (function (BABYLON) {
  63498. // Adds the parsers to the scene parsers.
  63499. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63500. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63501. if (!individualParser) {
  63502. return;
  63503. }
  63504. // Particles Systems
  63505. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63506. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63507. var parsedParticleSystem = parsedData.particleSystems[index];
  63508. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63509. }
  63510. }
  63511. });
  63512. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63513. if (parsedParticleSystem.activeParticleCount) {
  63514. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63515. return ps;
  63516. }
  63517. else {
  63518. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63519. return ps;
  63520. }
  63521. });
  63522. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63523. if (uniformsNames === void 0) { uniformsNames = []; }
  63524. if (samplers === void 0) { samplers = []; }
  63525. if (defines === void 0) { defines = ""; }
  63526. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63527. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63528. if (defines.indexOf(" BILLBOARD") === -1) {
  63529. defines += "\n#define BILLBOARD\n";
  63530. }
  63531. if (samplers.indexOf("diffuseSampler") === -1) {
  63532. samplers.push("diffuseSampler");
  63533. }
  63534. return this.createEffect({
  63535. vertex: "particles",
  63536. fragmentElement: fragmentName
  63537. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63538. };
  63539. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  63540. var results = new Array();
  63541. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63542. var particleSystem = this.getScene().particleSystems[index];
  63543. if (particleSystem.emitter === this) {
  63544. results.push(particleSystem);
  63545. }
  63546. }
  63547. return results;
  63548. };
  63549. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  63550. var results = new Array();
  63551. var descendants = this.getDescendants();
  63552. descendants.push(this);
  63553. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63554. var particleSystem = this.getScene().particleSystems[index];
  63555. var emitter = particleSystem.emitter;
  63556. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  63557. results.push(particleSystem);
  63558. }
  63559. }
  63560. return results;
  63561. };
  63562. })(BABYLON || (BABYLON = {}));
  63563. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  63564. var BABYLON;
  63565. (function (BABYLON) {
  63566. /**
  63567. * Type of sub emitter
  63568. */
  63569. var SubEmitterType;
  63570. (function (SubEmitterType) {
  63571. /**
  63572. * Attached to the particle over it's lifetime
  63573. */
  63574. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  63575. /**
  63576. * Created when the particle dies
  63577. */
  63578. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  63579. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  63580. /**
  63581. * Sub emitter class used to emit particles from an existing particle
  63582. */
  63583. var SubEmitter = /** @class */ (function () {
  63584. /**
  63585. * Creates a sub emitter
  63586. * @param particleSystem the particle system to be used by the sub emitter
  63587. */
  63588. function SubEmitter(
  63589. /**
  63590. * the particle system to be used by the sub emitter
  63591. */
  63592. particleSystem) {
  63593. this.particleSystem = particleSystem;
  63594. /**
  63595. * Type of the submitter (Default: END)
  63596. */
  63597. this.type = SubEmitterType.END;
  63598. /**
  63599. * 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)
  63600. * Note: This only is supported when using an emitter of type Mesh
  63601. */
  63602. this.inheritDirection = false;
  63603. /**
  63604. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  63605. */
  63606. this.inheritedVelocityAmount = 0;
  63607. // Create mesh as emitter to support rotation
  63608. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  63609. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  63610. }
  63611. // Automatically dispose of subemitter when system is disposed
  63612. particleSystem.onDisposeObservable.add(function () {
  63613. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  63614. particleSystem.emitter.dispose();
  63615. }
  63616. });
  63617. }
  63618. /**
  63619. * Clones the sub emitter
  63620. * @returns the cloned sub emitter
  63621. */
  63622. SubEmitter.prototype.clone = function () {
  63623. // Clone particle system
  63624. var emitter = this.particleSystem.emitter;
  63625. if (!emitter) {
  63626. emitter = new BABYLON.Vector3();
  63627. }
  63628. else if (emitter instanceof BABYLON.Vector3) {
  63629. emitter = emitter.clone();
  63630. }
  63631. else if (emitter instanceof BABYLON.AbstractMesh) {
  63632. emitter = new BABYLON.Mesh("", emitter.getScene());
  63633. emitter.isVisible = false;
  63634. }
  63635. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  63636. // Clone properties
  63637. clone.type = this.type;
  63638. clone.inheritDirection = this.inheritDirection;
  63639. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63640. clone.particleSystem._disposeEmitterOnDispose = true;
  63641. clone.particleSystem.disposeOnStop = true;
  63642. return clone;
  63643. };
  63644. /**
  63645. * Serialize current object to a JSON object
  63646. * @returns the serialized object
  63647. */
  63648. SubEmitter.prototype.serialize = function () {
  63649. var serializationObject = {};
  63650. serializationObject.type = this.type;
  63651. serializationObject.inheritDirection = this.inheritDirection;
  63652. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63653. serializationObject.particleSystem = this.particleSystem.serialize();
  63654. return serializationObject;
  63655. };
  63656. /**
  63657. * Creates a new SubEmitter from a serialized JSON version
  63658. * @param serializationObject defines the JSON object to read from
  63659. * @param scene defines the hosting scene
  63660. * @param rootUrl defines the rootUrl for data loading
  63661. * @returns a new SubEmitter
  63662. */
  63663. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  63664. var system = serializationObject.particleSystem;
  63665. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  63666. subEmitter.type = serializationObject.type;
  63667. subEmitter.inheritDirection = serializationObject.inheritDirection;
  63668. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  63669. subEmitter.particleSystem._isSubEmitter = true;
  63670. return subEmitter;
  63671. };
  63672. /** Release associated resources */
  63673. SubEmitter.prototype.dispose = function () {
  63674. this.particleSystem.dispose();
  63675. };
  63676. return SubEmitter;
  63677. }());
  63678. BABYLON.SubEmitter = SubEmitter;
  63679. })(BABYLON || (BABYLON = {}));
  63680. //# sourceMappingURL=babylon.subEmitter.js.map
  63681. var BABYLON;
  63682. (function (BABYLON) {
  63683. /**
  63684. * 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.
  63685. *
  63686. * This returned material effects how the mesh will look based on the code in the shaders.
  63687. *
  63688. * @see http://doc.babylonjs.com/how_to/shader_material
  63689. */
  63690. var ShaderMaterial = /** @class */ (function (_super) {
  63691. __extends(ShaderMaterial, _super);
  63692. /**
  63693. * Instantiate a new shader material.
  63694. * 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.
  63695. * This returned material effects how the mesh will look based on the code in the shaders.
  63696. * @see http://doc.babylonjs.com/how_to/shader_material
  63697. * @param name Define the name of the material in the scene
  63698. * @param scene Define the scene the material belongs to
  63699. * @param shaderPath Defines the route to the shader code in one of three ways:
  63700. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  63701. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  63702. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  63703. * @param options Define the options used to create the shader
  63704. */
  63705. function ShaderMaterial(name, scene, shaderPath, options) {
  63706. if (options === void 0) { options = {}; }
  63707. var _this = _super.call(this, name, scene) || this;
  63708. _this._textures = {};
  63709. _this._textureArrays = {};
  63710. _this._floats = {};
  63711. _this._ints = {};
  63712. _this._floatsArrays = {};
  63713. _this._colors3 = {};
  63714. _this._colors3Arrays = {};
  63715. _this._colors4 = {};
  63716. _this._vectors2 = {};
  63717. _this._vectors3 = {};
  63718. _this._vectors4 = {};
  63719. _this._matrices = {};
  63720. _this._matrices3x3 = {};
  63721. _this._matrices2x2 = {};
  63722. _this._vectors2Arrays = {};
  63723. _this._vectors3Arrays = {};
  63724. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  63725. _this._shaderPath = shaderPath;
  63726. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  63727. return _this;
  63728. }
  63729. /**
  63730. * Gets the current class name of the material e.g. "ShaderMaterial"
  63731. * Mainly use in serialization.
  63732. * @returns the class name
  63733. */
  63734. ShaderMaterial.prototype.getClassName = function () {
  63735. return "ShaderMaterial";
  63736. };
  63737. /**
  63738. * Specifies if the material will require alpha blending
  63739. * @returns a boolean specifying if alpha blending is needed
  63740. */
  63741. ShaderMaterial.prototype.needAlphaBlending = function () {
  63742. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  63743. };
  63744. /**
  63745. * Specifies if this material should be rendered in alpha test mode
  63746. * @returns a boolean specifying if an alpha test is needed.
  63747. */
  63748. ShaderMaterial.prototype.needAlphaTesting = function () {
  63749. return this._options.needAlphaTesting;
  63750. };
  63751. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  63752. if (this._options.uniforms.indexOf(uniformName) === -1) {
  63753. this._options.uniforms.push(uniformName);
  63754. }
  63755. };
  63756. /**
  63757. * Set a texture in the shader.
  63758. * @param name Define the name of the uniform samplers as defined in the shader
  63759. * @param texture Define the texture to bind to this sampler
  63760. * @return the material itself allowing "fluent" like uniform updates
  63761. */
  63762. ShaderMaterial.prototype.setTexture = function (name, texture) {
  63763. if (this._options.samplers.indexOf(name) === -1) {
  63764. this._options.samplers.push(name);
  63765. }
  63766. this._textures[name] = texture;
  63767. return this;
  63768. };
  63769. /**
  63770. * Set a texture array in the shader.
  63771. * @param name Define the name of the uniform sampler array as defined in the shader
  63772. * @param textures Define the list of textures to bind to this sampler
  63773. * @return the material itself allowing "fluent" like uniform updates
  63774. */
  63775. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  63776. if (this._options.samplers.indexOf(name) === -1) {
  63777. this._options.samplers.push(name);
  63778. }
  63779. this._checkUniform(name);
  63780. this._textureArrays[name] = textures;
  63781. return this;
  63782. };
  63783. /**
  63784. * Set a float in the shader.
  63785. * @param name Define the name of the uniform as defined in the shader
  63786. * @param value Define the value to give to the uniform
  63787. * @return the material itself allowing "fluent" like uniform updates
  63788. */
  63789. ShaderMaterial.prototype.setFloat = function (name, value) {
  63790. this._checkUniform(name);
  63791. this._floats[name] = value;
  63792. return this;
  63793. };
  63794. /**
  63795. * Set a int in the shader.
  63796. * @param name Define the name of the uniform as defined in the shader
  63797. * @param value Define the value to give to the uniform
  63798. * @return the material itself allowing "fluent" like uniform updates
  63799. */
  63800. ShaderMaterial.prototype.setInt = function (name, value) {
  63801. this._checkUniform(name);
  63802. this._ints[name] = value;
  63803. return this;
  63804. };
  63805. /**
  63806. * Set an array of floats in the shader.
  63807. * @param name Define the name of the uniform as defined in the shader
  63808. * @param value Define the value to give to the uniform
  63809. * @return the material itself allowing "fluent" like uniform updates
  63810. */
  63811. ShaderMaterial.prototype.setFloats = function (name, value) {
  63812. this._checkUniform(name);
  63813. this._floatsArrays[name] = value;
  63814. return this;
  63815. };
  63816. /**
  63817. * Set a vec3 in the shader from a Color3.
  63818. * @param name Define the name of the uniform as defined in the shader
  63819. * @param value Define the value to give to the uniform
  63820. * @return the material itself allowing "fluent" like uniform updates
  63821. */
  63822. ShaderMaterial.prototype.setColor3 = function (name, value) {
  63823. this._checkUniform(name);
  63824. this._colors3[name] = value;
  63825. return this;
  63826. };
  63827. /**
  63828. * Set a vec3 array in the shader from a Color3 array.
  63829. * @param name Define the name of the uniform as defined in the shader
  63830. * @param value Define the value to give to the uniform
  63831. * @return the material itself allowing "fluent" like uniform updates
  63832. */
  63833. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  63834. this._checkUniform(name);
  63835. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  63836. color.toArray(arr, arr.length);
  63837. return arr;
  63838. }, []);
  63839. return this;
  63840. };
  63841. /**
  63842. * Set a vec4 in the shader from a Color4.
  63843. * @param name Define the name of the uniform as defined in the shader
  63844. * @param value Define the value to give to the uniform
  63845. * @return the material itself allowing "fluent" like uniform updates
  63846. */
  63847. ShaderMaterial.prototype.setColor4 = function (name, value) {
  63848. this._checkUniform(name);
  63849. this._colors4[name] = value;
  63850. return this;
  63851. };
  63852. /**
  63853. * Set a vec2 in the shader from a Vector2.
  63854. * @param name Define the name of the uniform as defined in the shader
  63855. * @param value Define the value to give to the uniform
  63856. * @return the material itself allowing "fluent" like uniform updates
  63857. */
  63858. ShaderMaterial.prototype.setVector2 = function (name, value) {
  63859. this._checkUniform(name);
  63860. this._vectors2[name] = value;
  63861. return this;
  63862. };
  63863. /**
  63864. * Set a vec3 in the shader from a Vector3.
  63865. * @param name Define the name of the uniform as defined in the shader
  63866. * @param value Define the value to give to the uniform
  63867. * @return the material itself allowing "fluent" like uniform updates
  63868. */
  63869. ShaderMaterial.prototype.setVector3 = function (name, value) {
  63870. this._checkUniform(name);
  63871. this._vectors3[name] = value;
  63872. return this;
  63873. };
  63874. /**
  63875. * Set a vec4 in the shader from a Vector4.
  63876. * @param name Define the name of the uniform as defined in the shader
  63877. * @param value Define the value to give to the uniform
  63878. * @return the material itself allowing "fluent" like uniform updates
  63879. */
  63880. ShaderMaterial.prototype.setVector4 = function (name, value) {
  63881. this._checkUniform(name);
  63882. this._vectors4[name] = value;
  63883. return this;
  63884. };
  63885. /**
  63886. * Set a mat4 in the shader from a Matrix.
  63887. * @param name Define the name of the uniform as defined in the shader
  63888. * @param value Define the value to give to the uniform
  63889. * @return the material itself allowing "fluent" like uniform updates
  63890. */
  63891. ShaderMaterial.prototype.setMatrix = function (name, value) {
  63892. this._checkUniform(name);
  63893. this._matrices[name] = value;
  63894. return this;
  63895. };
  63896. /**
  63897. * Set a mat3 in the shader from a Float32Array.
  63898. * @param name Define the name of the uniform as defined in the shader
  63899. * @param value Define the value to give to the uniform
  63900. * @return the material itself allowing "fluent" like uniform updates
  63901. */
  63902. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  63903. this._checkUniform(name);
  63904. this._matrices3x3[name] = value;
  63905. return this;
  63906. };
  63907. /**
  63908. * Set a mat2 in the shader from a Float32Array.
  63909. * @param name Define the name of the uniform as defined in the shader
  63910. * @param value Define the value to give to the uniform
  63911. * @return the material itself allowing "fluent" like uniform updates
  63912. */
  63913. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  63914. this._checkUniform(name);
  63915. this._matrices2x2[name] = value;
  63916. return this;
  63917. };
  63918. /**
  63919. * Set a vec2 array in the shader from a number array.
  63920. * @param name Define the name of the uniform as defined in the shader
  63921. * @param value Define the value to give to the uniform
  63922. * @return the material itself allowing "fluent" like uniform updates
  63923. */
  63924. ShaderMaterial.prototype.setArray2 = function (name, value) {
  63925. this._checkUniform(name);
  63926. this._vectors2Arrays[name] = value;
  63927. return this;
  63928. };
  63929. /**
  63930. * Set a vec3 array in the shader from a number array.
  63931. * @param name Define the name of the uniform as defined in the shader
  63932. * @param value Define the value to give to the uniform
  63933. * @return the material itself allowing "fluent" like uniform updates
  63934. */
  63935. ShaderMaterial.prototype.setArray3 = function (name, value) {
  63936. this._checkUniform(name);
  63937. this._vectors3Arrays[name] = value;
  63938. return this;
  63939. };
  63940. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  63941. if (!mesh) {
  63942. return true;
  63943. }
  63944. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  63945. return false;
  63946. }
  63947. return false;
  63948. };
  63949. /**
  63950. * Checks if the material is ready to render the requested mesh
  63951. * @param mesh Define the mesh to render
  63952. * @param useInstances Define whether or not the material is used with instances
  63953. * @returns true if ready, otherwise false
  63954. */
  63955. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  63956. var scene = this.getScene();
  63957. var engine = scene.getEngine();
  63958. if (!this.checkReadyOnEveryCall) {
  63959. if (this._renderId === scene.getRenderId()) {
  63960. if (this._checkCache(scene, mesh, useInstances)) {
  63961. return true;
  63962. }
  63963. }
  63964. }
  63965. // Instances
  63966. var defines = [];
  63967. var attribs = [];
  63968. var fallbacks = new BABYLON.EffectFallbacks();
  63969. for (var index = 0; index < this._options.defines.length; index++) {
  63970. defines.push(this._options.defines[index]);
  63971. }
  63972. for (var index = 0; index < this._options.attributes.length; index++) {
  63973. attribs.push(this._options.attributes[index]);
  63974. }
  63975. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  63976. attribs.push(BABYLON.VertexBuffer.ColorKind);
  63977. defines.push("#define VERTEXCOLOR");
  63978. }
  63979. if (useInstances) {
  63980. defines.push("#define INSTANCES");
  63981. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  63982. }
  63983. // Bones
  63984. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63985. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63986. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63987. if (mesh.numBoneInfluencers > 4) {
  63988. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63989. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63990. }
  63991. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63992. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63993. fallbacks.addCPUSkinningFallback(0, mesh);
  63994. if (this._options.uniforms.indexOf("mBones") === -1) {
  63995. this._options.uniforms.push("mBones");
  63996. }
  63997. }
  63998. else {
  63999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64000. }
  64001. // Textures
  64002. for (var name in this._textures) {
  64003. if (!this._textures[name].isReady()) {
  64004. return false;
  64005. }
  64006. }
  64007. // Alpha test
  64008. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64009. defines.push("#define ALPHATEST");
  64010. }
  64011. var previousEffect = this._effect;
  64012. var join = defines.join("\n");
  64013. this._effect = engine.createEffect(this._shaderPath, {
  64014. attributes: attribs,
  64015. uniformsNames: this._options.uniforms,
  64016. uniformBuffersNames: this._options.uniformBuffers,
  64017. samplers: this._options.samplers,
  64018. defines: join,
  64019. fallbacks: fallbacks,
  64020. onCompiled: this.onCompiled,
  64021. onError: this.onError
  64022. }, engine);
  64023. if (!this._effect.isReady()) {
  64024. return false;
  64025. }
  64026. if (previousEffect !== this._effect) {
  64027. scene.resetCachedMaterial();
  64028. }
  64029. this._renderId = scene.getRenderId();
  64030. return true;
  64031. };
  64032. /**
  64033. * Binds the world matrix to the material
  64034. * @param world defines the world transformation matrix
  64035. */
  64036. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64037. var scene = this.getScene();
  64038. if (!this._effect) {
  64039. return;
  64040. }
  64041. if (this._options.uniforms.indexOf("world") !== -1) {
  64042. this._effect.setMatrix("world", world);
  64043. }
  64044. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64045. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64046. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64047. }
  64048. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64049. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64050. }
  64051. };
  64052. /**
  64053. * Binds the material to the mesh
  64054. * @param world defines the world transformation matrix
  64055. * @param mesh defines the mesh to bind the material to
  64056. */
  64057. ShaderMaterial.prototype.bind = function (world, mesh) {
  64058. // Std values
  64059. this.bindOnlyWorldMatrix(world);
  64060. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64061. if (this._options.uniforms.indexOf("view") !== -1) {
  64062. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64063. }
  64064. if (this._options.uniforms.indexOf("projection") !== -1) {
  64065. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64066. }
  64067. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64068. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64069. }
  64070. // Bones
  64071. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64072. var name;
  64073. // Texture
  64074. for (name in this._textures) {
  64075. this._effect.setTexture(name, this._textures[name]);
  64076. }
  64077. // Texture arrays
  64078. for (name in this._textureArrays) {
  64079. this._effect.setTextureArray(name, this._textureArrays[name]);
  64080. }
  64081. // Int
  64082. for (name in this._ints) {
  64083. this._effect.setInt(name, this._ints[name]);
  64084. }
  64085. // Float
  64086. for (name in this._floats) {
  64087. this._effect.setFloat(name, this._floats[name]);
  64088. }
  64089. // Floats
  64090. for (name in this._floatsArrays) {
  64091. this._effect.setArray(name, this._floatsArrays[name]);
  64092. }
  64093. // Color3
  64094. for (name in this._colors3) {
  64095. this._effect.setColor3(name, this._colors3[name]);
  64096. }
  64097. for (name in this._colors3Arrays) {
  64098. this._effect.setArray3(name, this._colors3Arrays[name]);
  64099. }
  64100. // Color4
  64101. for (name in this._colors4) {
  64102. var color = this._colors4[name];
  64103. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64104. }
  64105. // Vector2
  64106. for (name in this._vectors2) {
  64107. this._effect.setVector2(name, this._vectors2[name]);
  64108. }
  64109. // Vector3
  64110. for (name in this._vectors3) {
  64111. this._effect.setVector3(name, this._vectors3[name]);
  64112. }
  64113. // Vector4
  64114. for (name in this._vectors4) {
  64115. this._effect.setVector4(name, this._vectors4[name]);
  64116. }
  64117. // Matrix
  64118. for (name in this._matrices) {
  64119. this._effect.setMatrix(name, this._matrices[name]);
  64120. }
  64121. // Matrix 3x3
  64122. for (name in this._matrices3x3) {
  64123. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64124. }
  64125. // Matrix 2x2
  64126. for (name in this._matrices2x2) {
  64127. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64128. }
  64129. // Vector2Array
  64130. for (name in this._vectors2Arrays) {
  64131. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64132. }
  64133. // Vector3Array
  64134. for (name in this._vectors3Arrays) {
  64135. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64136. }
  64137. }
  64138. this._afterBind(mesh);
  64139. };
  64140. /**
  64141. * Gets the active textures from the material
  64142. * @returns an array of textures
  64143. */
  64144. ShaderMaterial.prototype.getActiveTextures = function () {
  64145. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64146. for (var name in this._textures) {
  64147. activeTextures.push(this._textures[name]);
  64148. }
  64149. for (var name in this._textureArrays) {
  64150. var array = this._textureArrays[name];
  64151. for (var index = 0; index < array.length; index++) {
  64152. activeTextures.push(array[index]);
  64153. }
  64154. }
  64155. return activeTextures;
  64156. };
  64157. /**
  64158. * Specifies if the material uses a texture
  64159. * @param texture defines the texture to check against the material
  64160. * @returns a boolean specifying if the material uses the texture
  64161. */
  64162. ShaderMaterial.prototype.hasTexture = function (texture) {
  64163. if (_super.prototype.hasTexture.call(this, texture)) {
  64164. return true;
  64165. }
  64166. for (var name in this._textures) {
  64167. if (this._textures[name] === texture) {
  64168. return true;
  64169. }
  64170. }
  64171. for (var name in this._textureArrays) {
  64172. var array = this._textureArrays[name];
  64173. for (var index = 0; index < array.length; index++) {
  64174. if (array[index] === texture) {
  64175. return true;
  64176. }
  64177. }
  64178. }
  64179. return false;
  64180. };
  64181. /**
  64182. * Makes a duplicate of the material, and gives it a new name
  64183. * @param name defines the new name for the duplicated material
  64184. * @returns the cloned material
  64185. */
  64186. ShaderMaterial.prototype.clone = function (name) {
  64187. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64188. return newShaderMaterial;
  64189. };
  64190. /**
  64191. * Disposes the material
  64192. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64193. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64194. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64195. */
  64196. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64197. if (forceDisposeTextures) {
  64198. var name;
  64199. for (name in this._textures) {
  64200. this._textures[name].dispose();
  64201. }
  64202. for (name in this._textureArrays) {
  64203. var array = this._textureArrays[name];
  64204. for (var index = 0; index < array.length; index++) {
  64205. array[index].dispose();
  64206. }
  64207. }
  64208. }
  64209. this._textures = {};
  64210. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64211. };
  64212. /**
  64213. * Serializes this material in a JSON representation
  64214. * @returns the serialized material object
  64215. */
  64216. ShaderMaterial.prototype.serialize = function () {
  64217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64218. serializationObject.customType = "BABYLON.ShaderMaterial";
  64219. serializationObject.options = this._options;
  64220. serializationObject.shaderPath = this._shaderPath;
  64221. var name;
  64222. // Texture
  64223. serializationObject.textures = {};
  64224. for (name in this._textures) {
  64225. serializationObject.textures[name] = this._textures[name].serialize();
  64226. }
  64227. // Texture arrays
  64228. serializationObject.textureArrays = {};
  64229. for (name in this._textureArrays) {
  64230. serializationObject.textureArrays[name] = [];
  64231. var array = this._textureArrays[name];
  64232. for (var index = 0; index < array.length; index++) {
  64233. serializationObject.textureArrays[name].push(array[index].serialize());
  64234. }
  64235. }
  64236. // Float
  64237. serializationObject.floats = {};
  64238. for (name in this._floats) {
  64239. serializationObject.floats[name] = this._floats[name];
  64240. }
  64241. // Float s
  64242. serializationObject.FloatArrays = {};
  64243. for (name in this._floatsArrays) {
  64244. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64245. }
  64246. // Color3
  64247. serializationObject.colors3 = {};
  64248. for (name in this._colors3) {
  64249. serializationObject.colors3[name] = this._colors3[name].asArray();
  64250. }
  64251. // Color3 array
  64252. serializationObject.colors3Arrays = {};
  64253. for (name in this._colors3Arrays) {
  64254. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64255. }
  64256. // Color4
  64257. serializationObject.colors4 = {};
  64258. for (name in this._colors4) {
  64259. serializationObject.colors4[name] = this._colors4[name].asArray();
  64260. }
  64261. // Vector2
  64262. serializationObject.vectors2 = {};
  64263. for (name in this._vectors2) {
  64264. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64265. }
  64266. // Vector3
  64267. serializationObject.vectors3 = {};
  64268. for (name in this._vectors3) {
  64269. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64270. }
  64271. // Vector4
  64272. serializationObject.vectors4 = {};
  64273. for (name in this._vectors4) {
  64274. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64275. }
  64276. // Matrix
  64277. serializationObject.matrices = {};
  64278. for (name in this._matrices) {
  64279. serializationObject.matrices[name] = this._matrices[name].asArray();
  64280. }
  64281. // Matrix 3x3
  64282. serializationObject.matrices3x3 = {};
  64283. for (name in this._matrices3x3) {
  64284. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64285. }
  64286. // Matrix 2x2
  64287. serializationObject.matrices2x2 = {};
  64288. for (name in this._matrices2x2) {
  64289. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64290. }
  64291. // Vector2Array
  64292. serializationObject.vectors2Arrays = {};
  64293. for (name in this._vectors2Arrays) {
  64294. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64295. }
  64296. // Vector3Array
  64297. serializationObject.vectors3Arrays = {};
  64298. for (name in this._vectors3Arrays) {
  64299. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64300. }
  64301. return serializationObject;
  64302. };
  64303. /**
  64304. * Creates a shader material from parsed shader material data
  64305. * @param source defines the JSON represnetation of the material
  64306. * @param scene defines the hosting scene
  64307. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64308. * @returns a new material
  64309. */
  64310. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64311. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64312. var name;
  64313. // Texture
  64314. for (name in source.textures) {
  64315. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64316. }
  64317. // Texture arrays
  64318. for (name in source.textureArrays) {
  64319. var array = source.textureArrays[name];
  64320. var textureArray = new Array();
  64321. for (var index = 0; index < array.length; index++) {
  64322. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64323. }
  64324. material.setTextureArray(name, textureArray);
  64325. }
  64326. // Float
  64327. for (name in source.floats) {
  64328. material.setFloat(name, source.floats[name]);
  64329. }
  64330. // Float s
  64331. for (name in source.floatsArrays) {
  64332. material.setFloats(name, source.floatsArrays[name]);
  64333. }
  64334. // Color3
  64335. for (name in source.colors3) {
  64336. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64337. }
  64338. // Color3 arrays
  64339. for (name in source.colors3Arrays) {
  64340. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64341. if (i % 3 === 0) {
  64342. arr.push([num]);
  64343. }
  64344. else {
  64345. arr[arr.length - 1].push(num);
  64346. }
  64347. return arr;
  64348. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64349. material.setColor3Array(name, colors);
  64350. }
  64351. // Color4
  64352. for (name in source.colors4) {
  64353. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64354. }
  64355. // Vector2
  64356. for (name in source.vectors2) {
  64357. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64358. }
  64359. // Vector3
  64360. for (name in source.vectors3) {
  64361. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64362. }
  64363. // Vector4
  64364. for (name in source.vectors4) {
  64365. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64366. }
  64367. // Matrix
  64368. for (name in source.matrices) {
  64369. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64370. }
  64371. // Matrix 3x3
  64372. for (name in source.matrices3x3) {
  64373. material.setMatrix3x3(name, source.matrices3x3[name]);
  64374. }
  64375. // Matrix 2x2
  64376. for (name in source.matrices2x2) {
  64377. material.setMatrix2x2(name, source.matrices2x2[name]);
  64378. }
  64379. // Vector2Array
  64380. for (name in source.vectors2Arrays) {
  64381. material.setArray2(name, source.vectors2Arrays[name]);
  64382. }
  64383. // Vector3Array
  64384. for (name in source.vectors3Arrays) {
  64385. material.setArray3(name, source.vectors3Arrays[name]);
  64386. }
  64387. return material;
  64388. };
  64389. return ShaderMaterial;
  64390. }(BABYLON.Material));
  64391. BABYLON.ShaderMaterial = ShaderMaterial;
  64392. })(BABYLON || (BABYLON = {}));
  64393. //# sourceMappingURL=babylon.shaderMaterial.js.map
  64394. var BABYLON;
  64395. (function (BABYLON) {
  64396. /**
  64397. * Mesh representing the gorund
  64398. */
  64399. var GroundMesh = /** @class */ (function (_super) {
  64400. __extends(GroundMesh, _super);
  64401. function GroundMesh(name, scene) {
  64402. var _this = _super.call(this, name, scene) || this;
  64403. /** If octree should be generated */
  64404. _this.generateOctree = false;
  64405. return _this;
  64406. }
  64407. /**
  64408. * "GroundMesh"
  64409. * @returns "GroundMesh"
  64410. */
  64411. GroundMesh.prototype.getClassName = function () {
  64412. return "GroundMesh";
  64413. };
  64414. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64415. /**
  64416. * The minimum of x and y subdivisions
  64417. */
  64418. get: function () {
  64419. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64420. },
  64421. enumerable: true,
  64422. configurable: true
  64423. });
  64424. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64425. /**
  64426. * X subdivisions
  64427. */
  64428. get: function () {
  64429. return this._subdivisionsX;
  64430. },
  64431. enumerable: true,
  64432. configurable: true
  64433. });
  64434. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64435. /**
  64436. * Y subdivisions
  64437. */
  64438. get: function () {
  64439. return this._subdivisionsY;
  64440. },
  64441. enumerable: true,
  64442. configurable: true
  64443. });
  64444. /**
  64445. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64446. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64447. * @param chunksCount the number of subdivisions for x and y
  64448. * @param octreeBlocksSize (Default: 32)
  64449. */
  64450. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64451. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64452. this._subdivisionsX = chunksCount;
  64453. this._subdivisionsY = chunksCount;
  64454. this.subdivide(chunksCount);
  64455. // Call the octree system optimization if it is defined.
  64456. var thisAsAny = this;
  64457. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64458. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64459. }
  64460. };
  64461. /**
  64462. * Returns a height (y) value in the Worl system :
  64463. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64464. * @param x x coordinate
  64465. * @param z z coordinate
  64466. * @returns the ground y position if (x, z) are outside the ground surface.
  64467. */
  64468. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64469. var world = this.getWorldMatrix();
  64470. var invMat = BABYLON.Tmp.Matrix[5];
  64471. world.invertToRef(invMat);
  64472. var tmpVect = BABYLON.Tmp.Vector3[8];
  64473. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64474. x = tmpVect.x;
  64475. z = tmpVect.z;
  64476. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64477. return this.position.y;
  64478. }
  64479. if (!this._heightQuads || this._heightQuads.length == 0) {
  64480. this._initHeightQuads();
  64481. this._computeHeightQuads();
  64482. }
  64483. var facet = this._getFacetAt(x, z);
  64484. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64485. // return y in the World system
  64486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64487. return tmpVect.y;
  64488. };
  64489. /**
  64490. * Returns a normalized vector (Vector3) orthogonal to the ground
  64491. * at the ground coordinates (x, z) expressed in the World system.
  64492. * @param x x coordinate
  64493. * @param z z coordinate
  64494. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64495. */
  64496. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64497. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64498. this.getNormalAtCoordinatesToRef(x, z, normal);
  64499. return normal;
  64500. };
  64501. /**
  64502. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64503. * at the ground coordinates (x, z) expressed in the World system.
  64504. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64505. * @param x x coordinate
  64506. * @param z z coordinate
  64507. * @param ref vector to store the result
  64508. * @returns the GroundMesh.
  64509. */
  64510. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64511. var world = this.getWorldMatrix();
  64512. var tmpMat = BABYLON.Tmp.Matrix[5];
  64513. world.invertToRef(tmpMat);
  64514. var tmpVect = BABYLON.Tmp.Vector3[8];
  64515. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64516. x = tmpVect.x;
  64517. z = tmpVect.z;
  64518. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64519. return this;
  64520. }
  64521. if (!this._heightQuads || this._heightQuads.length == 0) {
  64522. this._initHeightQuads();
  64523. this._computeHeightQuads();
  64524. }
  64525. var facet = this._getFacetAt(x, z);
  64526. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64527. return this;
  64528. };
  64529. /**
  64530. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  64531. * if the ground has been updated.
  64532. * This can be used in the render loop.
  64533. * @returns the GroundMesh.
  64534. */
  64535. GroundMesh.prototype.updateCoordinateHeights = function () {
  64536. if (!this._heightQuads || this._heightQuads.length == 0) {
  64537. this._initHeightQuads();
  64538. }
  64539. this._computeHeightQuads();
  64540. return this;
  64541. };
  64542. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  64543. GroundMesh.prototype._getFacetAt = function (x, z) {
  64544. // retrieve col and row from x, z coordinates in the ground local system
  64545. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  64546. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  64547. var quad = this._heightQuads[row * this._subdivisionsX + col];
  64548. var facet;
  64549. if (z < quad.slope.x * x + quad.slope.y) {
  64550. facet = quad.facet1;
  64551. }
  64552. else {
  64553. facet = quad.facet2;
  64554. }
  64555. return facet;
  64556. };
  64557. // Creates and populates the heightMap array with "facet" elements :
  64558. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  64559. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64560. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64561. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64562. // Returns the GroundMesh.
  64563. GroundMesh.prototype._initHeightQuads = function () {
  64564. var subdivisionsX = this._subdivisionsX;
  64565. var subdivisionsY = this._subdivisionsY;
  64566. this._heightQuads = new Array();
  64567. for (var row = 0; row < subdivisionsY; row++) {
  64568. for (var col = 0; col < subdivisionsX; col++) {
  64569. 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) };
  64570. this._heightQuads[row * subdivisionsX + col] = quad;
  64571. }
  64572. }
  64573. return this;
  64574. };
  64575. // Compute each quad element values and update the the heightMap array :
  64576. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64577. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64578. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64579. // Returns the GroundMesh.
  64580. GroundMesh.prototype._computeHeightQuads = function () {
  64581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64582. if (!positions) {
  64583. return this;
  64584. }
  64585. var v1 = BABYLON.Tmp.Vector3[3];
  64586. var v2 = BABYLON.Tmp.Vector3[2];
  64587. var v3 = BABYLON.Tmp.Vector3[1];
  64588. var v4 = BABYLON.Tmp.Vector3[0];
  64589. var v1v2 = BABYLON.Tmp.Vector3[4];
  64590. var v1v3 = BABYLON.Tmp.Vector3[5];
  64591. var v1v4 = BABYLON.Tmp.Vector3[6];
  64592. var norm1 = BABYLON.Tmp.Vector3[7];
  64593. var norm2 = BABYLON.Tmp.Vector3[8];
  64594. var i = 0;
  64595. var j = 0;
  64596. var k = 0;
  64597. var cd = 0; // 2D slope coefficient : z = cd * x + h
  64598. var h = 0;
  64599. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  64600. var d2 = 0;
  64601. var subdivisionsX = this._subdivisionsX;
  64602. var subdivisionsY = this._subdivisionsY;
  64603. for (var row = 0; row < subdivisionsY; row++) {
  64604. for (var col = 0; col < subdivisionsX; col++) {
  64605. i = col * 3;
  64606. j = row * (subdivisionsX + 1) * 3;
  64607. k = (row + 1) * (subdivisionsX + 1) * 3;
  64608. v1.x = positions[j + i];
  64609. v1.y = positions[j + i + 1];
  64610. v1.z = positions[j + i + 2];
  64611. v2.x = positions[j + i + 3];
  64612. v2.y = positions[j + i + 4];
  64613. v2.z = positions[j + i + 5];
  64614. v3.x = positions[k + i];
  64615. v3.y = positions[k + i + 1];
  64616. v3.z = positions[k + i + 2];
  64617. v4.x = positions[k + i + 3];
  64618. v4.y = positions[k + i + 4];
  64619. v4.z = positions[k + i + 5];
  64620. // 2D slope V1V4
  64621. cd = (v4.z - v1.z) / (v4.x - v1.x);
  64622. h = v1.z - cd * v1.x; // v1 belongs to the slope
  64623. // facet equations :
  64624. // we compute each facet normal vector
  64625. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  64626. // we compute the value d by applying the equation to v1 which belongs to the plane
  64627. // then we store the facet equation in a Vector4
  64628. v2.subtractToRef(v1, v1v2);
  64629. v3.subtractToRef(v1, v1v3);
  64630. v4.subtractToRef(v1, v1v4);
  64631. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  64632. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  64633. norm1.normalize();
  64634. norm2.normalize();
  64635. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  64636. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  64637. var quad = this._heightQuads[row * subdivisionsX + col];
  64638. quad.slope.copyFromFloats(cd, h);
  64639. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  64640. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  64641. }
  64642. }
  64643. return this;
  64644. };
  64645. /**
  64646. * Serializes this ground mesh
  64647. * @param serializationObject object to write serialization to
  64648. */
  64649. GroundMesh.prototype.serialize = function (serializationObject) {
  64650. _super.prototype.serialize.call(this, serializationObject);
  64651. serializationObject.subdivisionsX = this._subdivisionsX;
  64652. serializationObject.subdivisionsY = this._subdivisionsY;
  64653. serializationObject.minX = this._minX;
  64654. serializationObject.maxX = this._maxX;
  64655. serializationObject.minZ = this._minZ;
  64656. serializationObject.maxZ = this._maxZ;
  64657. serializationObject.width = this._width;
  64658. serializationObject.height = this._height;
  64659. };
  64660. /**
  64661. * Parses a serialized ground mesh
  64662. * @param parsedMesh the serialized mesh
  64663. * @param scene the scene to create the ground mesh in
  64664. * @returns the created ground mesh
  64665. */
  64666. GroundMesh.Parse = function (parsedMesh, scene) {
  64667. var result = new GroundMesh(parsedMesh.name, scene);
  64668. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  64669. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  64670. result._minX = parsedMesh.minX;
  64671. result._maxX = parsedMesh.maxX;
  64672. result._minZ = parsedMesh.minZ;
  64673. result._maxZ = parsedMesh.maxZ;
  64674. result._width = parsedMesh.width;
  64675. result._height = parsedMesh.height;
  64676. return result;
  64677. };
  64678. return GroundMesh;
  64679. }(BABYLON.Mesh));
  64680. BABYLON.GroundMesh = GroundMesh;
  64681. })(BABYLON || (BABYLON = {}));
  64682. //# sourceMappingURL=babylon.groundMesh.js.map
  64683. var BABYLON;
  64684. (function (BABYLON) {
  64685. /**
  64686. * Creates an instance based on a source mesh.
  64687. */
  64688. var InstancedMesh = /** @class */ (function (_super) {
  64689. __extends(InstancedMesh, _super);
  64690. function InstancedMesh(name, source) {
  64691. var _this = _super.call(this, name, source.getScene()) || this;
  64692. /** @hidden */
  64693. _this._indexInSourceMeshInstanceArray = -1;
  64694. source.addInstance(_this);
  64695. _this._sourceMesh = source;
  64696. _this.position.copyFrom(source.position);
  64697. _this.rotation.copyFrom(source.rotation);
  64698. _this.scaling.copyFrom(source.scaling);
  64699. if (source.rotationQuaternion) {
  64700. _this.rotationQuaternion = source.rotationQuaternion.clone();
  64701. }
  64702. _this.infiniteDistance = source.infiniteDistance;
  64703. _this.setPivotMatrix(source.getPivotMatrix());
  64704. _this.refreshBoundingInfo();
  64705. _this._syncSubMeshes();
  64706. return _this;
  64707. }
  64708. /**
  64709. * Returns the string "InstancedMesh".
  64710. */
  64711. InstancedMesh.prototype.getClassName = function () {
  64712. return "InstancedMesh";
  64713. };
  64714. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  64715. // Methods
  64716. /**
  64717. * If the source mesh receives shadows
  64718. */
  64719. get: function () {
  64720. return this._sourceMesh.receiveShadows;
  64721. },
  64722. enumerable: true,
  64723. configurable: true
  64724. });
  64725. Object.defineProperty(InstancedMesh.prototype, "material", {
  64726. /**
  64727. * The material of the source mesh
  64728. */
  64729. get: function () {
  64730. return this._sourceMesh.material;
  64731. },
  64732. enumerable: true,
  64733. configurable: true
  64734. });
  64735. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  64736. /**
  64737. * Visibility of the source mesh
  64738. */
  64739. get: function () {
  64740. return this._sourceMesh.visibility;
  64741. },
  64742. enumerable: true,
  64743. configurable: true
  64744. });
  64745. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  64746. /**
  64747. * Skeleton of the source mesh
  64748. */
  64749. get: function () {
  64750. return this._sourceMesh.skeleton;
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  64756. /**
  64757. * Rendering ground id of the source mesh
  64758. */
  64759. get: function () {
  64760. return this._sourceMesh.renderingGroupId;
  64761. },
  64762. set: function (value) {
  64763. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  64764. return;
  64765. }
  64766. //no-op with warning
  64767. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  64768. },
  64769. enumerable: true,
  64770. configurable: true
  64771. });
  64772. /**
  64773. * Returns the total number of vertices (integer).
  64774. */
  64775. InstancedMesh.prototype.getTotalVertices = function () {
  64776. return this._sourceMesh.getTotalVertices();
  64777. };
  64778. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  64779. /**
  64780. * The source mesh of the instance
  64781. */
  64782. get: function () {
  64783. return this._sourceMesh;
  64784. },
  64785. enumerable: true,
  64786. configurable: true
  64787. });
  64788. /**
  64789. * Is this node ready to be used/rendered
  64790. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  64791. * @return {boolean} is it ready
  64792. */
  64793. InstancedMesh.prototype.isReady = function (completeCheck) {
  64794. if (completeCheck === void 0) { completeCheck = false; }
  64795. return this._sourceMesh.isReady(completeCheck, true);
  64796. };
  64797. /**
  64798. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  64799. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  64800. * @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.
  64801. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  64802. */
  64803. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  64804. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  64805. };
  64806. /**
  64807. * Sets the vertex data of the mesh geometry for the requested `kind`.
  64808. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  64809. * The `data` are either a numeric array either a Float32Array.
  64810. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  64811. * 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).
  64812. * Note that a new underlying VertexBuffer object is created each call.
  64813. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  64814. *
  64815. * Possible `kind` values :
  64816. * - BABYLON.VertexBuffer.PositionKind
  64817. * - BABYLON.VertexBuffer.UVKind
  64818. * - BABYLON.VertexBuffer.UV2Kind
  64819. * - BABYLON.VertexBuffer.UV3Kind
  64820. * - BABYLON.VertexBuffer.UV4Kind
  64821. * - BABYLON.VertexBuffer.UV5Kind
  64822. * - BABYLON.VertexBuffer.UV6Kind
  64823. * - BABYLON.VertexBuffer.ColorKind
  64824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64828. *
  64829. * Returns the Mesh.
  64830. */
  64831. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  64832. if (this.sourceMesh) {
  64833. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  64834. }
  64835. return this.sourceMesh;
  64836. };
  64837. /**
  64838. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  64839. * If the mesh has no geometry, it is simply returned as it is.
  64840. * The `data` are either a numeric array either a Float32Array.
  64841. * No new underlying VertexBuffer object is created.
  64842. * 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.
  64843. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  64844. *
  64845. * Possible `kind` values :
  64846. * - BABYLON.VertexBuffer.PositionKind
  64847. * - BABYLON.VertexBuffer.UVKind
  64848. * - BABYLON.VertexBuffer.UV2Kind
  64849. * - BABYLON.VertexBuffer.UV3Kind
  64850. * - BABYLON.VertexBuffer.UV4Kind
  64851. * - BABYLON.VertexBuffer.UV5Kind
  64852. * - BABYLON.VertexBuffer.UV6Kind
  64853. * - BABYLON.VertexBuffer.ColorKind
  64854. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64855. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64856. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64857. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64858. *
  64859. * Returns the Mesh.
  64860. */
  64861. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  64862. if (this.sourceMesh) {
  64863. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  64864. }
  64865. return this.sourceMesh;
  64866. };
  64867. /**
  64868. * Sets the mesh indices.
  64869. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  64870. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  64871. * This method creates a new index buffer each call.
  64872. * Returns the Mesh.
  64873. */
  64874. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  64875. if (totalVertices === void 0) { totalVertices = null; }
  64876. if (this.sourceMesh) {
  64877. this.sourceMesh.setIndices(indices, totalVertices);
  64878. }
  64879. return this.sourceMesh;
  64880. };
  64881. /**
  64882. * Boolean : True if the mesh owns the requested kind of data.
  64883. */
  64884. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  64885. return this._sourceMesh.isVerticesDataPresent(kind);
  64886. };
  64887. /**
  64888. * Returns an array of indices (IndicesArray).
  64889. */
  64890. InstancedMesh.prototype.getIndices = function () {
  64891. return this._sourceMesh.getIndices();
  64892. };
  64893. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  64894. get: function () {
  64895. return this._sourceMesh._positions;
  64896. },
  64897. enumerable: true,
  64898. configurable: true
  64899. });
  64900. /**
  64901. * Sets a new updated BoundingInfo to the mesh.
  64902. * @returns the mesh.
  64903. */
  64904. InstancedMesh.prototype.refreshBoundingInfo = function () {
  64905. var meshBB = this._sourceMesh.getBoundingInfo();
  64906. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  64907. this._updateBoundingInfo();
  64908. return this;
  64909. };
  64910. /** @hidden */
  64911. InstancedMesh.prototype._preActivate = function () {
  64912. if (this._currentLOD) {
  64913. this._currentLOD._preActivate();
  64914. }
  64915. return this;
  64916. };
  64917. /** @hidden */
  64918. InstancedMesh.prototype._activate = function (renderId) {
  64919. if (this._currentLOD) {
  64920. this._currentLOD._registerInstanceForRenderId(this, renderId);
  64921. }
  64922. return this;
  64923. };
  64924. /**
  64925. * Returns the current associated LOD AbstractMesh.
  64926. */
  64927. InstancedMesh.prototype.getLOD = function (camera) {
  64928. if (!camera) {
  64929. return this;
  64930. }
  64931. var boundingInfo = this.getBoundingInfo();
  64932. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  64933. if (this._currentLOD === this.sourceMesh) {
  64934. return this;
  64935. }
  64936. return this._currentLOD;
  64937. };
  64938. /** @hidden */
  64939. InstancedMesh.prototype._syncSubMeshes = function () {
  64940. this.releaseSubMeshes();
  64941. if (this._sourceMesh.subMeshes) {
  64942. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  64943. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  64944. }
  64945. }
  64946. return this;
  64947. };
  64948. /** @hidden */
  64949. InstancedMesh.prototype._generatePointsArray = function () {
  64950. return this._sourceMesh._generatePointsArray();
  64951. };
  64952. /**
  64953. * Creates a new InstancedMesh from the current mesh.
  64954. * - name (string) : the cloned mesh name
  64955. * - newParent (optional Node) : the optional Node to parent the clone to.
  64956. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  64957. *
  64958. * Returns the clone.
  64959. */
  64960. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  64961. var result = this._sourceMesh.createInstance(name);
  64962. // Deep copy
  64963. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  64964. // Bounding info
  64965. this.refreshBoundingInfo();
  64966. // Parent
  64967. if (newParent) {
  64968. result.parent = newParent;
  64969. }
  64970. if (!doNotCloneChildren) {
  64971. // Children
  64972. for (var index = 0; index < this.getScene().meshes.length; index++) {
  64973. var mesh = this.getScene().meshes[index];
  64974. if (mesh.parent === this) {
  64975. mesh.clone(mesh.name, result);
  64976. }
  64977. }
  64978. }
  64979. result.computeWorldMatrix(true);
  64980. return result;
  64981. };
  64982. /**
  64983. * Disposes the InstancedMesh.
  64984. * Returns nothing.
  64985. */
  64986. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  64987. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  64988. // Remove from mesh
  64989. this._sourceMesh.removeInstance(this);
  64990. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  64991. };
  64992. return InstancedMesh;
  64993. }(BABYLON.AbstractMesh));
  64994. BABYLON.InstancedMesh = InstancedMesh;
  64995. })(BABYLON || (BABYLON = {}));
  64996. //# sourceMappingURL=babylon.instancedMesh.js.map
  64997. var BABYLON;
  64998. (function (BABYLON) {
  64999. /**
  65000. * Line mesh
  65001. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65002. */
  65003. var LinesMesh = /** @class */ (function (_super) {
  65004. __extends(LinesMesh, _super);
  65005. /**
  65006. * Creates a new LinesMesh
  65007. * @param name defines the name
  65008. * @param scene defines the hosting scene
  65009. * @param parent defines the parent mesh if any
  65010. * @param source defines the optional source LinesMesh used to clone data from
  65011. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65012. * When false, achieved by calling a clone(), also passing False.
  65013. * This will make creation of children, recursive.
  65014. * @param useVertexColor defines if this LinesMesh supports vertex color
  65015. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65016. */
  65017. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65018. /**
  65019. * If vertex color should be applied to the mesh
  65020. */
  65021. useVertexColor,
  65022. /**
  65023. * If vertex alpha should be applied to the mesh
  65024. */
  65025. useVertexAlpha) {
  65026. if (scene === void 0) { scene = null; }
  65027. if (parent === void 0) { parent = null; }
  65028. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65029. _this.useVertexColor = useVertexColor;
  65030. _this.useVertexAlpha = useVertexAlpha;
  65031. /**
  65032. * Color of the line (Default: White)
  65033. */
  65034. _this.color = new BABYLON.Color3(1, 1, 1);
  65035. /**
  65036. * Alpha of the line (Default: 1)
  65037. */
  65038. _this.alpha = 1;
  65039. if (source) {
  65040. _this.color = source.color.clone();
  65041. _this.alpha = source.alpha;
  65042. _this.useVertexColor = source.useVertexColor;
  65043. _this.useVertexAlpha = source.useVertexAlpha;
  65044. }
  65045. _this._intersectionThreshold = 0.1;
  65046. var defines = [];
  65047. var options = {
  65048. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65049. uniforms: ["world", "viewProjection"],
  65050. needAlphaBlending: true,
  65051. defines: defines
  65052. };
  65053. if (useVertexAlpha === false) {
  65054. options.needAlphaBlending = false;
  65055. }
  65056. if (!useVertexColor) {
  65057. options.uniforms.push("color");
  65058. }
  65059. else {
  65060. options.defines.push("#define VERTEXCOLOR");
  65061. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65062. }
  65063. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65064. return _this;
  65065. }
  65066. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  65067. /**
  65068. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65069. * This margin is expressed in world space coordinates, so its value may vary.
  65070. * Default value is 0.1
  65071. * @returns the intersection Threshold value.
  65072. */
  65073. get: function () {
  65074. return this._intersectionThreshold;
  65075. },
  65076. /**
  65077. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65078. * This margin is expressed in world space coordinates, so its value may vary.
  65079. */
  65080. set: function (value) {
  65081. if (this._intersectionThreshold === value) {
  65082. return;
  65083. }
  65084. this._intersectionThreshold = value;
  65085. if (this.geometry) {
  65086. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  65087. }
  65088. },
  65089. enumerable: true,
  65090. configurable: true
  65091. });
  65092. /**
  65093. * Returns the string "LineMesh"
  65094. */
  65095. LinesMesh.prototype.getClassName = function () {
  65096. return "LinesMesh";
  65097. };
  65098. Object.defineProperty(LinesMesh.prototype, "material", {
  65099. /**
  65100. * @hidden
  65101. */
  65102. get: function () {
  65103. return this._colorShader;
  65104. },
  65105. /**
  65106. * @hidden
  65107. */
  65108. set: function (value) {
  65109. // Do nothing
  65110. },
  65111. enumerable: true,
  65112. configurable: true
  65113. });
  65114. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65115. /**
  65116. * @hidden
  65117. */
  65118. get: function () {
  65119. return false;
  65120. },
  65121. enumerable: true,
  65122. configurable: true
  65123. });
  65124. /** @hidden */
  65125. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65126. if (!this._geometry) {
  65127. return this;
  65128. }
  65129. // VBOs
  65130. this._geometry._bind(this._colorShader.getEffect());
  65131. // Color
  65132. if (!this.useVertexColor) {
  65133. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65134. }
  65135. return this;
  65136. };
  65137. /** @hidden */
  65138. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65139. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65140. return this;
  65141. }
  65142. var engine = this.getScene().getEngine();
  65143. // Draw order
  65144. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65145. return this;
  65146. };
  65147. /**
  65148. * Disposes of the line mesh
  65149. * @param doNotRecurse If children should be disposed
  65150. */
  65151. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65152. this._colorShader.dispose(false, false, true);
  65153. _super.prototype.dispose.call(this, doNotRecurse);
  65154. };
  65155. /**
  65156. * Returns a new LineMesh object cloned from the current one.
  65157. */
  65158. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65159. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65160. };
  65161. return LinesMesh;
  65162. }(BABYLON.Mesh));
  65163. BABYLON.LinesMesh = LinesMesh;
  65164. })(BABYLON || (BABYLON = {}));
  65165. //# sourceMappingURL=babylon.linesMesh.js.map
  65166. var BABYLON;
  65167. (function (BABYLON) {
  65168. /**
  65169. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65170. * The underlying implementation relies on an associative array to ensure the best performances.
  65171. * The value can be anything including 'null' but except 'undefined'
  65172. */
  65173. var StringDictionary = /** @class */ (function () {
  65174. function StringDictionary() {
  65175. this._count = 0;
  65176. this._data = {};
  65177. }
  65178. /**
  65179. * This will clear this dictionary and copy the content from the 'source' one.
  65180. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65181. * @param source the dictionary to take the content from and copy to this dictionary
  65182. */
  65183. StringDictionary.prototype.copyFrom = function (source) {
  65184. var _this = this;
  65185. this.clear();
  65186. source.forEach(function (t, v) { return _this.add(t, v); });
  65187. };
  65188. /**
  65189. * Get a value based from its key
  65190. * @param key the given key to get the matching value from
  65191. * @return the value if found, otherwise undefined is returned
  65192. */
  65193. StringDictionary.prototype.get = function (key) {
  65194. var val = this._data[key];
  65195. if (val !== undefined) {
  65196. return val;
  65197. }
  65198. return undefined;
  65199. };
  65200. /**
  65201. * Get a value from its key or add it if it doesn't exist.
  65202. * This method will ensure you that a given key/data will be present in the dictionary.
  65203. * @param key the given key to get the matching value from
  65204. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65205. * The factory will only be invoked if there's no data for the given key.
  65206. * @return the value corresponding to the key.
  65207. */
  65208. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65209. var val = this.get(key);
  65210. if (val !== undefined) {
  65211. return val;
  65212. }
  65213. val = factory(key);
  65214. if (val) {
  65215. this.add(key, val);
  65216. }
  65217. return val;
  65218. };
  65219. /**
  65220. * Get a value from its key if present in the dictionary otherwise add it
  65221. * @param key the key to get the value from
  65222. * @param val if there's no such key/value pair in the dictionary add it with this value
  65223. * @return the value corresponding to the key
  65224. */
  65225. StringDictionary.prototype.getOrAdd = function (key, val) {
  65226. var curVal = this.get(key);
  65227. if (curVal !== undefined) {
  65228. return curVal;
  65229. }
  65230. this.add(key, val);
  65231. return val;
  65232. };
  65233. /**
  65234. * Check if there's a given key in the dictionary
  65235. * @param key the key to check for
  65236. * @return true if the key is present, false otherwise
  65237. */
  65238. StringDictionary.prototype.contains = function (key) {
  65239. return this._data[key] !== undefined;
  65240. };
  65241. /**
  65242. * Add a new key and its corresponding value
  65243. * @param key the key to add
  65244. * @param value the value corresponding to the key
  65245. * @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
  65246. */
  65247. StringDictionary.prototype.add = function (key, value) {
  65248. if (this._data[key] !== undefined) {
  65249. return false;
  65250. }
  65251. this._data[key] = value;
  65252. ++this._count;
  65253. return true;
  65254. };
  65255. /**
  65256. * Update a specific value associated to a key
  65257. * @param key defines the key to use
  65258. * @param value defines the value to store
  65259. * @returns true if the value was updated (or false if the key was not found)
  65260. */
  65261. StringDictionary.prototype.set = function (key, value) {
  65262. if (this._data[key] === undefined) {
  65263. return false;
  65264. }
  65265. this._data[key] = value;
  65266. return true;
  65267. };
  65268. /**
  65269. * Get the element of the given key and remove it from the dictionary
  65270. * @param key defines the key to search
  65271. * @returns the value associated with the key or null if not found
  65272. */
  65273. StringDictionary.prototype.getAndRemove = function (key) {
  65274. var val = this.get(key);
  65275. if (val !== undefined) {
  65276. delete this._data[key];
  65277. --this._count;
  65278. return val;
  65279. }
  65280. return null;
  65281. };
  65282. /**
  65283. * Remove a key/value from the dictionary.
  65284. * @param key the key to remove
  65285. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65286. */
  65287. StringDictionary.prototype.remove = function (key) {
  65288. if (this.contains(key)) {
  65289. delete this._data[key];
  65290. --this._count;
  65291. return true;
  65292. }
  65293. return false;
  65294. };
  65295. /**
  65296. * Clear the whole content of the dictionary
  65297. */
  65298. StringDictionary.prototype.clear = function () {
  65299. this._data = {};
  65300. this._count = 0;
  65301. };
  65302. Object.defineProperty(StringDictionary.prototype, "count", {
  65303. /**
  65304. * Gets the current count
  65305. */
  65306. get: function () {
  65307. return this._count;
  65308. },
  65309. enumerable: true,
  65310. configurable: true
  65311. });
  65312. /**
  65313. * Execute a callback on each key/val of the dictionary.
  65314. * Note that you can remove any element in this dictionary in the callback implementation
  65315. * @param callback the callback to execute on a given key/value pair
  65316. */
  65317. StringDictionary.prototype.forEach = function (callback) {
  65318. for (var cur in this._data) {
  65319. var val = this._data[cur];
  65320. callback(cur, val);
  65321. }
  65322. };
  65323. /**
  65324. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65325. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65326. * Note that you can remove any element in this dictionary in the callback implementation
  65327. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65328. * @returns the first item
  65329. */
  65330. StringDictionary.prototype.first = function (callback) {
  65331. for (var cur in this._data) {
  65332. var val = this._data[cur];
  65333. var res = callback(cur, val);
  65334. if (res) {
  65335. return res;
  65336. }
  65337. }
  65338. return null;
  65339. };
  65340. return StringDictionary;
  65341. }());
  65342. BABYLON.StringDictionary = StringDictionary;
  65343. })(BABYLON || (BABYLON = {}));
  65344. //# sourceMappingURL=babylon.stringDictionary.js.map
  65345. var BABYLON;
  65346. (function (BABYLON) {
  65347. var Debug;
  65348. (function (Debug) {
  65349. /**
  65350. * Class used to render a debug view of a given skeleton
  65351. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65352. */
  65353. var SkeletonViewer = /** @class */ (function () {
  65354. /**
  65355. * Creates a new SkeletonViewer
  65356. * @param skeleton defines the skeleton to render
  65357. * @param mesh defines the mesh attached to the skeleton
  65358. * @param scene defines the hosting scene
  65359. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65360. * @param renderingGroupId defines the rendering group id to use with the viewer
  65361. */
  65362. function SkeletonViewer(
  65363. /** defines the skeleton to render */
  65364. skeleton,
  65365. /** defines the mesh attached to the skeleton */
  65366. mesh, scene,
  65367. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65368. autoUpdateBonesMatrices,
  65369. /** defines the rendering group id to use with the viewer */
  65370. renderingGroupId) {
  65371. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65372. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65373. this.skeleton = skeleton;
  65374. this.mesh = mesh;
  65375. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65376. this.renderingGroupId = renderingGroupId;
  65377. /** Gets or sets the color used to render the skeleton */
  65378. this.color = BABYLON.Color3.White();
  65379. this._debugLines = new Array();
  65380. this._isEnabled = false;
  65381. this._scene = scene;
  65382. this.update();
  65383. this._renderFunction = this.update.bind(this);
  65384. }
  65385. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65386. get: function () {
  65387. return this._isEnabled;
  65388. },
  65389. /** Gets or sets a boolean indicating if the viewer is enabled */
  65390. set: function (value) {
  65391. if (this._isEnabled === value) {
  65392. return;
  65393. }
  65394. this._isEnabled = value;
  65395. if (value) {
  65396. this._scene.registerBeforeRender(this._renderFunction);
  65397. }
  65398. else {
  65399. this._scene.unregisterBeforeRender(this._renderFunction);
  65400. }
  65401. },
  65402. enumerable: true,
  65403. configurable: true
  65404. });
  65405. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65406. if (x === void 0) { x = 0; }
  65407. if (y === void 0) { y = 0; }
  65408. if (z === void 0) { z = 0; }
  65409. var tmat = BABYLON.Tmp.Matrix[0];
  65410. var parentBone = bone.getParent();
  65411. tmat.copyFrom(bone.getLocalMatrix());
  65412. if (x !== 0 || y !== 0 || z !== 0) {
  65413. var tmat2 = BABYLON.Tmp.Matrix[1];
  65414. BABYLON.Matrix.IdentityToRef(tmat2);
  65415. tmat2.m[12] = x;
  65416. tmat2.m[13] = y;
  65417. tmat2.m[14] = z;
  65418. tmat2.multiplyToRef(tmat, tmat);
  65419. }
  65420. if (parentBone) {
  65421. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65422. }
  65423. tmat.multiplyToRef(meshMat, tmat);
  65424. position.x = tmat.m[12];
  65425. position.y = tmat.m[13];
  65426. position.z = tmat.m[14];
  65427. };
  65428. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65429. var len = bones.length;
  65430. var meshPos = this.mesh.position;
  65431. for (var i = 0; i < len; i++) {
  65432. var bone = bones[i];
  65433. var points = this._debugLines[i];
  65434. if (!points) {
  65435. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65436. this._debugLines[i] = points;
  65437. }
  65438. this._getBonePosition(points[0], bone, meshMat);
  65439. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65440. points[0].subtractInPlace(meshPos);
  65441. points[1].subtractInPlace(meshPos);
  65442. }
  65443. };
  65444. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65445. var len = bones.length;
  65446. var boneNum = 0;
  65447. var meshPos = this.mesh.position;
  65448. for (var i = len - 1; i >= 0; i--) {
  65449. var childBone = bones[i];
  65450. var parentBone = childBone.getParent();
  65451. if (!parentBone) {
  65452. continue;
  65453. }
  65454. var points = this._debugLines[boneNum];
  65455. if (!points) {
  65456. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65457. this._debugLines[boneNum] = points;
  65458. }
  65459. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65460. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65461. points[0].subtractInPlace(meshPos);
  65462. points[1].subtractInPlace(meshPos);
  65463. boneNum++;
  65464. }
  65465. };
  65466. /** Update the viewer to sync with current skeleton state */
  65467. SkeletonViewer.prototype.update = function () {
  65468. if (this.autoUpdateBonesMatrices) {
  65469. this.skeleton.computeAbsoluteTransforms();
  65470. }
  65471. if (this.skeleton.bones[0].length === undefined) {
  65472. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65473. }
  65474. else {
  65475. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65476. }
  65477. if (!this._debugMesh) {
  65478. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  65479. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65480. }
  65481. else {
  65482. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65483. }
  65484. this._debugMesh.position.copyFrom(this.mesh.position);
  65485. this._debugMesh.color = this.color;
  65486. };
  65487. /** Release associated resources */
  65488. SkeletonViewer.prototype.dispose = function () {
  65489. if (this._debugMesh) {
  65490. this.isEnabled = false;
  65491. this._debugMesh.dispose();
  65492. this._debugMesh = null;
  65493. }
  65494. };
  65495. return SkeletonViewer;
  65496. }());
  65497. Debug.SkeletonViewer = SkeletonViewer;
  65498. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65499. })(BABYLON || (BABYLON = {}));
  65500. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65501. /**
  65502. * Module Debug contains the (visual) components to debug a scene correctly
  65503. */
  65504. var BABYLON;
  65505. (function (BABYLON) {
  65506. var Debug;
  65507. (function (Debug) {
  65508. /**
  65509. * The Axes viewer will show 3 axes in a specific point in space
  65510. */
  65511. var AxesViewer = /** @class */ (function () {
  65512. /**
  65513. * Creates a new AxesViewer
  65514. * @param scene defines the hosting scene
  65515. * @param scaleLines defines a number used to scale line length (1 by default)
  65516. */
  65517. function AxesViewer(scene, scaleLines) {
  65518. if (scaleLines === void 0) { scaleLines = 1; }
  65519. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65520. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65521. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65522. /**
  65523. * Gets or sets a number used to scale line length
  65524. */
  65525. this.scaleLines = 1;
  65526. this.scaleLines = scaleLines;
  65527. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65528. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65529. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65530. this._xmesh.renderingGroupId = 2;
  65531. this._ymesh.renderingGroupId = 2;
  65532. this._zmesh.renderingGroupId = 2;
  65533. this._xmesh.material.checkReadyOnlyOnce = true;
  65534. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65535. this._ymesh.material.checkReadyOnlyOnce = true;
  65536. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65537. this._zmesh.material.checkReadyOnlyOnce = true;
  65538. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65539. this.scene = scene;
  65540. }
  65541. /**
  65542. * Force the viewer to update
  65543. * @param position defines the position of the viewer
  65544. * @param xaxis defines the x axis of the viewer
  65545. * @param yaxis defines the y axis of the viewer
  65546. * @param zaxis defines the z axis of the viewer
  65547. */
  65548. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65549. var scaleLines = this.scaleLines;
  65550. if (this._xmesh) {
  65551. this._xmesh.position.copyFrom(position);
  65552. }
  65553. if (this._ymesh) {
  65554. this._ymesh.position.copyFrom(position);
  65555. }
  65556. if (this._zmesh) {
  65557. this._zmesh.position.copyFrom(position);
  65558. }
  65559. var point2 = this._xline[1];
  65560. point2.x = xaxis.x * scaleLines;
  65561. point2.y = xaxis.y * scaleLines;
  65562. point2.z = xaxis.z * scaleLines;
  65563. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  65564. point2 = this._yline[1];
  65565. point2.x = yaxis.x * scaleLines;
  65566. point2.y = yaxis.y * scaleLines;
  65567. point2.z = yaxis.z * scaleLines;
  65568. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  65569. point2 = this._zline[1];
  65570. point2.x = zaxis.x * scaleLines;
  65571. point2.y = zaxis.y * scaleLines;
  65572. point2.z = zaxis.z * scaleLines;
  65573. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  65574. };
  65575. /** Releases resources */
  65576. AxesViewer.prototype.dispose = function () {
  65577. if (this._xmesh) {
  65578. this._xmesh.dispose();
  65579. }
  65580. if (this._ymesh) {
  65581. this._ymesh.dispose();
  65582. }
  65583. if (this._zmesh) {
  65584. this._zmesh.dispose();
  65585. }
  65586. this._xmesh = null;
  65587. this._ymesh = null;
  65588. this._zmesh = null;
  65589. this.scene = null;
  65590. };
  65591. return AxesViewer;
  65592. }());
  65593. Debug.AxesViewer = AxesViewer;
  65594. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65595. })(BABYLON || (BABYLON = {}));
  65596. //# sourceMappingURL=babylon.axesViewer.js.map
  65597. var BABYLON;
  65598. (function (BABYLON) {
  65599. var Debug;
  65600. (function (Debug) {
  65601. /**
  65602. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  65603. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  65604. */
  65605. var BoneAxesViewer = /** @class */ (function (_super) {
  65606. __extends(BoneAxesViewer, _super);
  65607. /**
  65608. * Creates a new BoneAxesViewer
  65609. * @param scene defines the hosting scene
  65610. * @param bone defines the target bone
  65611. * @param mesh defines the target mesh
  65612. * @param scaleLines defines a scaling factor for line length (1 by default)
  65613. */
  65614. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65615. if (scaleLines === void 0) { scaleLines = 1; }
  65616. var _this = _super.call(this, scene, scaleLines) || this;
  65617. /** Gets current position */
  65618. _this.pos = BABYLON.Vector3.Zero();
  65619. /** Gets direction of X axis */
  65620. _this.xaxis = BABYLON.Vector3.Zero();
  65621. /** Gets direction of Y axis */
  65622. _this.yaxis = BABYLON.Vector3.Zero();
  65623. /** Gets direction of Z axis */
  65624. _this.zaxis = BABYLON.Vector3.Zero();
  65625. _this.mesh = mesh;
  65626. _this.bone = bone;
  65627. return _this;
  65628. }
  65629. /**
  65630. * Force the viewer to update
  65631. */
  65632. BoneAxesViewer.prototype.update = function () {
  65633. if (!this.mesh || !this.bone) {
  65634. return;
  65635. }
  65636. var bone = this.bone;
  65637. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65638. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65639. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65640. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65641. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65642. };
  65643. /** Releases resources */
  65644. BoneAxesViewer.prototype.dispose = function () {
  65645. if (this.mesh) {
  65646. this.mesh = null;
  65647. this.bone = null;
  65648. _super.prototype.dispose.call(this);
  65649. }
  65650. };
  65651. return BoneAxesViewer;
  65652. }(Debug.AxesViewer));
  65653. Debug.BoneAxesViewer = BoneAxesViewer;
  65654. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65655. })(BABYLON || (BABYLON = {}));
  65656. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  65657. var BABYLON;
  65658. (function (BABYLON) {
  65659. /**
  65660. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65661. * in order to better appreciate the issue one might have.
  65662. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65663. */
  65664. var RayHelper = /** @class */ (function () {
  65665. /**
  65666. * Instantiate a new ray helper.
  65667. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65668. * in order to better appreciate the issue one might have.
  65669. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65670. * @param ray Defines the ray we are currently tryin to visualize
  65671. */
  65672. function RayHelper(ray) {
  65673. this.ray = ray;
  65674. }
  65675. /**
  65676. * Helper function to create a colored helper in a scene in one line.
  65677. * @param ray Defines the ray we are currently tryin to visualize
  65678. * @param scene Defines the scene the ray is used in
  65679. * @param color Defines the color we want to see the ray in
  65680. * @returns The newly created ray helper.
  65681. */
  65682. RayHelper.CreateAndShow = function (ray, scene, color) {
  65683. var helper = new RayHelper(ray);
  65684. helper.show(scene, color);
  65685. return helper;
  65686. };
  65687. /**
  65688. * Shows the ray we are willing to debug.
  65689. * @param scene Defines the scene the ray needs to be rendered in
  65690. * @param color Defines the color the ray needs to be rendered in
  65691. */
  65692. RayHelper.prototype.show = function (scene, color) {
  65693. if (!this._renderFunction && this.ray) {
  65694. var ray = this.ray;
  65695. this._renderFunction = this._render.bind(this);
  65696. this._scene = scene;
  65697. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  65698. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  65699. if (this._renderFunction) {
  65700. this._scene.registerBeforeRender(this._renderFunction);
  65701. }
  65702. }
  65703. if (color && this._renderLine) {
  65704. this._renderLine.color.copyFrom(color);
  65705. }
  65706. };
  65707. /**
  65708. * Hides the ray we are debugging.
  65709. */
  65710. RayHelper.prototype.hide = function () {
  65711. if (this._renderFunction && this._scene) {
  65712. this._scene.unregisterBeforeRender(this._renderFunction);
  65713. this._scene = null;
  65714. this._renderFunction = null;
  65715. if (this._renderLine) {
  65716. this._renderLine.dispose();
  65717. this._renderLine = null;
  65718. }
  65719. this._renderPoints = [];
  65720. }
  65721. };
  65722. RayHelper.prototype._render = function () {
  65723. var ray = this.ray;
  65724. if (!ray) {
  65725. return;
  65726. }
  65727. var point = this._renderPoints[1];
  65728. var len = Math.min(ray.length, 1000000);
  65729. point.copyFrom(ray.direction);
  65730. point.scaleInPlace(len);
  65731. point.addInPlace(ray.origin);
  65732. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  65733. };
  65734. /**
  65735. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  65736. * @param mesh Defines the mesh we want the helper attached to
  65737. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  65738. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  65739. * @param length Defines the length of the ray
  65740. */
  65741. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  65742. this._attachedToMesh = mesh;
  65743. var ray = this.ray;
  65744. if (!ray) {
  65745. return;
  65746. }
  65747. if (!ray.direction) {
  65748. ray.direction = BABYLON.Vector3.Zero();
  65749. }
  65750. if (!ray.origin) {
  65751. ray.origin = BABYLON.Vector3.Zero();
  65752. }
  65753. if (length) {
  65754. ray.length = length;
  65755. }
  65756. if (!meshSpaceOrigin) {
  65757. meshSpaceOrigin = BABYLON.Vector3.Zero();
  65758. }
  65759. if (!meshSpaceDirection) {
  65760. // -1 so that this will work with Mesh.lookAt
  65761. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  65762. }
  65763. if (!this._meshSpaceDirection) {
  65764. this._meshSpaceDirection = meshSpaceDirection.clone();
  65765. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  65766. }
  65767. else {
  65768. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  65769. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  65770. }
  65771. if (!this._updateToMeshFunction) {
  65772. this._updateToMeshFunction = this._updateToMesh.bind(this);
  65773. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  65774. }
  65775. this._updateToMesh();
  65776. };
  65777. /**
  65778. * Detach the ray helper from the mesh it has previously been attached to.
  65779. */
  65780. RayHelper.prototype.detachFromMesh = function () {
  65781. if (this._attachedToMesh) {
  65782. if (this._updateToMeshFunction) {
  65783. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  65784. }
  65785. this._attachedToMesh = null;
  65786. this._updateToMeshFunction = null;
  65787. }
  65788. };
  65789. RayHelper.prototype._updateToMesh = function () {
  65790. var ray = this.ray;
  65791. if (!this._attachedToMesh || !ray) {
  65792. return;
  65793. }
  65794. if (this._attachedToMesh._isDisposed) {
  65795. this.detachFromMesh();
  65796. return;
  65797. }
  65798. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  65799. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  65800. };
  65801. /**
  65802. * Dispose the helper and release its associated resources.
  65803. */
  65804. RayHelper.prototype.dispose = function () {
  65805. this.hide();
  65806. this.detachFromMesh();
  65807. this.ray = null;
  65808. };
  65809. return RayHelper;
  65810. }());
  65811. BABYLON.RayHelper = RayHelper;
  65812. })(BABYLON || (BABYLON = {}));
  65813. //# sourceMappingURL=babylon.rayHelper.js.map
  65814. var BABYLON;
  65815. (function (BABYLON) {
  65816. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  65817. get: function () {
  65818. if (!this._debugLayer) {
  65819. this._debugLayer = new DebugLayer(this);
  65820. }
  65821. return this._debugLayer;
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. /**
  65827. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65828. * what is happening in your scene
  65829. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65830. */
  65831. var DebugLayer = /** @class */ (function () {
  65832. /**
  65833. * Instantiates a new debug layer.
  65834. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65835. * what is happening in your scene
  65836. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65837. * @param scene Defines the scene to inspect
  65838. */
  65839. function DebugLayer(scene) {
  65840. var _this = this;
  65841. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65842. /**
  65843. * Observable triggered when a property is changed through the inspector.
  65844. */
  65845. this.onPropertyChangedObservable = new BABYLON.Observable();
  65846. this._scene = scene;
  65847. this._scene.onDisposeObservable.add(function () {
  65848. // Debug layer
  65849. if (_this._scene._debugLayer) {
  65850. _this._scene._debugLayer.hide();
  65851. }
  65852. });
  65853. }
  65854. /** Creates the inspector window. */
  65855. DebugLayer.prototype._createInspector = function (config) {
  65856. if (config === void 0) { config = {}; }
  65857. var popup = config.popup || false;
  65858. var initialTab = config.initialTab || 0;
  65859. var parentElement = config.parentElement || null;
  65860. if (!this._inspector) {
  65861. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65862. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  65863. } // else nothing to do as instance is already created
  65864. };
  65865. /**
  65866. * Get if the inspector is visible or not.
  65867. * @returns true if visible otherwise, false
  65868. */
  65869. DebugLayer.prototype.isVisible = function () {
  65870. if (!this._inspector) {
  65871. return false;
  65872. }
  65873. return true;
  65874. };
  65875. /**
  65876. * Hide the inspector and close its window.
  65877. */
  65878. DebugLayer.prototype.hide = function () {
  65879. if (this._inspector) {
  65880. try {
  65881. this._inspector.dispose();
  65882. }
  65883. catch (e) {
  65884. // If the inspector has been removed directly from the inspector tool
  65885. }
  65886. this.onPropertyChangedObservable.clear();
  65887. this._inspector = null;
  65888. }
  65889. };
  65890. /**
  65891. *
  65892. * Launch the debugLayer.
  65893. *
  65894. * initialTab:
  65895. * | Value | Tab Name |
  65896. * | --- | --- |
  65897. * | 0 | Scene |
  65898. * | 1 | Console |
  65899. * | 2 | Stats |
  65900. * | 3 | Textures |
  65901. * | 4 | Mesh |
  65902. * | 5 | Light |
  65903. * | 6 | Material |
  65904. * | 7 | GLTF |
  65905. * | 8 | GUI |
  65906. * | 9 | Physics |
  65907. * | 10 | Camera |
  65908. * | 11 | Audio |
  65909. *
  65910. * @param config Define the configuration of the inspector
  65911. */
  65912. DebugLayer.prototype.show = function (config) {
  65913. if (config === void 0) { config = {}; }
  65914. if (typeof this.BJSINSPECTOR == 'undefined') {
  65915. // Load inspector and add it to the DOM
  65916. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  65917. }
  65918. else {
  65919. // Otherwise creates the inspector
  65920. this._createInspector(config);
  65921. }
  65922. };
  65923. /**
  65924. * Gets the active tab
  65925. * @return the index of the active tab or -1 if the inspector is hidden
  65926. */
  65927. DebugLayer.prototype.getActiveTab = function () {
  65928. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  65929. };
  65930. /**
  65931. * Define the url to get the inspector script from.
  65932. * By default it uses the babylonjs CDN.
  65933. * @ignoreNaming
  65934. */
  65935. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  65936. return DebugLayer;
  65937. }());
  65938. BABYLON.DebugLayer = DebugLayer;
  65939. })(BABYLON || (BABYLON = {}));
  65940. //# sourceMappingURL=babylon.debugLayer.js.map
  65941. var BABYLON;
  65942. (function (BABYLON) {
  65943. var Debug;
  65944. (function (Debug) {
  65945. /**
  65946. * Used to show the physics impostor around the specific mesh
  65947. */
  65948. var PhysicsViewer = /** @class */ (function () {
  65949. /**
  65950. * Creates a new PhysicsViewer
  65951. * @param scene defines the hosting scene
  65952. */
  65953. function PhysicsViewer(scene) {
  65954. /** @hidden */
  65955. this._impostors = [];
  65956. /** @hidden */
  65957. this._meshes = [];
  65958. /** @hidden */
  65959. this._numMeshes = 0;
  65960. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65961. var physicEngine = this._scene.getPhysicsEngine();
  65962. if (physicEngine) {
  65963. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  65964. }
  65965. }
  65966. /** @hidden */
  65967. PhysicsViewer.prototype._updateDebugMeshes = function () {
  65968. var plugin = this._physicsEnginePlugin;
  65969. for (var i = 0; i < this._numMeshes; i++) {
  65970. var impostor = this._impostors[i];
  65971. if (!impostor) {
  65972. continue;
  65973. }
  65974. if (impostor.isDisposed) {
  65975. this.hideImpostor(this._impostors[i--]);
  65976. }
  65977. else {
  65978. var mesh = this._meshes[i];
  65979. if (mesh && plugin) {
  65980. plugin.syncMeshWithImpostor(mesh, impostor);
  65981. }
  65982. }
  65983. }
  65984. };
  65985. /**
  65986. * Renders a specified physic impostor
  65987. * @param impostor defines the impostor to render
  65988. */
  65989. PhysicsViewer.prototype.showImpostor = function (impostor) {
  65990. if (!this._scene) {
  65991. return;
  65992. }
  65993. for (var i = 0; i < this._numMeshes; i++) {
  65994. if (this._impostors[i] == impostor) {
  65995. return;
  65996. }
  65997. }
  65998. var debugMesh = this._getDebugMesh(impostor, this._scene);
  65999. if (debugMesh) {
  66000. this._impostors[this._numMeshes] = impostor;
  66001. this._meshes[this._numMeshes] = debugMesh;
  66002. if (this._numMeshes === 0) {
  66003. this._renderFunction = this._updateDebugMeshes.bind(this);
  66004. this._scene.registerBeforeRender(this._renderFunction);
  66005. }
  66006. this._numMeshes++;
  66007. }
  66008. };
  66009. /**
  66010. * Hides a specified physic impostor
  66011. * @param impostor defines the impostor to hide
  66012. */
  66013. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66014. if (!impostor || !this._scene) {
  66015. return;
  66016. }
  66017. var removed = false;
  66018. for (var i = 0; i < this._numMeshes; i++) {
  66019. if (this._impostors[i] == impostor) {
  66020. var mesh = this._meshes[i];
  66021. if (!mesh) {
  66022. continue;
  66023. }
  66024. this._scene.removeMesh(mesh);
  66025. mesh.dispose();
  66026. this._numMeshes--;
  66027. if (this._numMeshes > 0) {
  66028. this._meshes[i] = this._meshes[this._numMeshes];
  66029. this._impostors[i] = this._impostors[this._numMeshes];
  66030. this._meshes[this._numMeshes] = null;
  66031. this._impostors[this._numMeshes] = null;
  66032. }
  66033. else {
  66034. this._meshes[0] = null;
  66035. this._impostors[0] = null;
  66036. }
  66037. removed = true;
  66038. break;
  66039. }
  66040. }
  66041. if (removed && this._numMeshes === 0) {
  66042. this._scene.unregisterBeforeRender(this._renderFunction);
  66043. }
  66044. };
  66045. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66046. if (!this._debugMaterial) {
  66047. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66048. this._debugMaterial.wireframe = true;
  66049. }
  66050. return this._debugMaterial;
  66051. };
  66052. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66053. if (!this._debugBoxMesh) {
  66054. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66055. this._debugBoxMesh.renderingGroupId = 1;
  66056. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66057. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66058. scene.removeMesh(this._debugBoxMesh);
  66059. }
  66060. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66061. };
  66062. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66063. if (!this._debugSphereMesh) {
  66064. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66065. this._debugSphereMesh.renderingGroupId = 1;
  66066. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66067. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66068. scene.removeMesh(this._debugSphereMesh);
  66069. }
  66070. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66071. };
  66072. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66073. var mesh = null;
  66074. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66075. mesh = this._getDebugBoxMesh(scene);
  66076. impostor.getBoxSizeToRef(mesh.scaling);
  66077. }
  66078. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66079. mesh = this._getDebugSphereMesh(scene);
  66080. var radius = impostor.getRadius();
  66081. mesh.scaling.x = radius * 2;
  66082. mesh.scaling.y = radius * 2;
  66083. mesh.scaling.z = radius * 2;
  66084. }
  66085. return mesh;
  66086. };
  66087. /** Releases all resources */
  66088. PhysicsViewer.prototype.dispose = function () {
  66089. for (var i = 0; i < this._numMeshes; i++) {
  66090. this.hideImpostor(this._impostors[i]);
  66091. }
  66092. if (this._debugBoxMesh) {
  66093. this._debugBoxMesh.dispose();
  66094. }
  66095. if (this._debugSphereMesh) {
  66096. this._debugSphereMesh.dispose();
  66097. }
  66098. if (this._debugMaterial) {
  66099. this._debugMaterial.dispose();
  66100. }
  66101. this._impostors.length = 0;
  66102. this._scene = null;
  66103. this._physicsEnginePlugin = null;
  66104. };
  66105. return PhysicsViewer;
  66106. }());
  66107. Debug.PhysicsViewer = PhysicsViewer;
  66108. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66109. })(BABYLON || (BABYLON = {}));
  66110. //# sourceMappingURL=babylon.physicsViewer.js.map
  66111. var BABYLON;
  66112. (function (BABYLON) {
  66113. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66114. get: function () {
  66115. return this._forceShowBoundingBoxes || false;
  66116. },
  66117. set: function (value) {
  66118. this._forceShowBoundingBoxes = value;
  66119. // Lazyly creates a BB renderer if needed.
  66120. if (value) {
  66121. this.getBoundingBoxRenderer();
  66122. }
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66128. if (!this._boundingBoxRenderer) {
  66129. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66130. }
  66131. return this._boundingBoxRenderer;
  66132. };
  66133. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66134. get: function () {
  66135. return this._showBoundingBox || false;
  66136. },
  66137. set: function (value) {
  66138. this._showBoundingBox = value;
  66139. // Lazyly creates a BB renderer if needed.
  66140. if (value) {
  66141. this.getScene().getBoundingBoxRenderer();
  66142. }
  66143. },
  66144. enumerable: true,
  66145. configurable: true
  66146. });
  66147. /**
  66148. * Component responsible of rendering the bounding box of the meshes in a scene.
  66149. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66150. */
  66151. var BoundingBoxRenderer = /** @class */ (function () {
  66152. /**
  66153. * Instantiates a new bounding box renderer in a scene.
  66154. * @param scene the scene the renderer renders in
  66155. */
  66156. function BoundingBoxRenderer(scene) {
  66157. /**
  66158. * The component name helpfull to identify the component in the list of scene components.
  66159. */
  66160. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66161. /**
  66162. * Color of the bounding box lines placed in front of an object
  66163. */
  66164. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66165. /**
  66166. * Color of the bounding box lines placed behind an object
  66167. */
  66168. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66169. /**
  66170. * Defines if the renderer should show the back lines or not
  66171. */
  66172. this.showBackLines = true;
  66173. /**
  66174. * @hidden
  66175. */
  66176. this.renderList = new BABYLON.SmartArray(32);
  66177. this._vertexBuffers = {};
  66178. this.scene = scene;
  66179. scene._addComponent(this);
  66180. }
  66181. /**
  66182. * Registers the component in a given scene
  66183. */
  66184. BoundingBoxRenderer.prototype.register = function () {
  66185. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66186. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66187. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66188. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66189. };
  66190. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66191. if (mesh.showSubMeshesBoundingBox) {
  66192. var boundingInfo = subMesh.getBoundingInfo();
  66193. if (boundingInfo !== null && boundingInfo !== undefined) {
  66194. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66195. this.renderList.push(boundingInfo.boundingBox);
  66196. }
  66197. }
  66198. };
  66199. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66200. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66201. var boundingInfo = sourceMesh.getBoundingInfo();
  66202. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66203. this.renderList.push(boundingInfo.boundingBox);
  66204. }
  66205. };
  66206. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66207. if (this._colorShader) {
  66208. return;
  66209. }
  66210. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66211. attributes: [BABYLON.VertexBuffer.PositionKind],
  66212. uniforms: ["world", "viewProjection", "color"]
  66213. });
  66214. var engine = this.scene.getEngine();
  66215. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66216. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66217. this._createIndexBuffer();
  66218. };
  66219. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66220. var engine = this.scene.getEngine();
  66221. 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]);
  66222. };
  66223. /**
  66224. * Rebuilds the elements related to this component in case of
  66225. * context lost for instance.
  66226. */
  66227. BoundingBoxRenderer.prototype.rebuild = function () {
  66228. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66229. if (vb) {
  66230. vb._rebuild();
  66231. }
  66232. this._createIndexBuffer();
  66233. };
  66234. /**
  66235. * @hidden
  66236. */
  66237. BoundingBoxRenderer.prototype.reset = function () {
  66238. this.renderList.reset();
  66239. };
  66240. /**
  66241. * Render the bounding boxes of a specific rendering group
  66242. * @param renderingGroupId defines the rendering group to render
  66243. */
  66244. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66245. if (this.renderList.length === 0) {
  66246. return;
  66247. }
  66248. this._prepareRessources();
  66249. if (!this._colorShader.isReady()) {
  66250. return;
  66251. }
  66252. var engine = this.scene.getEngine();
  66253. engine.setDepthWrite(false);
  66254. this._colorShader._preBind();
  66255. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66256. var boundingBox = this.renderList.data[boundingBoxIndex];
  66257. if (boundingBox._tag !== renderingGroupId) {
  66258. continue;
  66259. }
  66260. var min = boundingBox.minimum;
  66261. var max = boundingBox.maximum;
  66262. var diff = max.subtract(min);
  66263. var median = min.add(diff.scale(0.5));
  66264. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66265. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66266. .multiply(boundingBox.getWorldMatrix());
  66267. // VBOs
  66268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66269. if (this.showBackLines) {
  66270. // Back
  66271. engine.setDepthFunctionToGreaterOrEqual();
  66272. this.scene.resetCachedMaterial();
  66273. this._colorShader.setColor4("color", this.backColor.toColor4());
  66274. this._colorShader.bind(worldMatrix);
  66275. // Draw order
  66276. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66277. }
  66278. // Front
  66279. engine.setDepthFunctionToLess();
  66280. this.scene.resetCachedMaterial();
  66281. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66282. this._colorShader.bind(worldMatrix);
  66283. // Draw order
  66284. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66285. }
  66286. this._colorShader.unbind();
  66287. engine.setDepthFunctionToLessOrEqual();
  66288. engine.setDepthWrite(true);
  66289. };
  66290. /**
  66291. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66292. * @param mesh Define the mesh to render the occlusion bounding box for
  66293. */
  66294. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66295. this._prepareRessources();
  66296. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66297. return;
  66298. }
  66299. var engine = this.scene.getEngine();
  66300. engine.setDepthWrite(false);
  66301. engine.setColorWrite(false);
  66302. this._colorShader._preBind();
  66303. var boundingBox = mesh._boundingInfo.boundingBox;
  66304. var min = boundingBox.minimum;
  66305. var max = boundingBox.maximum;
  66306. var diff = max.subtract(min);
  66307. var median = min.add(diff.scale(0.5));
  66308. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66309. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66310. .multiply(boundingBox.getWorldMatrix());
  66311. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66312. engine.setDepthFunctionToLess();
  66313. this.scene.resetCachedMaterial();
  66314. this._colorShader.bind(worldMatrix);
  66315. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66316. this._colorShader.unbind();
  66317. engine.setDepthFunctionToLessOrEqual();
  66318. engine.setDepthWrite(true);
  66319. engine.setColorWrite(true);
  66320. };
  66321. /**
  66322. * Dispose and release the resources attached to this renderer.
  66323. */
  66324. BoundingBoxRenderer.prototype.dispose = function () {
  66325. if (!this._colorShader) {
  66326. return;
  66327. }
  66328. this.renderList.dispose();
  66329. this._colorShader.dispose();
  66330. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66331. if (buffer) {
  66332. buffer.dispose();
  66333. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66334. }
  66335. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66336. };
  66337. return BoundingBoxRenderer;
  66338. }());
  66339. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66340. })(BABYLON || (BABYLON = {}));
  66341. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66342. var BABYLON;
  66343. (function (BABYLON) {
  66344. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66345. return this._gl.createTransformFeedback();
  66346. };
  66347. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66348. this._gl.deleteTransformFeedback(value);
  66349. };
  66350. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66351. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66352. };
  66353. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66354. if (usePoints === void 0) { usePoints = true; }
  66355. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66356. };
  66357. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66358. this._gl.endTransformFeedback();
  66359. };
  66360. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66361. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66362. };
  66363. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66364. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66365. };
  66366. })(BABYLON || (BABYLON = {}));
  66367. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  66368. var BABYLON;
  66369. (function (BABYLON) {
  66370. /**
  66371. * This represents a GPU particle system in Babylon
  66372. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66373. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66374. */
  66375. var GPUParticleSystem = /** @class */ (function (_super) {
  66376. __extends(GPUParticleSystem, _super);
  66377. /**
  66378. * Instantiates a GPU particle system.
  66379. * 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.
  66380. * @param name The name of the particle system
  66381. * @param options The options used to create the system
  66382. * @param scene The scene the particle system belongs to
  66383. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66384. */
  66385. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66386. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66387. var _this = _super.call(this, name) || this;
  66388. /**
  66389. * The layer mask we are rendering the particles through.
  66390. */
  66391. _this.layerMask = 0x0FFFFFFF;
  66392. _this._accumulatedCount = 0;
  66393. _this._targetIndex = 0;
  66394. _this._currentRenderId = -1;
  66395. _this._started = false;
  66396. _this._stopped = false;
  66397. _this._timeDelta = 0;
  66398. _this._attributesStrideSize = 21;
  66399. _this._actualFrame = 0;
  66400. _this._rawTextureWidth = 256;
  66401. /**
  66402. * An event triggered when the system is disposed.
  66403. */
  66404. _this.onDisposeObservable = new BABYLON.Observable();
  66405. /**
  66406. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66407. * to override the particles.
  66408. */
  66409. _this.forceDepthWrite = false;
  66410. _this._preWarmDone = false;
  66411. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66412. // Setup the default processing configuration to the scene.
  66413. _this._attachImageProcessingConfiguration(null);
  66414. _this._engine = _this._scene.getEngine();
  66415. if (!options.randomTextureSize) {
  66416. delete options.randomTextureSize;
  66417. }
  66418. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66419. var optionsAsNumber = options;
  66420. if (isFinite(optionsAsNumber)) {
  66421. fullOptions.capacity = optionsAsNumber;
  66422. }
  66423. _this._capacity = fullOptions.capacity;
  66424. _this._activeCount = fullOptions.capacity;
  66425. _this._currentActiveCount = 0;
  66426. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66427. _this._scene.particleSystems.push(_this);
  66428. _this._updateEffectOptions = {
  66429. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66430. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66431. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66432. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66433. uniformBuffersNames: [],
  66434. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66435. defines: "",
  66436. fallbacks: null,
  66437. onCompiled: null,
  66438. onError: null,
  66439. indexParameters: null,
  66440. maxSimultaneousLights: 0,
  66441. transformFeedbackVaryings: []
  66442. };
  66443. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66444. // Random data
  66445. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66446. var d = [];
  66447. for (var i = 0; i < maxTextureSize; ++i) {
  66448. d.push(Math.random());
  66449. d.push(Math.random());
  66450. d.push(Math.random());
  66451. d.push(Math.random());
  66452. }
  66453. _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);
  66454. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66455. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66456. d = [];
  66457. for (var i = 0; i < maxTextureSize; ++i) {
  66458. d.push(Math.random());
  66459. d.push(Math.random());
  66460. d.push(Math.random());
  66461. d.push(Math.random());
  66462. }
  66463. _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);
  66464. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66465. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66466. _this._randomTextureSize = maxTextureSize;
  66467. return _this;
  66468. }
  66469. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66470. /**
  66471. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66472. */
  66473. get: function () {
  66474. if (!BABYLON.Engine.LastCreatedEngine) {
  66475. return false;
  66476. }
  66477. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66478. },
  66479. enumerable: true,
  66480. configurable: true
  66481. });
  66482. /**
  66483. * Gets the maximum number of particles active at the same time.
  66484. * @returns The max number of active particles.
  66485. */
  66486. GPUParticleSystem.prototype.getCapacity = function () {
  66487. return this._capacity;
  66488. };
  66489. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66490. /**
  66491. * Gets or set the number of active particles
  66492. */
  66493. get: function () {
  66494. return this._activeCount;
  66495. },
  66496. set: function (value) {
  66497. this._activeCount = Math.min(value, this._capacity);
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. /**
  66503. * Is this system ready to be used/rendered
  66504. * @return true if the system is ready
  66505. */
  66506. GPUParticleSystem.prototype.isReady = function () {
  66507. if (!this._updateEffect) {
  66508. this._recreateUpdateEffect();
  66509. this._recreateRenderEffect();
  66510. return false;
  66511. }
  66512. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  66513. return false;
  66514. }
  66515. return true;
  66516. };
  66517. /**
  66518. * Gets if the system has been started. (Note: this will still be true after stop is called)
  66519. * @returns True if it has been started, otherwise false.
  66520. */
  66521. GPUParticleSystem.prototype.isStarted = function () {
  66522. return this._started;
  66523. };
  66524. /**
  66525. * Starts the particle system and begins to emit
  66526. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  66527. */
  66528. GPUParticleSystem.prototype.start = function (delay) {
  66529. var _this = this;
  66530. if (delay === void 0) { delay = this.startDelay; }
  66531. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  66532. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  66533. }
  66534. if (delay) {
  66535. setTimeout(function () {
  66536. _this.start(0);
  66537. }, delay);
  66538. return;
  66539. }
  66540. this._started = true;
  66541. this._stopped = false;
  66542. this._preWarmDone = false;
  66543. // Animations
  66544. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  66545. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  66546. }
  66547. };
  66548. /**
  66549. * Stops the particle system.
  66550. */
  66551. GPUParticleSystem.prototype.stop = function () {
  66552. this._stopped = true;
  66553. };
  66554. /**
  66555. * Remove all active particles
  66556. */
  66557. GPUParticleSystem.prototype.reset = function () {
  66558. this._releaseBuffers();
  66559. this._releaseVAOs();
  66560. this._currentActiveCount = 0;
  66561. this._targetIndex = 0;
  66562. };
  66563. /**
  66564. * Returns the string "GPUParticleSystem"
  66565. * @returns a string containing the class name
  66566. */
  66567. GPUParticleSystem.prototype.getClassName = function () {
  66568. return "GPUParticleSystem";
  66569. };
  66570. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  66571. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  66572. this._releaseBuffers();
  66573. return this;
  66574. };
  66575. /**
  66576. * Adds a new color gradient
  66577. * @param gradient defines the gradient to use (between 0 and 1)
  66578. * @param color1 defines the color to affect to the specified gradient
  66579. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  66580. * @returns the current particle system
  66581. */
  66582. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  66583. if (!this._colorGradients) {
  66584. this._colorGradients = [];
  66585. }
  66586. var colorGradient = new BABYLON.ColorGradient();
  66587. colorGradient.gradient = gradient;
  66588. colorGradient.color1 = color1;
  66589. this._colorGradients.push(colorGradient);
  66590. this._colorGradients.sort(function (a, b) {
  66591. if (a.gradient < b.gradient) {
  66592. return -1;
  66593. }
  66594. else if (a.gradient > b.gradient) {
  66595. return 1;
  66596. }
  66597. return 0;
  66598. });
  66599. if (this._colorGradientsTexture) {
  66600. this._colorGradientsTexture.dispose();
  66601. this._colorGradientsTexture = null;
  66602. }
  66603. this._releaseBuffers();
  66604. return this;
  66605. };
  66606. /**
  66607. * Remove a specific color gradient
  66608. * @param gradient defines the gradient to remove
  66609. * @returns the current particle system
  66610. */
  66611. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  66612. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  66613. this._colorGradientsTexture = null;
  66614. return this;
  66615. };
  66616. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  66617. var valueGradient = new BABYLON.FactorGradient();
  66618. valueGradient.gradient = gradient;
  66619. valueGradient.factor1 = factor;
  66620. factorGradients.push(valueGradient);
  66621. factorGradients.sort(function (a, b) {
  66622. if (a.gradient < b.gradient) {
  66623. return -1;
  66624. }
  66625. else if (a.gradient > b.gradient) {
  66626. return 1;
  66627. }
  66628. return 0;
  66629. });
  66630. this._releaseBuffers();
  66631. };
  66632. /**
  66633. * Adds a new size gradient
  66634. * @param gradient defines the gradient to use (between 0 and 1)
  66635. * @param factor defines the size factor to affect to the specified gradient
  66636. * @returns the current particle system
  66637. */
  66638. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  66639. if (!this._sizeGradients) {
  66640. this._sizeGradients = [];
  66641. }
  66642. this._addFactorGradient(this._sizeGradients, gradient, factor);
  66643. if (this._sizeGradientsTexture) {
  66644. this._sizeGradientsTexture.dispose();
  66645. this._sizeGradientsTexture = null;
  66646. }
  66647. this._releaseBuffers();
  66648. return this;
  66649. };
  66650. /**
  66651. * Remove a specific size gradient
  66652. * @param gradient defines the gradient to remove
  66653. * @returns the current particle system
  66654. */
  66655. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  66656. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  66657. this._sizeGradientsTexture = null;
  66658. return this;
  66659. };
  66660. /**
  66661. * Adds a new angular speed gradient
  66662. * @param gradient defines the gradient to use (between 0 and 1)
  66663. * @param factor defines the angular speed to affect to the specified gradient
  66664. * @returns the current particle system
  66665. */
  66666. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  66667. if (!this._angularSpeedGradients) {
  66668. this._angularSpeedGradients = [];
  66669. }
  66670. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  66671. if (this._angularSpeedGradientsTexture) {
  66672. this._angularSpeedGradientsTexture.dispose();
  66673. this._angularSpeedGradientsTexture = null;
  66674. }
  66675. this._releaseBuffers();
  66676. return this;
  66677. };
  66678. /**
  66679. * Remove a specific angular speed gradient
  66680. * @param gradient defines the gradient to remove
  66681. * @returns the current particle system
  66682. */
  66683. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  66684. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  66685. this._angularSpeedGradientsTexture = null;
  66686. return this;
  66687. };
  66688. /**
  66689. * Adds a new velocity gradient
  66690. * @param gradient defines the gradient to use (between 0 and 1)
  66691. * @param factor defines the velocity to affect to the specified gradient
  66692. * @returns the current particle system
  66693. */
  66694. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  66695. if (!this._velocityGradients) {
  66696. this._velocityGradients = [];
  66697. }
  66698. this._addFactorGradient(this._velocityGradients, gradient, factor);
  66699. if (this._velocityGradientsTexture) {
  66700. this._velocityGradientsTexture.dispose();
  66701. this._velocityGradientsTexture = null;
  66702. }
  66703. this._releaseBuffers();
  66704. return this;
  66705. };
  66706. /**
  66707. * Remove a specific velocity gradient
  66708. * @param gradient defines the gradient to remove
  66709. * @returns the current particle system
  66710. */
  66711. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  66712. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  66713. this._velocityGradientsTexture = null;
  66714. return this;
  66715. };
  66716. /**
  66717. * Adds a new limit velocity gradient
  66718. * @param gradient defines the gradient to use (between 0 and 1)
  66719. * @param factor defines the limit velocity value to affect to the specified gradient
  66720. * @returns the current particle system
  66721. */
  66722. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  66723. if (!this._limitVelocityGradients) {
  66724. this._limitVelocityGradients = [];
  66725. }
  66726. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  66727. if (this._limitVelocityGradientsTexture) {
  66728. this._limitVelocityGradientsTexture.dispose();
  66729. this._limitVelocityGradientsTexture = null;
  66730. }
  66731. this._releaseBuffers();
  66732. return this;
  66733. };
  66734. /**
  66735. * Remove a specific limit velocity gradient
  66736. * @param gradient defines the gradient to remove
  66737. * @returns the current particle system
  66738. */
  66739. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  66740. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  66741. this._limitVelocityGradientsTexture = null;
  66742. return this;
  66743. };
  66744. /**
  66745. * Adds a new drag gradient
  66746. * @param gradient defines the gradient to use (between 0 and 1)
  66747. * @param factor defines the drag value to affect to the specified gradient
  66748. * @returns the current particle system
  66749. */
  66750. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  66751. if (!this._dragGradients) {
  66752. this._dragGradients = [];
  66753. }
  66754. this._addFactorGradient(this._dragGradients, gradient, factor);
  66755. if (this._dragGradientsTexture) {
  66756. this._dragGradientsTexture.dispose();
  66757. this._dragGradientsTexture = null;
  66758. }
  66759. this._releaseBuffers();
  66760. return this;
  66761. };
  66762. /**
  66763. * Remove a specific drag gradient
  66764. * @param gradient defines the gradient to remove
  66765. * @returns the current particle system
  66766. */
  66767. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  66768. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  66769. this._dragGradientsTexture = null;
  66770. return this;
  66771. };
  66772. /**
  66773. * Not supported by GPUParticleSystem
  66774. * @param gradient defines the gradient to use (between 0 and 1)
  66775. * @param factor defines the emit rate value to affect to the specified gradient
  66776. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66777. * @returns the current particle system
  66778. */
  66779. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  66780. // Do nothing as emit rate is not supported by GPUParticleSystem
  66781. return this;
  66782. };
  66783. /**
  66784. * Not supported by GPUParticleSystem
  66785. * @param gradient defines the gradient to remove
  66786. * @returns the current particle system
  66787. */
  66788. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  66789. // Do nothing as emit rate is not supported by GPUParticleSystem
  66790. return this;
  66791. };
  66792. /**
  66793. * Not supported by GPUParticleSystem
  66794. * @param gradient defines the gradient to use (between 0 and 1)
  66795. * @param factor defines the start size value to affect to the specified gradient
  66796. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66797. * @returns the current particle system
  66798. */
  66799. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  66800. // Do nothing as start size is not supported by GPUParticleSystem
  66801. return this;
  66802. };
  66803. /**
  66804. * Not supported by GPUParticleSystem
  66805. * @param gradient defines the gradient to remove
  66806. * @returns the current particle system
  66807. */
  66808. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  66809. // Do nothing as start size is not supported by GPUParticleSystem
  66810. return this;
  66811. };
  66812. /**
  66813. * Not supported by GPUParticleSystem
  66814. * @param gradient defines the gradient to use (between 0 and 1)
  66815. * @param min defines the color remap minimal range
  66816. * @param max defines the color remap maximal range
  66817. * @returns the current particle system
  66818. */
  66819. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  66820. // Do nothing as start size is not supported by GPUParticleSystem
  66821. return this;
  66822. };
  66823. /**
  66824. * Not supported by GPUParticleSystem
  66825. * @param gradient defines the gradient to remove
  66826. * @returns the current particle system
  66827. */
  66828. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  66829. // Do nothing as start size is not supported by GPUParticleSystem
  66830. return this;
  66831. };
  66832. /**
  66833. * Not supported by GPUParticleSystem
  66834. * @param gradient defines the gradient to use (between 0 and 1)
  66835. * @param min defines the alpha remap minimal range
  66836. * @param max defines the alpha remap maximal range
  66837. * @returns the current particle system
  66838. */
  66839. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  66840. // Do nothing as start size is not supported by GPUParticleSystem
  66841. return this;
  66842. };
  66843. /**
  66844. * Not supported by GPUParticleSystem
  66845. * @param gradient defines the gradient to remove
  66846. * @returns the current particle system
  66847. */
  66848. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  66849. // Do nothing as start size is not supported by GPUParticleSystem
  66850. return this;
  66851. };
  66852. /**
  66853. * Not supported by GPUParticleSystem
  66854. * @param gradient defines the gradient to use (between 0 and 1)
  66855. * @param color defines the color to affect to the specified gradient
  66856. * @returns the current particle system
  66857. */
  66858. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  66859. //Not supported by GPUParticleSystem
  66860. return this;
  66861. };
  66862. /**
  66863. * Not supported by GPUParticleSystem
  66864. * @param gradient defines the gradient to remove
  66865. * @returns the current particle system
  66866. */
  66867. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  66868. //Not supported by GPUParticleSystem
  66869. return this;
  66870. };
  66871. /**
  66872. * Not supported by GPUParticleSystem
  66873. * @returns the list of ramp gradients
  66874. */
  66875. GPUParticleSystem.prototype.getRampGradients = function () {
  66876. return null;
  66877. };
  66878. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  66879. /**
  66880. * Not supported by GPUParticleSystem
  66881. * Gets or sets a boolean indicating that ramp gradients must be used
  66882. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  66883. */
  66884. get: function () {
  66885. //Not supported by GPUParticleSystem
  66886. return false;
  66887. },
  66888. set: function (value) {
  66889. //Not supported by GPUParticleSystem
  66890. },
  66891. enumerable: true,
  66892. configurable: true
  66893. });
  66894. /**
  66895. * Not supported by GPUParticleSystem
  66896. * @param gradient defines the gradient to use (between 0 and 1)
  66897. * @param factor defines the life time factor to affect to the specified gradient
  66898. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66899. * @returns the current particle system
  66900. */
  66901. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  66902. //Not supported by GPUParticleSystem
  66903. return this;
  66904. };
  66905. /**
  66906. * Not supported by GPUParticleSystem
  66907. * @param gradient defines the gradient to remove
  66908. * @returns the current particle system
  66909. */
  66910. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  66911. //Not supported by GPUParticleSystem
  66912. return this;
  66913. };
  66914. GPUParticleSystem.prototype._reset = function () {
  66915. this._releaseBuffers();
  66916. };
  66917. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  66918. var updateVertexBuffers = {};
  66919. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  66920. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  66921. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  66922. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  66923. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  66924. var offset = 12;
  66925. if (!this._colorGradientsTexture) {
  66926. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  66927. offset += 4;
  66928. }
  66929. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  66930. offset += 3;
  66931. if (!this._isBillboardBased) {
  66932. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  66933. offset += 3;
  66934. }
  66935. if (this._angularSpeedGradientsTexture) {
  66936. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  66937. offset += 1;
  66938. }
  66939. else {
  66940. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  66941. offset += 2;
  66942. }
  66943. if (this._isAnimationSheetEnabled) {
  66944. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  66945. offset += 1;
  66946. if (this.spriteRandomStartCell) {
  66947. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  66948. offset += 1;
  66949. }
  66950. }
  66951. if (this.noiseTexture) {
  66952. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  66953. offset += 3;
  66954. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  66955. offset += 3;
  66956. }
  66957. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  66958. this._engine.bindArrayBuffer(null);
  66959. return vao;
  66960. };
  66961. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  66962. var renderVertexBuffers = {};
  66963. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  66964. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  66965. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  66966. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  66967. var offset = 12;
  66968. if (!this._colorGradientsTexture) {
  66969. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  66970. offset += 4;
  66971. }
  66972. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  66973. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  66974. }
  66975. offset += 3; // Direction
  66976. if (!this._isBillboardBased) {
  66977. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  66978. offset += 3;
  66979. }
  66980. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  66981. if (this._angularSpeedGradientsTexture) {
  66982. offset++;
  66983. }
  66984. else {
  66985. offset += 2;
  66986. }
  66987. if (this._isAnimationSheetEnabled) {
  66988. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  66989. offset += 1;
  66990. if (this.spriteRandomStartCell) {
  66991. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  66992. offset += 1;
  66993. }
  66994. }
  66995. if (this.noiseTexture) {
  66996. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  66997. offset += 3;
  66998. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  66999. offset += 3;
  67000. }
  67001. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67002. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67003. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67004. this._engine.bindArrayBuffer(null);
  67005. return vao;
  67006. };
  67007. GPUParticleSystem.prototype._initialize = function (force) {
  67008. if (force === void 0) { force = false; }
  67009. if (this._buffer0 && !force) {
  67010. return;
  67011. }
  67012. var engine = this._scene.getEngine();
  67013. var data = new Array();
  67014. if (!this.isBillboardBased) {
  67015. this._attributesStrideSize += 3;
  67016. }
  67017. if (this._colorGradientsTexture) {
  67018. this._attributesStrideSize -= 4;
  67019. }
  67020. if (this._angularSpeedGradientsTexture) {
  67021. this._attributesStrideSize -= 1;
  67022. }
  67023. if (this._isAnimationSheetEnabled) {
  67024. this._attributesStrideSize += 1;
  67025. if (this.spriteRandomStartCell) {
  67026. this._attributesStrideSize += 1;
  67027. }
  67028. }
  67029. if (this.noiseTexture) {
  67030. this._attributesStrideSize += 6;
  67031. }
  67032. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67033. // position
  67034. data.push(0.0);
  67035. data.push(0.0);
  67036. data.push(0.0);
  67037. // Age and life
  67038. data.push(0.0); // create the particle as a dead one to create a new one at start
  67039. data.push(0.0);
  67040. // Seed
  67041. data.push(Math.random());
  67042. data.push(Math.random());
  67043. data.push(Math.random());
  67044. data.push(Math.random());
  67045. // Size
  67046. data.push(0.0);
  67047. data.push(0.0);
  67048. data.push(0.0);
  67049. if (!this._colorGradientsTexture) {
  67050. // color
  67051. data.push(0.0);
  67052. data.push(0.0);
  67053. data.push(0.0);
  67054. data.push(0.0);
  67055. }
  67056. // direction
  67057. data.push(0.0);
  67058. data.push(0.0);
  67059. data.push(0.0);
  67060. if (!this.isBillboardBased) {
  67061. // initialDirection
  67062. data.push(0.0);
  67063. data.push(0.0);
  67064. data.push(0.0);
  67065. }
  67066. // angle
  67067. data.push(0.0);
  67068. if (!this._angularSpeedGradientsTexture) {
  67069. data.push(0.0);
  67070. }
  67071. if (this._isAnimationSheetEnabled) {
  67072. data.push(0.0);
  67073. if (this.spriteRandomStartCell) {
  67074. data.push(0.0);
  67075. }
  67076. }
  67077. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67078. data.push(Math.random());
  67079. data.push(Math.random());
  67080. data.push(Math.random());
  67081. data.push(Math.random());
  67082. data.push(Math.random());
  67083. data.push(Math.random());
  67084. }
  67085. }
  67086. // Sprite data
  67087. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67088. -0.5, 0.5, 0, 1,
  67089. -0.5, -0.5, 0, 0,
  67090. 0.5, -0.5, 1, 0]);
  67091. // Buffers
  67092. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67093. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67094. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67095. // Update VAO
  67096. this._updateVAO = [];
  67097. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67098. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67099. // Render VAO
  67100. this._renderVAO = [];
  67101. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67102. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67103. // Links
  67104. this._sourceBuffer = this._buffer0;
  67105. this._targetBuffer = this._buffer1;
  67106. };
  67107. /** @hidden */
  67108. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67109. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67110. if (this._isBillboardBased) {
  67111. defines += "\n#define BILLBOARD";
  67112. }
  67113. if (this._colorGradientsTexture) {
  67114. defines += "\n#define COLORGRADIENTS";
  67115. }
  67116. if (this._sizeGradientsTexture) {
  67117. defines += "\n#define SIZEGRADIENTS";
  67118. }
  67119. if (this._angularSpeedGradientsTexture) {
  67120. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67121. }
  67122. if (this._velocityGradientsTexture) {
  67123. defines += "\n#define VELOCITYGRADIENTS";
  67124. }
  67125. if (this._limitVelocityGradientsTexture) {
  67126. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67127. }
  67128. if (this._dragGradientsTexture) {
  67129. defines += "\n#define DRAGGRADIENTS";
  67130. }
  67131. if (this.isAnimationSheetEnabled) {
  67132. defines += "\n#define ANIMATESHEET";
  67133. if (this.spriteRandomStartCell) {
  67134. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67135. }
  67136. }
  67137. if (this.noiseTexture) {
  67138. defines += "\n#define NOISE";
  67139. }
  67140. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67141. return;
  67142. }
  67143. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67144. if (!this._colorGradientsTexture) {
  67145. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67146. }
  67147. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67148. if (!this._isBillboardBased) {
  67149. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67150. }
  67151. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67152. if (this.isAnimationSheetEnabled) {
  67153. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67154. if (this.spriteRandomStartCell) {
  67155. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67156. }
  67157. }
  67158. if (this.noiseTexture) {
  67159. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67160. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67161. }
  67162. this._updateEffectOptions.defines = defines;
  67163. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67164. };
  67165. /** @hidden */
  67166. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67167. var defines = "";
  67168. if (this._scene.clipPlane) {
  67169. defines = "\n#define CLIPPLANE";
  67170. }
  67171. if (this._scene.clipPlane2) {
  67172. defines = "\n#define CLIPPLANE2";
  67173. }
  67174. if (this._scene.clipPlane3) {
  67175. defines = "\n#define CLIPPLANE3";
  67176. }
  67177. if (this._scene.clipPlane4) {
  67178. defines = "\n#define CLIPPLANE4";
  67179. }
  67180. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67181. defines = "\n#define BLENDMULTIPLYMODE";
  67182. }
  67183. if (this._isBillboardBased) {
  67184. defines += "\n#define BILLBOARD";
  67185. switch (this.billboardMode) {
  67186. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67187. defines += "\n#define BILLBOARDY";
  67188. break;
  67189. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67190. defines += "\n#define BILLBOARDSTRETCHED";
  67191. break;
  67192. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67193. default:
  67194. break;
  67195. }
  67196. }
  67197. if (this._colorGradientsTexture) {
  67198. defines += "\n#define COLORGRADIENTS";
  67199. }
  67200. if (this.isAnimationSheetEnabled) {
  67201. defines += "\n#define ANIMATESHEET";
  67202. }
  67203. if (this._imageProcessingConfiguration) {
  67204. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67205. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67206. }
  67207. if (this._renderEffect && this._renderEffect.defines === defines) {
  67208. return;
  67209. }
  67210. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67211. var samplers = ["textureSampler", "colorGradientSampler"];
  67212. if (BABYLON.ImageProcessingConfiguration) {
  67213. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67214. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67215. }
  67216. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67217. };
  67218. /**
  67219. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67220. * @param preWarm defines if we are in the pre-warmimg phase
  67221. */
  67222. GPUParticleSystem.prototype.animate = function (preWarm) {
  67223. if (preWarm === void 0) { preWarm = false; }
  67224. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67225. this._actualFrame += this._timeDelta;
  67226. if (!this._stopped) {
  67227. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67228. this.stop();
  67229. }
  67230. }
  67231. };
  67232. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67233. var texture = this[textureName];
  67234. if (!factorGradients || !factorGradients.length || texture) {
  67235. return;
  67236. }
  67237. var data = new Float32Array(this._rawTextureWidth);
  67238. for (var x = 0; x < this._rawTextureWidth; x++) {
  67239. var ratio = x / this._rawTextureWidth;
  67240. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67241. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67242. });
  67243. }
  67244. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67245. };
  67246. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67247. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67248. };
  67249. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67250. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67251. };
  67252. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67253. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67254. };
  67255. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67256. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67257. };
  67258. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67259. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67260. };
  67261. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67262. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67263. return;
  67264. }
  67265. var data = new Uint8Array(this._rawTextureWidth * 4);
  67266. var tmpColor = BABYLON.Tmp.Color4[0];
  67267. for (var x = 0; x < this._rawTextureWidth; x++) {
  67268. var ratio = x / this._rawTextureWidth;
  67269. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67270. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67271. data[x * 4] = tmpColor.r * 255;
  67272. data[x * 4 + 1] = tmpColor.g * 255;
  67273. data[x * 4 + 2] = tmpColor.b * 255;
  67274. data[x * 4 + 3] = tmpColor.a * 255;
  67275. });
  67276. }
  67277. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67278. };
  67279. /**
  67280. * Renders the particle system in its current state
  67281. * @param preWarm defines if the system should only update the particles but not render them
  67282. * @returns the current number of particles
  67283. */
  67284. GPUParticleSystem.prototype.render = function (preWarm) {
  67285. if (preWarm === void 0) { preWarm = false; }
  67286. if (!this._started) {
  67287. return 0;
  67288. }
  67289. this._createColorGradientTexture();
  67290. this._createSizeGradientTexture();
  67291. this._createAngularSpeedGradientTexture();
  67292. this._createVelocityGradientTexture();
  67293. this._createLimitVelocityGradientTexture();
  67294. this._createDragGradientTexture();
  67295. this._recreateUpdateEffect();
  67296. this._recreateRenderEffect();
  67297. if (!this.isReady()) {
  67298. return 0;
  67299. }
  67300. if (!preWarm) {
  67301. if (!this._preWarmDone && this.preWarmCycles) {
  67302. for (var index = 0; index < this.preWarmCycles; index++) {
  67303. this.animate(true);
  67304. this.render(true);
  67305. }
  67306. this._preWarmDone = true;
  67307. }
  67308. if (this._currentRenderId === this._scene.getFrameId()) {
  67309. return 0;
  67310. }
  67311. this._currentRenderId = this._scene.getFrameId();
  67312. }
  67313. // Get everything ready to render
  67314. this._initialize();
  67315. this._accumulatedCount += this.emitRate * this._timeDelta;
  67316. if (this._accumulatedCount > 1) {
  67317. var intPart = this._accumulatedCount | 0;
  67318. this._accumulatedCount -= intPart;
  67319. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67320. }
  67321. if (!this._currentActiveCount) {
  67322. return 0;
  67323. }
  67324. // Enable update effect
  67325. this._engine.enableEffect(this._updateEffect);
  67326. this._engine.setState(false);
  67327. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67328. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67329. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67330. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67331. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67332. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67333. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67334. if (!this._colorGradientsTexture) {
  67335. this._updateEffect.setDirectColor4("color1", this.color1);
  67336. this._updateEffect.setDirectColor4("color2", this.color2);
  67337. }
  67338. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67339. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67340. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67341. this._updateEffect.setVector3("gravity", this.gravity);
  67342. if (this._sizeGradientsTexture) {
  67343. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67344. }
  67345. if (this._angularSpeedGradientsTexture) {
  67346. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67347. }
  67348. if (this._velocityGradientsTexture) {
  67349. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67350. }
  67351. if (this._limitVelocityGradientsTexture) {
  67352. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67353. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67354. }
  67355. if (this._dragGradientsTexture) {
  67356. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67357. }
  67358. if (this.particleEmitterType) {
  67359. this.particleEmitterType.applyToShader(this._updateEffect);
  67360. }
  67361. if (this._isAnimationSheetEnabled) {
  67362. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67363. }
  67364. if (this.noiseTexture) {
  67365. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67366. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67367. }
  67368. var emitterWM;
  67369. if (this.emitter.position) {
  67370. var emitterMesh = this.emitter;
  67371. emitterWM = emitterMesh.getWorldMatrix();
  67372. }
  67373. else {
  67374. var emitterPosition = this.emitter;
  67375. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67376. }
  67377. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67378. // Bind source VAO
  67379. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67380. // Update
  67381. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67382. this._engine.setRasterizerState(false);
  67383. this._engine.beginTransformFeedback(true);
  67384. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67385. this._engine.endTransformFeedback();
  67386. this._engine.setRasterizerState(true);
  67387. this._engine.bindTransformFeedbackBuffer(null);
  67388. if (!preWarm) {
  67389. // Enable render effect
  67390. this._engine.enableEffect(this._renderEffect);
  67391. var viewMatrix = this._scene.getViewMatrix();
  67392. this._renderEffect.setMatrix("view", viewMatrix);
  67393. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67394. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67395. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67396. if (this._colorGradientsTexture) {
  67397. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67398. }
  67399. else {
  67400. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67401. }
  67402. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67403. var baseSize = this.particleTexture.getBaseSize();
  67404. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67405. }
  67406. if (this._isBillboardBased) {
  67407. var camera = this._scene.activeCamera;
  67408. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67409. }
  67410. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67411. var invView = viewMatrix.clone();
  67412. invView.invert();
  67413. this._renderEffect.setMatrix("invView", invView);
  67414. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67415. }
  67416. // image processing
  67417. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67418. this._imageProcessingConfiguration.bind(this._renderEffect);
  67419. }
  67420. // Draw order
  67421. switch (this.blendMode) {
  67422. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67423. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67424. break;
  67425. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67426. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67427. break;
  67428. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67429. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67430. break;
  67431. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67432. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67433. break;
  67434. }
  67435. if (this.forceDepthWrite) {
  67436. this._engine.setDepthWrite(true);
  67437. }
  67438. // Bind source VAO
  67439. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67440. // Render
  67441. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67442. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67443. }
  67444. // Switch VAOs
  67445. this._targetIndex++;
  67446. if (this._targetIndex === 2) {
  67447. this._targetIndex = 0;
  67448. }
  67449. // Switch buffers
  67450. var tmpBuffer = this._sourceBuffer;
  67451. this._sourceBuffer = this._targetBuffer;
  67452. this._targetBuffer = tmpBuffer;
  67453. return this._currentActiveCount;
  67454. };
  67455. /**
  67456. * Rebuilds the particle system
  67457. */
  67458. GPUParticleSystem.prototype.rebuild = function () {
  67459. this._initialize(true);
  67460. };
  67461. GPUParticleSystem.prototype._releaseBuffers = function () {
  67462. if (this._buffer0) {
  67463. this._buffer0.dispose();
  67464. this._buffer0 = null;
  67465. }
  67466. if (this._buffer1) {
  67467. this._buffer1.dispose();
  67468. this._buffer1 = null;
  67469. }
  67470. if (this._spriteBuffer) {
  67471. this._spriteBuffer.dispose();
  67472. this._spriteBuffer = null;
  67473. }
  67474. };
  67475. GPUParticleSystem.prototype._releaseVAOs = function () {
  67476. if (!this._updateVAO) {
  67477. return;
  67478. }
  67479. for (var index = 0; index < this._updateVAO.length; index++) {
  67480. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67481. }
  67482. this._updateVAO = [];
  67483. for (var index = 0; index < this._renderVAO.length; index++) {
  67484. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67485. }
  67486. this._renderVAO = [];
  67487. };
  67488. /**
  67489. * Disposes the particle system and free the associated resources
  67490. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67491. */
  67492. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67493. if (disposeTexture === void 0) { disposeTexture = true; }
  67494. var index = this._scene.particleSystems.indexOf(this);
  67495. if (index > -1) {
  67496. this._scene.particleSystems.splice(index, 1);
  67497. }
  67498. this._releaseBuffers();
  67499. this._releaseVAOs();
  67500. if (this._colorGradientsTexture) {
  67501. this._colorGradientsTexture.dispose();
  67502. this._colorGradientsTexture = null;
  67503. }
  67504. if (this._sizeGradientsTexture) {
  67505. this._sizeGradientsTexture.dispose();
  67506. this._sizeGradientsTexture = null;
  67507. }
  67508. if (this._angularSpeedGradientsTexture) {
  67509. this._angularSpeedGradientsTexture.dispose();
  67510. this._angularSpeedGradientsTexture = null;
  67511. }
  67512. if (this._velocityGradientsTexture) {
  67513. this._velocityGradientsTexture.dispose();
  67514. this._velocityGradientsTexture = null;
  67515. }
  67516. if (this._limitVelocityGradientsTexture) {
  67517. this._limitVelocityGradientsTexture.dispose();
  67518. this._limitVelocityGradientsTexture = null;
  67519. }
  67520. if (this._dragGradientsTexture) {
  67521. this._dragGradientsTexture.dispose();
  67522. this._dragGradientsTexture = null;
  67523. }
  67524. if (this._randomTexture) {
  67525. this._randomTexture.dispose();
  67526. this._randomTexture = null;
  67527. }
  67528. if (this._randomTexture2) {
  67529. this._randomTexture2.dispose();
  67530. this._randomTexture2 = null;
  67531. }
  67532. if (disposeTexture && this.particleTexture) {
  67533. this.particleTexture.dispose();
  67534. this.particleTexture = null;
  67535. }
  67536. if (disposeTexture && this.noiseTexture) {
  67537. this.noiseTexture.dispose();
  67538. this.noiseTexture = null;
  67539. }
  67540. // Callback
  67541. this.onDisposeObservable.notifyObservers(this);
  67542. this.onDisposeObservable.clear();
  67543. };
  67544. /**
  67545. * Clones the particle system.
  67546. * @param name The name of the cloned object
  67547. * @param newEmitter The new emitter to use
  67548. * @returns the cloned particle system
  67549. */
  67550. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  67551. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  67552. BABYLON.Tools.DeepCopy(this, result);
  67553. if (newEmitter === undefined) {
  67554. newEmitter = this.emitter;
  67555. }
  67556. result.emitter = newEmitter;
  67557. if (this.particleTexture) {
  67558. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  67559. }
  67560. return result;
  67561. };
  67562. /**
  67563. * Serializes the particle system to a JSON object.
  67564. * @returns the JSON object
  67565. */
  67566. GPUParticleSystem.prototype.serialize = function () {
  67567. var serializationObject = {};
  67568. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  67569. serializationObject.activeParticleCount = this.activeParticleCount;
  67570. return serializationObject;
  67571. };
  67572. /**
  67573. * Parses a JSON object to create a GPU particle system.
  67574. * @param parsedParticleSystem The JSON object to parse
  67575. * @param scene The scene to create the particle system in
  67576. * @param rootUrl The root url to use to load external dependencies like texture
  67577. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  67578. * @returns the parsed GPU particle system
  67579. */
  67580. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  67581. if (doNotStart === void 0) { doNotStart = false; }
  67582. var name = parsedParticleSystem.name;
  67583. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  67584. if (parsedParticleSystem.activeParticleCount) {
  67585. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  67586. }
  67587. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  67588. // Auto start
  67589. if (parsedParticleSystem.preventAutoStart) {
  67590. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  67591. }
  67592. if (!doNotStart && !particleSystem.preventAutoStart) {
  67593. particleSystem.start();
  67594. }
  67595. return particleSystem;
  67596. };
  67597. return GPUParticleSystem;
  67598. }(BABYLON.BaseParticleSystem));
  67599. BABYLON.GPUParticleSystem = GPUParticleSystem;
  67600. })(BABYLON || (BABYLON = {}));
  67601. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  67602. var BABYLON;
  67603. (function (BABYLON) {
  67604. /**
  67605. * Represents one particle of a solid particle system.
  67606. */
  67607. var SolidParticle = /** @class */ (function () {
  67608. /**
  67609. * Creates a Solid Particle object.
  67610. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  67611. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  67612. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  67613. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  67614. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  67615. * @param shapeId (integer) is the model shape identifier in the SPS.
  67616. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  67617. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  67618. */
  67619. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  67620. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  67621. /**
  67622. * particle global index
  67623. */
  67624. this.idx = 0;
  67625. /**
  67626. * The color of the particle
  67627. */
  67628. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67629. /**
  67630. * The world space position of the particle.
  67631. */
  67632. this.position = BABYLON.Vector3.Zero();
  67633. /**
  67634. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  67635. */
  67636. this.rotation = BABYLON.Vector3.Zero();
  67637. /**
  67638. * The scaling of the particle.
  67639. */
  67640. this.scaling = BABYLON.Vector3.One();
  67641. /**
  67642. * The uvs of the particle.
  67643. */
  67644. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  67645. /**
  67646. * The current speed of the particle.
  67647. */
  67648. this.velocity = BABYLON.Vector3.Zero();
  67649. /**
  67650. * The pivot point in the particle local space.
  67651. */
  67652. this.pivot = BABYLON.Vector3.Zero();
  67653. /**
  67654. * Must the particle be translated from its pivot point in its local space ?
  67655. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  67656. * Default : false
  67657. */
  67658. this.translateFromPivot = false;
  67659. /**
  67660. * Is the particle active or not ?
  67661. */
  67662. this.alive = true;
  67663. /**
  67664. * Is the particle visible or not ?
  67665. */
  67666. this.isVisible = true;
  67667. /**
  67668. * Index of this particle in the global "positions" array (Internal use)
  67669. * @hidden
  67670. */
  67671. this._pos = 0;
  67672. /**
  67673. * @hidden Index of this particle in the global "indices" array (Internal use)
  67674. */
  67675. this._ind = 0;
  67676. /**
  67677. * ModelShape id of this particle
  67678. */
  67679. this.shapeId = 0;
  67680. /**
  67681. * Index of the particle in its shape id (Internal use)
  67682. */
  67683. this.idxInShape = 0;
  67684. /**
  67685. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  67686. */
  67687. this._stillInvisible = false;
  67688. /**
  67689. * @hidden Last computed particle rotation matrix
  67690. */
  67691. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  67692. /**
  67693. * Parent particle Id, if any.
  67694. * Default null.
  67695. */
  67696. this.parentId = null;
  67697. /**
  67698. * @hidden Internal global position in the SPS.
  67699. */
  67700. this._globalPosition = BABYLON.Vector3.Zero();
  67701. this.idx = particleIndex;
  67702. this._pos = positionIndex;
  67703. this._ind = indiceIndex;
  67704. this._model = model;
  67705. this.shapeId = shapeId;
  67706. this.idxInShape = idxInShape;
  67707. this._sps = sps;
  67708. if (modelBoundingInfo) {
  67709. this._modelBoundingInfo = modelBoundingInfo;
  67710. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  67711. }
  67712. }
  67713. Object.defineProperty(SolidParticle.prototype, "scale", {
  67714. /**
  67715. * Legacy support, changed scale to scaling
  67716. */
  67717. get: function () {
  67718. return this.scaling;
  67719. },
  67720. /**
  67721. * Legacy support, changed scale to scaling
  67722. */
  67723. set: function (scale) {
  67724. this.scaling = scale;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  67730. /**
  67731. * Legacy support, changed quaternion to rotationQuaternion
  67732. */
  67733. get: function () {
  67734. return this.rotationQuaternion;
  67735. },
  67736. /**
  67737. * Legacy support, changed quaternion to rotationQuaternion
  67738. */
  67739. set: function (q) {
  67740. this.rotationQuaternion = q;
  67741. },
  67742. enumerable: true,
  67743. configurable: true
  67744. });
  67745. /**
  67746. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  67747. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  67748. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  67749. * @returns true if it intersects
  67750. */
  67751. SolidParticle.prototype.intersectsMesh = function (target) {
  67752. if (!this._boundingInfo || !target._boundingInfo) {
  67753. return false;
  67754. }
  67755. if (this._sps._bSphereOnly) {
  67756. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  67757. }
  67758. return this._boundingInfo.intersects(target._boundingInfo, false);
  67759. };
  67760. /**
  67761. * get the rotation matrix of the particle
  67762. * @hidden
  67763. */
  67764. SolidParticle.prototype.getRotationMatrix = function (m) {
  67765. var quaternion;
  67766. if (this.rotationQuaternion) {
  67767. quaternion = this.rotationQuaternion;
  67768. }
  67769. else {
  67770. quaternion = BABYLON.Tmp.Quaternion[0];
  67771. var rotation = this.rotation;
  67772. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  67773. }
  67774. quaternion.toRotationMatrix(m);
  67775. };
  67776. return SolidParticle;
  67777. }());
  67778. BABYLON.SolidParticle = SolidParticle;
  67779. /**
  67780. * Represents the shape of the model used by one particle of a solid particle system.
  67781. * SPS internal tool, don't use it manually.
  67782. */
  67783. var ModelShape = /** @class */ (function () {
  67784. /**
  67785. * 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.
  67786. * SPS internal tool, don't use it manually.
  67787. * @hidden
  67788. */
  67789. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  67790. /**
  67791. * length of the shape in the model indices array (internal use)
  67792. * @hidden
  67793. */
  67794. this._indicesLength = 0;
  67795. this.shapeID = id;
  67796. this._shape = shape;
  67797. this._indicesLength = indicesLength;
  67798. this._shapeUV = shapeUV;
  67799. this._positionFunction = posFunction;
  67800. this._vertexFunction = vtxFunction;
  67801. }
  67802. return ModelShape;
  67803. }());
  67804. BABYLON.ModelShape = ModelShape;
  67805. /**
  67806. * Represents a Depth Sorted Particle in the solid particle system.
  67807. */
  67808. var DepthSortedParticle = /** @class */ (function () {
  67809. function DepthSortedParticle() {
  67810. /**
  67811. * Index of the particle in the "indices" array
  67812. */
  67813. this.ind = 0;
  67814. /**
  67815. * Length of the particle shape in the "indices" array
  67816. */
  67817. this.indicesLength = 0;
  67818. /**
  67819. * Squared distance from the particle to the camera
  67820. */
  67821. this.sqDistance = 0.0;
  67822. }
  67823. return DepthSortedParticle;
  67824. }());
  67825. BABYLON.DepthSortedParticle = DepthSortedParticle;
  67826. })(BABYLON || (BABYLON = {}));
  67827. //# sourceMappingURL=babylon.solidParticle.js.map
  67828. var BABYLON;
  67829. (function (BABYLON) {
  67830. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  67831. /**
  67832. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  67833. *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.
  67834. * The SPS is also a particle system. It provides some methods to manage the particles.
  67835. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  67836. *
  67837. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  67838. */
  67839. var SolidParticleSystem = /** @class */ (function () {
  67840. /**
  67841. * Creates a SPS (Solid Particle System) object.
  67842. * @param name (String) is the SPS name, this will be the underlying mesh name.
  67843. * @param scene (Scene) is the scene in which the SPS is added.
  67844. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  67845. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  67846. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  67847. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  67848. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  67849. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  67850. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  67851. */
  67852. function SolidParticleSystem(name, scene, options) {
  67853. /**
  67854. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  67855. * Example : var p = SPS.particles[i];
  67856. */
  67857. this.particles = new Array();
  67858. /**
  67859. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  67860. */
  67861. this.nbParticles = 0;
  67862. /**
  67863. * If the particles must ever face the camera (default false). Useful for planar particles.
  67864. */
  67865. this.billboard = false;
  67866. /**
  67867. * Recompute normals when adding a shape
  67868. */
  67869. this.recomputeNormals = true;
  67870. /**
  67871. * This a counter ofr your own usage. It's not set by any SPS functions.
  67872. */
  67873. this.counter = 0;
  67874. /**
  67875. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  67876. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  67877. */
  67878. this.vars = {};
  67879. /**
  67880. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  67881. * @hidden
  67882. */
  67883. this._bSphereOnly = false;
  67884. /**
  67885. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  67886. * @hidden
  67887. */
  67888. this._bSphereRadiusFactor = 1.0;
  67889. this._positions = new Array();
  67890. this._indices = new Array();
  67891. this._normals = new Array();
  67892. this._colors = new Array();
  67893. this._uvs = new Array();
  67894. this._index = 0; // indices index
  67895. this._updatable = true;
  67896. this._pickable = false;
  67897. this._isVisibilityBoxLocked = false;
  67898. this._alwaysVisible = false;
  67899. this._depthSort = false;
  67900. this._shapeCounter = 0;
  67901. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  67902. this._color = new BABYLON.Color4(0, 0, 0, 0);
  67903. this._computeParticleColor = true;
  67904. this._computeParticleTexture = true;
  67905. this._computeParticleRotation = true;
  67906. this._computeParticleVertex = false;
  67907. this._computeBoundingBox = false;
  67908. this._depthSortParticles = true;
  67909. this._mustUnrotateFixedNormals = false;
  67910. this._particlesIntersect = false;
  67911. this._needs32Bits = false;
  67912. this.name = name;
  67913. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67914. this._camera = scene.activeCamera;
  67915. this._pickable = options ? options.isPickable : false;
  67916. this._depthSort = options ? options.enableDepthSort : false;
  67917. this._particlesIntersect = options ? options.particleIntersection : false;
  67918. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  67919. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  67920. if (options && options.updatable !== undefined) {
  67921. this._updatable = options.updatable;
  67922. }
  67923. else {
  67924. this._updatable = true;
  67925. }
  67926. if (this._pickable) {
  67927. this.pickedParticles = [];
  67928. }
  67929. if (this._depthSort) {
  67930. this.depthSortedParticles = [];
  67931. }
  67932. }
  67933. /**
  67934. * Builds the SPS underlying mesh. Returns a standard Mesh.
  67935. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  67936. * @returns the created mesh
  67937. */
  67938. SolidParticleSystem.prototype.buildMesh = function () {
  67939. if (this.nbParticles === 0) {
  67940. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  67941. this.addShape(triangle, 1);
  67942. triangle.dispose();
  67943. }
  67944. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  67945. this._positions32 = new Float32Array(this._positions);
  67946. this._uvs32 = new Float32Array(this._uvs);
  67947. this._colors32 = new Float32Array(this._colors);
  67948. if (this.recomputeNormals) {
  67949. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  67950. }
  67951. this._normals32 = new Float32Array(this._normals);
  67952. this._fixedNormal32 = new Float32Array(this._normals);
  67953. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  67954. this._unrotateFixedNormals();
  67955. }
  67956. var vertexData = new BABYLON.VertexData();
  67957. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  67958. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  67959. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  67960. if (this._uvs32.length > 0) {
  67961. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  67962. }
  67963. if (this._colors32.length > 0) {
  67964. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  67965. }
  67966. var mesh = new BABYLON.Mesh(this.name, this._scene);
  67967. vertexData.applyToMesh(mesh, this._updatable);
  67968. this.mesh = mesh;
  67969. this.mesh.isPickable = this._pickable;
  67970. // free memory
  67971. if (!this._depthSort) {
  67972. this._indices = null;
  67973. }
  67974. this._positions = null;
  67975. this._normals = null;
  67976. this._uvs = null;
  67977. this._colors = null;
  67978. if (!this._updatable) {
  67979. this.particles.length = 0;
  67980. }
  67981. return mesh;
  67982. };
  67983. /**
  67984. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  67985. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  67986. * Thus the particles generated from `digest()` have their property `position` set yet.
  67987. * @param mesh ( Mesh ) is the mesh to be digested
  67988. * @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
  67989. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  67990. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  67991. * @returns the current SPS
  67992. */
  67993. SolidParticleSystem.prototype.digest = function (mesh, options) {
  67994. var size = (options && options.facetNb) || 1;
  67995. var number = (options && options.number) || 0;
  67996. var delta = (options && options.delta) || 0;
  67997. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67998. var meshInd = mesh.getIndices();
  67999. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68000. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68001. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68002. var f = 0; // facet counter
  68003. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68004. // compute size from number
  68005. if (number) {
  68006. number = (number > totalFacets) ? totalFacets : number;
  68007. size = Math.round(totalFacets / number);
  68008. delta = 0;
  68009. }
  68010. else {
  68011. size = (size > totalFacets) ? totalFacets : size;
  68012. }
  68013. var facetPos = []; // submesh positions
  68014. var facetInd = []; // submesh indices
  68015. var facetUV = []; // submesh UV
  68016. var facetCol = []; // submesh colors
  68017. var barycenter = BABYLON.Vector3.Zero();
  68018. var sizeO = size;
  68019. while (f < totalFacets) {
  68020. size = sizeO + Math.floor((1 + delta) * Math.random());
  68021. if (f > totalFacets - size) {
  68022. size = totalFacets - f;
  68023. }
  68024. // reset temp arrays
  68025. facetPos.length = 0;
  68026. facetInd.length = 0;
  68027. facetUV.length = 0;
  68028. facetCol.length = 0;
  68029. // iterate over "size" facets
  68030. var fi = 0;
  68031. for (var j = f * 3; j < (f + size) * 3; j++) {
  68032. facetInd.push(fi);
  68033. var i = meshInd[j];
  68034. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68035. if (meshUV) {
  68036. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68037. }
  68038. if (meshCol) {
  68039. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68040. }
  68041. fi++;
  68042. }
  68043. // create a model shape for each single particle
  68044. var idx = this.nbParticles;
  68045. var shape = this._posToShape(facetPos);
  68046. var shapeUV = this._uvsToShapeUV(facetUV);
  68047. // compute the barycenter of the shape
  68048. var v;
  68049. for (v = 0; v < shape.length; v++) {
  68050. barycenter.addInPlace(shape[v]);
  68051. }
  68052. barycenter.scaleInPlace(1 / shape.length);
  68053. // shift the shape from its barycenter to the origin
  68054. for (v = 0; v < shape.length; v++) {
  68055. shape[v].subtractInPlace(barycenter);
  68056. }
  68057. var bInfo;
  68058. if (this._particlesIntersect) {
  68059. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68060. }
  68061. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68062. // add the particle in the SPS
  68063. var currentPos = this._positions.length;
  68064. var currentInd = this._indices.length;
  68065. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68066. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68067. // initialize the particle position
  68068. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68069. this._index += shape.length;
  68070. idx++;
  68071. this.nbParticles++;
  68072. this._shapeCounter++;
  68073. f += size;
  68074. }
  68075. return this;
  68076. };
  68077. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68078. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68079. var index = 0;
  68080. var idx = 0;
  68081. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68082. var quaternion = BABYLON.Tmp.Quaternion[0];
  68083. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68084. for (var p = 0; p < this.particles.length; p++) {
  68085. var particle = this.particles[p];
  68086. var shape = particle._model._shape;
  68087. // computing the inverse of the rotation matrix from the quaternion
  68088. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68089. if (particle.rotationQuaternion) {
  68090. particle.rotationQuaternion.conjugateToRef(quaternion);
  68091. }
  68092. else {
  68093. var rotation = particle.rotation;
  68094. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68095. quaternion.conjugateInPlace();
  68096. }
  68097. quaternion.toRotationMatrix(invertedRotMatrix);
  68098. for (var pt = 0; pt < shape.length; pt++) {
  68099. idx = index + pt * 3;
  68100. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68101. tmpNormal.toArray(this._fixedNormal32, idx);
  68102. }
  68103. index = idx + 3;
  68104. }
  68105. };
  68106. //reset copy
  68107. SolidParticleSystem.prototype._resetCopy = function () {
  68108. var copy = this._copy;
  68109. copy.position.setAll(0);
  68110. copy.rotation.setAll(0);
  68111. copy.rotationQuaternion = null;
  68112. copy.scaling.setAll(1);
  68113. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68114. copy.color = null;
  68115. copy.translateFromPivot = false;
  68116. };
  68117. // _meshBuilder : inserts the shape model in the global SPS mesh
  68118. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68119. var i;
  68120. var u = 0;
  68121. var c = 0;
  68122. var n = 0;
  68123. this._resetCopy();
  68124. var copy = this._copy;
  68125. if (options && options.positionFunction) { // call to custom positionFunction
  68126. options.positionFunction(copy, idx, idxInShape);
  68127. this._mustUnrotateFixedNormals = true;
  68128. }
  68129. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68130. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68131. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68132. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68133. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68134. copy.getRotationMatrix(rotMatrix);
  68135. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68136. if (copy.translateFromPivot) {
  68137. pivotBackTranslation.setAll(0.0);
  68138. }
  68139. else {
  68140. pivotBackTranslation.copyFrom(scaledPivot);
  68141. }
  68142. for (i = 0; i < shape.length; i++) {
  68143. tmpVertex.copyFrom(shape[i]);
  68144. if (options && options.vertexFunction) {
  68145. options.vertexFunction(copy, tmpVertex, i);
  68146. }
  68147. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68148. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68149. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68150. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68151. if (meshUV) {
  68152. var copyUvs = copy.uvs;
  68153. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68154. u += 2;
  68155. }
  68156. if (copy.color) {
  68157. this._color = copy.color;
  68158. }
  68159. else {
  68160. var color = this._color;
  68161. if (meshCol && meshCol[c] !== undefined) {
  68162. color.r = meshCol[c];
  68163. color.g = meshCol[c + 1];
  68164. color.b = meshCol[c + 2];
  68165. color.a = meshCol[c + 3];
  68166. }
  68167. else {
  68168. color.r = 1.0;
  68169. color.g = 1.0;
  68170. color.b = 1.0;
  68171. color.a = 1.0;
  68172. }
  68173. }
  68174. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68175. c += 4;
  68176. if (!this.recomputeNormals && meshNor) {
  68177. tmpVertex.x = meshNor[n];
  68178. tmpVertex.y = meshNor[n + 1];
  68179. tmpVertex.z = meshNor[n + 2];
  68180. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68181. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68182. n += 3;
  68183. }
  68184. }
  68185. for (i = 0; i < meshInd.length; i++) {
  68186. var current_ind = p + meshInd[i];
  68187. indices.push(current_ind);
  68188. if (current_ind > 65535) {
  68189. this._needs32Bits = true;
  68190. }
  68191. }
  68192. if (this._pickable) {
  68193. var nbfaces = meshInd.length / 3;
  68194. for (i = 0; i < nbfaces; i++) {
  68195. this.pickedParticles.push({ idx: idx, faceId: i });
  68196. }
  68197. }
  68198. if (this._depthSort) {
  68199. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68200. }
  68201. return copy;
  68202. };
  68203. // returns a shape array from positions array
  68204. SolidParticleSystem.prototype._posToShape = function (positions) {
  68205. var shape = [];
  68206. for (var i = 0; i < positions.length; i += 3) {
  68207. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68208. }
  68209. return shape;
  68210. };
  68211. // returns a shapeUV array from a Vector4 uvs
  68212. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68213. var shapeUV = [];
  68214. if (uvs) {
  68215. for (var i = 0; i < uvs.length; i++) {
  68216. shapeUV.push(uvs[i]);
  68217. }
  68218. }
  68219. return shapeUV;
  68220. };
  68221. // adds a new particle object in the particles array
  68222. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68223. if (bInfo === void 0) { bInfo = null; }
  68224. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68225. this.particles.push(sp);
  68226. return sp;
  68227. };
  68228. /**
  68229. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68230. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68231. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68232. * @param nb (positive integer) the number of particles to be created from this model
  68233. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68234. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68235. * @returns the number of shapes in the system
  68236. */
  68237. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68238. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68239. var meshInd = mesh.getIndices();
  68240. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68241. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68242. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68243. var bbInfo;
  68244. if (this._particlesIntersect) {
  68245. bbInfo = mesh.getBoundingInfo();
  68246. }
  68247. var shape = this._posToShape(meshPos);
  68248. var shapeUV = this._uvsToShapeUV(meshUV);
  68249. var posfunc = options ? options.positionFunction : null;
  68250. var vtxfunc = options ? options.vertexFunction : null;
  68251. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68252. // particles
  68253. var sp;
  68254. var currentCopy;
  68255. var idx = this.nbParticles;
  68256. for (var i = 0; i < nb; i++) {
  68257. var currentPos = this._positions.length;
  68258. var currentInd = this._indices.length;
  68259. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68260. if (this._updatable) {
  68261. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68262. sp.position.copyFrom(currentCopy.position);
  68263. sp.rotation.copyFrom(currentCopy.rotation);
  68264. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68265. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68266. }
  68267. if (currentCopy.color && sp.color) {
  68268. sp.color.copyFrom(currentCopy.color);
  68269. }
  68270. sp.scaling.copyFrom(currentCopy.scaling);
  68271. sp.uvs.copyFrom(currentCopy.uvs);
  68272. }
  68273. this._index += shape.length;
  68274. idx++;
  68275. }
  68276. this.nbParticles += nb;
  68277. this._shapeCounter++;
  68278. return this._shapeCounter - 1;
  68279. };
  68280. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68281. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68282. this._resetCopy();
  68283. var copy = this._copy;
  68284. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68285. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68286. }
  68287. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68288. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68289. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68290. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68291. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68292. copy.getRotationMatrix(rotMatrix);
  68293. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68294. if (copy.translateFromPivot) {
  68295. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68296. }
  68297. else {
  68298. pivotBackTranslation.copyFrom(scaledPivot);
  68299. }
  68300. var shape = particle._model._shape;
  68301. for (var pt = 0; pt < shape.length; pt++) {
  68302. tmpVertex.copyFrom(shape[pt]);
  68303. if (particle._model._vertexFunction) {
  68304. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68305. }
  68306. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68307. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68308. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68309. }
  68310. particle.position.setAll(0.0);
  68311. particle.rotation.setAll(0.0);
  68312. particle.rotationQuaternion = null;
  68313. particle.scaling.setAll(1.0);
  68314. particle.uvs.setAll(0.0);
  68315. particle.pivot.setAll(0.0);
  68316. particle.translateFromPivot = false;
  68317. particle.parentId = null;
  68318. };
  68319. /**
  68320. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68321. * @returns the SPS.
  68322. */
  68323. SolidParticleSystem.prototype.rebuildMesh = function () {
  68324. for (var p = 0; p < this.particles.length; p++) {
  68325. this._rebuildParticle(this.particles[p]);
  68326. }
  68327. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68328. return this;
  68329. };
  68330. /**
  68331. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68332. * This method calls `updateParticle()` for each particle of the SPS.
  68333. * For an animated SPS, it is usually called within the render loop.
  68334. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68335. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68336. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68337. * @returns the SPS.
  68338. */
  68339. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68340. if (start === void 0) { start = 0; }
  68341. if (end === void 0) { end = this.nbParticles - 1; }
  68342. if (update === void 0) { update = true; }
  68343. if (!this._updatable) {
  68344. return this;
  68345. }
  68346. // custom beforeUpdate
  68347. this.beforeUpdateParticles(start, end, update);
  68348. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68349. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68350. var mesh = this.mesh;
  68351. var colors32 = this._colors32;
  68352. var positions32 = this._positions32;
  68353. var normals32 = this._normals32;
  68354. var uvs32 = this._uvs32;
  68355. var indices32 = this._indices32;
  68356. var indices = this._indices;
  68357. var fixedNormal32 = this._fixedNormal32;
  68358. var tempVectors = BABYLON.Tmp.Vector3;
  68359. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68360. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68361. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68362. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68363. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68364. var camInvertedPosition = tempVectors[10].setAll(0);
  68365. // cases when the World Matrix is to be computed first
  68366. if (this.billboard || this._depthSort) {
  68367. this.mesh.computeWorldMatrix(true);
  68368. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68369. }
  68370. // if the particles will always face the camera
  68371. if (this.billboard) {
  68372. // compute the camera position and un-rotate it by the current mesh rotation
  68373. var tmpVertex = tempVectors[0];
  68374. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68375. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68376. camAxisZ.normalize();
  68377. // same for camera up vector extracted from the cam view matrix
  68378. var view = this._camera.getViewMatrix(true);
  68379. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68380. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68381. camAxisY.normalize();
  68382. camAxisX.normalize();
  68383. }
  68384. // if depthSort, compute the camera global position in the mesh local system
  68385. if (this._depthSort) {
  68386. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68387. }
  68388. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68389. var idx = 0; // current position index in the global array positions32
  68390. var index = 0; // position start index in the global array positions32 of the current particle
  68391. var colidx = 0; // current color index in the global array colors32
  68392. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68393. var uvidx = 0; // current uv index in the global array uvs32
  68394. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68395. var pt = 0; // current index in the particle model shape
  68396. if (this.mesh.isFacetDataEnabled) {
  68397. this._computeBoundingBox = true;
  68398. }
  68399. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68400. if (this._computeBoundingBox) {
  68401. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68402. var boundingInfo = this.mesh._boundingInfo;
  68403. if (boundingInfo) {
  68404. minimum.copyFrom(boundingInfo.minimum);
  68405. maximum.copyFrom(boundingInfo.maximum);
  68406. }
  68407. }
  68408. }
  68409. // particle loop
  68410. index = this.particles[start]._pos;
  68411. var vpos = (index / 3) | 0;
  68412. colorIndex = vpos * 4;
  68413. uvIndex = vpos * 2;
  68414. for (var p = start; p <= end; p++) {
  68415. var particle = this.particles[p];
  68416. // call to custom user function to update the particle properties
  68417. this.updateParticle(particle);
  68418. var shape = particle._model._shape;
  68419. var shapeUV = particle._model._shapeUV;
  68420. var particleRotationMatrix = particle._rotationMatrix;
  68421. var particlePosition = particle.position;
  68422. var particleRotation = particle.rotation;
  68423. var particleScaling = particle.scaling;
  68424. var particleGlobalPosition = particle._globalPosition;
  68425. // camera-particle distance for depth sorting
  68426. if (this._depthSort && this._depthSortParticles) {
  68427. var dsp = this.depthSortedParticles[p];
  68428. dsp.ind = particle._ind;
  68429. dsp.indicesLength = particle._model._indicesLength;
  68430. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68431. }
  68432. // skip the computations for inactive or already invisible particles
  68433. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68434. // increment indexes for the next particle
  68435. pt = shape.length;
  68436. index += pt * 3;
  68437. colorIndex += pt * 4;
  68438. uvIndex += pt * 2;
  68439. continue;
  68440. }
  68441. if (particle.isVisible) {
  68442. particle._stillInvisible = false; // un-mark permanent invisibility
  68443. var scaledPivot = tempVectors[12];
  68444. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68445. // particle rotation matrix
  68446. if (this.billboard) {
  68447. particleRotation.x = 0.0;
  68448. particleRotation.y = 0.0;
  68449. }
  68450. if (this._computeParticleRotation || this.billboard) {
  68451. particle.getRotationMatrix(rotMatrix);
  68452. }
  68453. var particleHasParent = (particle.parentId !== null);
  68454. if (particleHasParent) {
  68455. var parent_1 = this.particles[particle.parentId];
  68456. var parentRotationMatrix = parent_1._rotationMatrix;
  68457. var parentGlobalPosition = parent_1._globalPosition;
  68458. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68459. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68460. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68461. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68462. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68463. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68464. if (this._computeParticleRotation || this.billboard) {
  68465. var rotMatrixValues = rotMatrix.m;
  68466. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68467. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68468. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68469. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68470. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68471. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68472. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68473. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68474. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68475. }
  68476. }
  68477. else {
  68478. particleGlobalPosition.x = particlePosition.x;
  68479. particleGlobalPosition.y = particlePosition.y;
  68480. particleGlobalPosition.z = particlePosition.z;
  68481. if (this._computeParticleRotation || this.billboard) {
  68482. var rotMatrixValues = rotMatrix.m;
  68483. particleRotationMatrix[0] = rotMatrixValues[0];
  68484. particleRotationMatrix[1] = rotMatrixValues[1];
  68485. particleRotationMatrix[2] = rotMatrixValues[2];
  68486. particleRotationMatrix[3] = rotMatrixValues[4];
  68487. particleRotationMatrix[4] = rotMatrixValues[5];
  68488. particleRotationMatrix[5] = rotMatrixValues[6];
  68489. particleRotationMatrix[6] = rotMatrixValues[8];
  68490. particleRotationMatrix[7] = rotMatrixValues[9];
  68491. particleRotationMatrix[8] = rotMatrixValues[10];
  68492. }
  68493. }
  68494. var pivotBackTranslation = tempVectors[11];
  68495. if (particle.translateFromPivot) {
  68496. pivotBackTranslation.setAll(0.0);
  68497. }
  68498. else {
  68499. pivotBackTranslation.copyFrom(scaledPivot);
  68500. }
  68501. // particle vertex loop
  68502. for (pt = 0; pt < shape.length; pt++) {
  68503. idx = index + pt * 3;
  68504. colidx = colorIndex + pt * 4;
  68505. uvidx = uvIndex + pt * 2;
  68506. var tmpVertex = tempVectors[0];
  68507. tmpVertex.copyFrom(shape[pt]);
  68508. if (this._computeParticleVertex) {
  68509. this.updateParticleVertex(particle, tmpVertex, pt);
  68510. }
  68511. // positions
  68512. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  68513. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  68514. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  68515. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  68516. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  68517. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  68518. rotatedX += pivotBackTranslation.x;
  68519. rotatedY += pivotBackTranslation.y;
  68520. rotatedZ += pivotBackTranslation.z;
  68521. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68522. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68523. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68524. if (this._computeBoundingBox) {
  68525. minimum.minimizeInPlaceFromFloats(px, py, pz);
  68526. maximum.maximizeInPlaceFromFloats(px, py, pz);
  68527. }
  68528. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  68529. if (!this._computeParticleVertex) {
  68530. var normalx = fixedNormal32[idx];
  68531. var normaly = fixedNormal32[idx + 1];
  68532. var normalz = fixedNormal32[idx + 2];
  68533. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  68534. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  68535. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  68536. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  68537. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  68538. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  68539. }
  68540. if (this._computeParticleColor && particle.color) {
  68541. var color = particle.color;
  68542. var colors32_1 = this._colors32;
  68543. colors32_1[colidx] = color.r;
  68544. colors32_1[colidx + 1] = color.g;
  68545. colors32_1[colidx + 2] = color.b;
  68546. colors32_1[colidx + 3] = color.a;
  68547. }
  68548. if (this._computeParticleTexture) {
  68549. var uvs = particle.uvs;
  68550. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68551. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68552. }
  68553. }
  68554. }
  68555. // particle just set invisible : scaled to zero and positioned at the origin
  68556. else {
  68557. particle._stillInvisible = true; // mark the particle as invisible
  68558. for (pt = 0; pt < shape.length; pt++) {
  68559. idx = index + pt * 3;
  68560. colidx = colorIndex + pt * 4;
  68561. uvidx = uvIndex + pt * 2;
  68562. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  68563. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  68564. if (this._computeParticleColor && particle.color) {
  68565. var color = particle.color;
  68566. colors32[colidx] = color.r;
  68567. colors32[colidx + 1] = color.g;
  68568. colors32[colidx + 2] = color.b;
  68569. colors32[colidx + 3] = color.a;
  68570. }
  68571. if (this._computeParticleTexture) {
  68572. var uvs = particle.uvs;
  68573. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68574. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68575. }
  68576. }
  68577. }
  68578. // if the particle intersections must be computed : update the bbInfo
  68579. if (this._particlesIntersect) {
  68580. var bInfo = particle._boundingInfo;
  68581. var bBox = bInfo.boundingBox;
  68582. var bSphere = bInfo.boundingSphere;
  68583. var modelBoundingInfo = particle._modelBoundingInfo;
  68584. if (!this._bSphereOnly) {
  68585. // place, scale and rotate the particle bbox within the SPS local system, then update it
  68586. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  68587. var tempMin = tempVectors[1];
  68588. var tempMax = tempVectors[2];
  68589. tempMin.setAll(Number.MAX_VALUE);
  68590. tempMax.setAll(-Number.MAX_VALUE);
  68591. for (var b = 0; b < 8; b++) {
  68592. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  68593. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  68594. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  68595. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  68596. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  68597. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  68598. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68599. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68600. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68601. tempMin.minimizeInPlaceFromFloats(x, y, z);
  68602. tempMax.maximizeInPlaceFromFloats(x, y, z);
  68603. }
  68604. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  68605. }
  68606. // place and scale the particle bouding sphere in the SPS local system, then update it
  68607. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  68608. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  68609. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  68610. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  68611. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  68612. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  68613. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  68614. }
  68615. // increment indexes for the next particle
  68616. index = idx + 3;
  68617. colorIndex = colidx + 4;
  68618. uvIndex = uvidx + 2;
  68619. }
  68620. // if the VBO must be updated
  68621. if (update) {
  68622. if (this._computeParticleColor) {
  68623. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  68624. }
  68625. if (this._computeParticleTexture) {
  68626. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  68627. }
  68628. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  68629. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  68630. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  68631. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  68632. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  68633. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  68634. for (var i = 0; i < normals32.length; i++) {
  68635. fixedNormal32[i] = normals32[i];
  68636. }
  68637. }
  68638. if (!mesh.areNormalsFrozen) {
  68639. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  68640. }
  68641. }
  68642. if (this._depthSort && this._depthSortParticles) {
  68643. var depthSortedParticles = this.depthSortedParticles;
  68644. depthSortedParticles.sort(depthSortFunction);
  68645. var dspl = depthSortedParticles.length;
  68646. var sid = 0;
  68647. for (var sorted = 0; sorted < dspl; sorted++) {
  68648. var lind = depthSortedParticles[sorted].indicesLength;
  68649. var sind = depthSortedParticles[sorted].ind;
  68650. for (var i = 0; i < lind; i++) {
  68651. indices32[sid] = indices[sind + i];
  68652. sid++;
  68653. }
  68654. }
  68655. mesh.updateIndices(indices32);
  68656. }
  68657. }
  68658. if (this._computeBoundingBox) {
  68659. if (mesh._boundingInfo) {
  68660. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  68661. }
  68662. else {
  68663. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  68664. }
  68665. }
  68666. this.afterUpdateParticles(start, end, update);
  68667. return this;
  68668. };
  68669. /**
  68670. * Disposes the SPS.
  68671. */
  68672. SolidParticleSystem.prototype.dispose = function () {
  68673. this.mesh.dispose();
  68674. this.vars = null;
  68675. // drop references to internal big arrays for the GC
  68676. this._positions = null;
  68677. this._indices = null;
  68678. this._normals = null;
  68679. this._uvs = null;
  68680. this._colors = null;
  68681. this._indices32 = null;
  68682. this._positions32 = null;
  68683. this._normals32 = null;
  68684. this._fixedNormal32 = null;
  68685. this._uvs32 = null;
  68686. this._colors32 = null;
  68687. this.pickedParticles = null;
  68688. };
  68689. /**
  68690. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  68691. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68692. * @returns the SPS.
  68693. */
  68694. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  68695. if (!this._isVisibilityBoxLocked) {
  68696. this.mesh.refreshBoundingInfo();
  68697. }
  68698. return this;
  68699. };
  68700. /**
  68701. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  68702. * @param size the size (float) of the visibility box
  68703. * note : this doesn't lock the SPS mesh bounding box.
  68704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68705. */
  68706. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  68707. var vis = size / 2;
  68708. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  68709. };
  68710. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  68711. /**
  68712. * Gets whether the SPS as always visible or not
  68713. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68714. */
  68715. get: function () {
  68716. return this._alwaysVisible;
  68717. },
  68718. /**
  68719. * Sets the SPS as always visible or not
  68720. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68721. */
  68722. set: function (val) {
  68723. this._alwaysVisible = val;
  68724. this.mesh.alwaysSelectAsActiveMesh = val;
  68725. },
  68726. enumerable: true,
  68727. configurable: true
  68728. });
  68729. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  68730. /**
  68731. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68732. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68733. */
  68734. get: function () {
  68735. return this._isVisibilityBoxLocked;
  68736. },
  68737. /**
  68738. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68740. */
  68741. set: function (val) {
  68742. this._isVisibilityBoxLocked = val;
  68743. var boundingInfo = this.mesh.getBoundingInfo();
  68744. boundingInfo.isLocked = val;
  68745. },
  68746. enumerable: true,
  68747. configurable: true
  68748. });
  68749. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  68750. /**
  68751. * Gets if `setParticles()` computes the particle rotations or not.
  68752. * Default value : true. The SPS is faster when it's set to false.
  68753. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68754. */
  68755. get: function () {
  68756. return this._computeParticleRotation;
  68757. },
  68758. /**
  68759. * Tells to `setParticles()` to compute the particle rotations or not.
  68760. * Default value : true. The SPS is faster when it's set to false.
  68761. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68762. */
  68763. set: function (val) {
  68764. this._computeParticleRotation = val;
  68765. },
  68766. enumerable: true,
  68767. configurable: true
  68768. });
  68769. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  68770. /**
  68771. * Gets if `setParticles()` computes the particle colors or not.
  68772. * Default value : true. The SPS is faster when it's set to false.
  68773. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68774. */
  68775. get: function () {
  68776. return this._computeParticleColor;
  68777. },
  68778. /**
  68779. * Tells to `setParticles()` to compute the particle colors or not.
  68780. * Default value : true. The SPS is faster when it's set to false.
  68781. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68782. */
  68783. set: function (val) {
  68784. this._computeParticleColor = val;
  68785. },
  68786. enumerable: true,
  68787. configurable: true
  68788. });
  68789. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  68790. /**
  68791. * Gets if `setParticles()` computes the particle textures or not.
  68792. * Default value : true. The SPS is faster when it's set to false.
  68793. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  68794. */
  68795. get: function () {
  68796. return this._computeParticleTexture;
  68797. },
  68798. set: function (val) {
  68799. this._computeParticleTexture = val;
  68800. },
  68801. enumerable: true,
  68802. configurable: true
  68803. });
  68804. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  68805. /**
  68806. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  68807. * Default value : false. The SPS is faster when it's set to false.
  68808. * Note : the particle custom vertex positions aren't stored values.
  68809. */
  68810. get: function () {
  68811. return this._computeParticleVertex;
  68812. },
  68813. /**
  68814. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  68815. * Default value : false. The SPS is faster when it's set to false.
  68816. * Note : the particle custom vertex positions aren't stored values.
  68817. */
  68818. set: function (val) {
  68819. this._computeParticleVertex = val;
  68820. },
  68821. enumerable: true,
  68822. configurable: true
  68823. });
  68824. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  68825. /**
  68826. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  68827. */
  68828. get: function () {
  68829. return this._computeBoundingBox;
  68830. },
  68831. /**
  68832. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  68833. */
  68834. set: function (val) {
  68835. this._computeBoundingBox = val;
  68836. },
  68837. enumerable: true,
  68838. configurable: true
  68839. });
  68840. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  68841. /**
  68842. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  68843. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68844. * Default : `true`
  68845. */
  68846. get: function () {
  68847. return this._depthSortParticles;
  68848. },
  68849. /**
  68850. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  68851. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68852. * Default : `true`
  68853. */
  68854. set: function (val) {
  68855. this._depthSortParticles = val;
  68856. },
  68857. enumerable: true,
  68858. configurable: true
  68859. });
  68860. // =======================================================================
  68861. // Particle behavior logic
  68862. // these following methods may be overwritten by the user to fit his needs
  68863. /**
  68864. * This function does nothing. It may be overwritten to set all the particle first values.
  68865. * The SPS doesn't call this function, you may have to call it by your own.
  68866. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68867. */
  68868. SolidParticleSystem.prototype.initParticles = function () {
  68869. };
  68870. /**
  68871. * This function does nothing. It may be overwritten to recycle a particle.
  68872. * The SPS doesn't call this function, you may have to call it by your own.
  68873. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68874. * @param particle The particle to recycle
  68875. * @returns the recycled particle
  68876. */
  68877. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  68878. return particle;
  68879. };
  68880. /**
  68881. * Updates a particle : this function should be overwritten by the user.
  68882. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  68883. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68884. * @example : just set a particle position or velocity and recycle conditions
  68885. * @param particle The particle to update
  68886. * @returns the updated particle
  68887. */
  68888. SolidParticleSystem.prototype.updateParticle = function (particle) {
  68889. return particle;
  68890. };
  68891. /**
  68892. * Updates a vertex of a particle : it can be overwritten by the user.
  68893. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  68894. * @param particle the current particle
  68895. * @param vertex the current index of the current particle
  68896. * @param pt the index of the current vertex in the particle shape
  68897. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  68898. * @example : just set a vertex particle position
  68899. * @returns the updated vertex
  68900. */
  68901. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  68902. return vertex;
  68903. };
  68904. /**
  68905. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  68906. * This does nothing and may be overwritten by the user.
  68907. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68908. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68909. * @param update the boolean update value actually passed to setParticles()
  68910. */
  68911. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  68912. };
  68913. /**
  68914. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  68915. * This will be passed three parameters.
  68916. * This does nothing and may be overwritten by the user.
  68917. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68918. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68919. * @param update the boolean update value actually passed to setParticles()
  68920. */
  68921. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  68922. };
  68923. return SolidParticleSystem;
  68924. }());
  68925. BABYLON.SolidParticleSystem = SolidParticleSystem;
  68926. })(BABYLON || (BABYLON = {}));
  68927. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  68928. var BABYLON;
  68929. (function (BABYLON) {
  68930. /**
  68931. * Class containing static functions to help procedurally build meshes
  68932. */
  68933. var MeshBuilder = /** @class */ (function () {
  68934. function MeshBuilder() {
  68935. }
  68936. MeshBuilder.updateSideOrientation = function (orientation) {
  68937. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  68938. return BABYLON.Mesh.DOUBLESIDE;
  68939. }
  68940. if (orientation === undefined || orientation === null) {
  68941. return BABYLON.Mesh.FRONTSIDE;
  68942. }
  68943. return orientation;
  68944. };
  68945. /**
  68946. * Creates a box mesh
  68947. * * The parameter `size` sets the size (float) of each box side (default 1)
  68948. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  68949. * * 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)
  68950. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68952. * * 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
  68953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68954. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  68955. * @param name defines the name of the mesh
  68956. * @param options defines the options used to create the mesh
  68957. * @param scene defines the hosting scene
  68958. * @returns the box mesh
  68959. */
  68960. MeshBuilder.CreateBox = function (name, options, scene) {
  68961. if (scene === void 0) { scene = null; }
  68962. var box = new BABYLON.Mesh(name, scene);
  68963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68964. box._originalBuilderSideOrientation = options.sideOrientation;
  68965. var vertexData = BABYLON.VertexData.CreateBox(options);
  68966. vertexData.applyToMesh(box, options.updatable);
  68967. return box;
  68968. };
  68969. /**
  68970. * Creates a sphere mesh
  68971. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  68972. * * 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`)
  68973. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  68974. * * 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
  68975. * * 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)
  68976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68977. * * 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
  68978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68979. * @param name defines the name of the mesh
  68980. * @param options defines the options used to create the mesh
  68981. * @param scene defines the hosting scene
  68982. * @returns the sphere mesh
  68983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  68984. */
  68985. MeshBuilder.CreateSphere = function (name, options, scene) {
  68986. var sphere = new BABYLON.Mesh(name, scene);
  68987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68988. sphere._originalBuilderSideOrientation = options.sideOrientation;
  68989. var vertexData = BABYLON.VertexData.CreateSphere(options);
  68990. vertexData.applyToMesh(sphere, options.updatable);
  68991. return sphere;
  68992. };
  68993. /**
  68994. * Creates a plane polygonal mesh. By default, this is a disc
  68995. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  68996. * * 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
  68997. * * 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
  68998. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68999. * * 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
  69000. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69001. * @param name defines the name of the mesh
  69002. * @param options defines the options used to create the mesh
  69003. * @param scene defines the hosting scene
  69004. * @returns the plane polygonal mesh
  69005. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69006. */
  69007. MeshBuilder.CreateDisc = function (name, options, scene) {
  69008. if (scene === void 0) { scene = null; }
  69009. var disc = new BABYLON.Mesh(name, scene);
  69010. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69011. disc._originalBuilderSideOrientation = options.sideOrientation;
  69012. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69013. vertexData.applyToMesh(disc, options.updatable);
  69014. return disc;
  69015. };
  69016. /**
  69017. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69018. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69019. * * 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`)
  69020. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69021. * * 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
  69022. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69023. * * 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
  69024. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69025. * @param name defines the name of the mesh
  69026. * @param options defines the options used to create the mesh
  69027. * @param scene defines the hosting scene
  69028. * @returns the icosahedron mesh
  69029. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69030. */
  69031. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69032. var sphere = new BABYLON.Mesh(name, scene);
  69033. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69034. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69035. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69036. vertexData.applyToMesh(sphere, options.updatable);
  69037. return sphere;
  69038. };
  69039. /**
  69040. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69041. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69042. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69043. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69044. * * 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
  69045. * * 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
  69046. * * 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
  69047. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69048. * * 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
  69049. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69050. * * 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
  69051. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69052. * * 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
  69053. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69055. * @param name defines the name of the mesh
  69056. * @param options defines the options used to create the mesh
  69057. * @param scene defines the hosting scene
  69058. * @returns the ribbon mesh
  69059. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69060. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69061. */
  69062. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69063. if (scene === void 0) { scene = null; }
  69064. var pathArray = options.pathArray;
  69065. var closeArray = options.closeArray;
  69066. var closePath = options.closePath;
  69067. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69068. var instance = options.instance;
  69069. var updatable = options.updatable;
  69070. if (instance) { // existing ribbon instance update
  69071. // positionFunction : ribbon case
  69072. // only pathArray and sideOrientation parameters are taken into account for positions update
  69073. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69074. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69075. var positionFunction = function (positions) {
  69076. var minlg = pathArray[0].length;
  69077. var mesh = instance;
  69078. var i = 0;
  69079. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69080. for (var si = 1; si <= ns; ++si) {
  69081. for (var p = 0; p < pathArray.length; ++p) {
  69082. var path = pathArray[p];
  69083. var l = path.length;
  69084. minlg = (minlg < l) ? minlg : l;
  69085. for (var j = 0; j < minlg; ++j) {
  69086. var pathPoint = path[j];
  69087. positions[i] = pathPoint.x;
  69088. positions[i + 1] = pathPoint.y;
  69089. positions[i + 2] = pathPoint.z;
  69090. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69091. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69092. i += 3;
  69093. }
  69094. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69095. var pathPoint = path[0];
  69096. positions[i] = pathPoint.x;
  69097. positions[i + 1] = pathPoint.y;
  69098. positions[i + 2] = pathPoint.z;
  69099. i += 3;
  69100. }
  69101. }
  69102. }
  69103. };
  69104. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69105. positionFunction(positions);
  69106. if (instance._boundingInfo) {
  69107. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69108. }
  69109. else {
  69110. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69111. }
  69112. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69113. if (options.colors) {
  69114. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69115. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69116. var color = options.colors[c];
  69117. colors[colorIndex] = color.r;
  69118. colors[colorIndex + 1] = color.g;
  69119. colors[colorIndex + 2] = color.b;
  69120. colors[colorIndex + 3] = color.a;
  69121. }
  69122. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69123. }
  69124. if (options.uvs) {
  69125. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69126. for (var i = 0; i < options.uvs.length; i++) {
  69127. uvs[i * 2] = options.uvs[i].x;
  69128. uvs[i * 2 + 1] = options.uvs[i].y;
  69129. }
  69130. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69131. }
  69132. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69133. var indices = instance.getIndices();
  69134. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69135. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69136. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69137. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69138. var indexFirst = 0;
  69139. var indexLast = 0;
  69140. for (var p = 0; p < pathArray.length; p++) {
  69141. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69142. if (p + 1 < pathArray.length) {
  69143. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69144. }
  69145. else {
  69146. indexLast = normals.length - 3;
  69147. }
  69148. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69149. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69150. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69151. normals[indexLast] = normals[indexFirst];
  69152. normals[indexLast + 1] = normals[indexFirst + 1];
  69153. normals[indexLast + 2] = normals[indexFirst + 2];
  69154. }
  69155. }
  69156. if (!(instance.areNormalsFrozen)) {
  69157. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69158. }
  69159. }
  69160. return instance;
  69161. }
  69162. else { // new ribbon creation
  69163. var ribbon = new BABYLON.Mesh(name, scene);
  69164. ribbon._originalBuilderSideOrientation = sideOrientation;
  69165. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69166. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69167. if (closePath) {
  69168. ribbon._creationDataStorage.idx = vertexData._idx;
  69169. }
  69170. ribbon._creationDataStorage.closePath = closePath;
  69171. ribbon._creationDataStorage.closeArray = closeArray;
  69172. vertexData.applyToMesh(ribbon, updatable);
  69173. return ribbon;
  69174. }
  69175. };
  69176. /**
  69177. * Creates a cylinder or a cone mesh
  69178. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69179. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69180. * * 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.
  69181. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69182. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69183. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69184. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69185. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69186. * * 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).
  69187. * * 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
  69188. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69189. * * 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
  69190. * * 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.
  69191. * * If `enclose` is false, a ring surface is one element.
  69192. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69193. * * 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
  69194. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69195. * * 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
  69196. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69197. * @param name defines the name of the mesh
  69198. * @param options defines the options used to create the mesh
  69199. * @param scene defines the hosting scene
  69200. * @returns the cylinder mesh
  69201. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69202. */
  69203. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69204. var cylinder = new BABYLON.Mesh(name, scene);
  69205. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69206. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69207. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69208. vertexData.applyToMesh(cylinder, options.updatable);
  69209. return cylinder;
  69210. };
  69211. /**
  69212. * Creates a torus mesh
  69213. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69214. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69215. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69216. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69217. * * 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
  69218. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69219. * @param name defines the name of the mesh
  69220. * @param options defines the options used to create the mesh
  69221. * @param scene defines the hosting scene
  69222. * @returns the torus mesh
  69223. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69224. */
  69225. MeshBuilder.CreateTorus = function (name, options, scene) {
  69226. var torus = new BABYLON.Mesh(name, scene);
  69227. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69228. torus._originalBuilderSideOrientation = options.sideOrientation;
  69229. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69230. vertexData.applyToMesh(torus, options.updatable);
  69231. return torus;
  69232. };
  69233. /**
  69234. * Creates a torus knot mesh
  69235. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69236. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69237. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69238. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69239. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69240. * * 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
  69241. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69242. * @param name defines the name of the mesh
  69243. * @param options defines the options used to create the mesh
  69244. * @param scene defines the hosting scene
  69245. * @returns the torus knot mesh
  69246. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69247. */
  69248. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69249. var torusKnot = new BABYLON.Mesh(name, scene);
  69250. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69251. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69252. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69253. vertexData.applyToMesh(torusKnot, options.updatable);
  69254. return torusKnot;
  69255. };
  69256. /**
  69257. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69258. * * 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
  69259. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69260. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69261. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69262. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69263. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69264. * * 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
  69265. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69267. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69268. * @param name defines the name of the new line system
  69269. * @param options defines the options used to create the line system
  69270. * @param scene defines the hosting scene
  69271. * @returns a new line system mesh
  69272. */
  69273. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69274. var instance = options.instance;
  69275. var lines = options.lines;
  69276. var colors = options.colors;
  69277. if (instance) { // lines update
  69278. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69279. var vertexColor;
  69280. var lineColors;
  69281. if (colors) {
  69282. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69283. }
  69284. var i = 0;
  69285. var c = 0;
  69286. for (var l = 0; l < lines.length; l++) {
  69287. var points = lines[l];
  69288. for (var p = 0; p < points.length; p++) {
  69289. positions[i] = points[p].x;
  69290. positions[i + 1] = points[p].y;
  69291. positions[i + 2] = points[p].z;
  69292. if (colors && vertexColor) {
  69293. lineColors = colors[l];
  69294. vertexColor[c] = lineColors[p].r;
  69295. vertexColor[c + 1] = lineColors[p].g;
  69296. vertexColor[c + 2] = lineColors[p].b;
  69297. vertexColor[c + 3] = lineColors[p].a;
  69298. c += 4;
  69299. }
  69300. i += 3;
  69301. }
  69302. }
  69303. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69304. if (colors && vertexColor) {
  69305. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69306. }
  69307. return instance;
  69308. }
  69309. // line system creation
  69310. var useVertexColor = (colors) ? true : false;
  69311. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69312. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69313. vertexData.applyToMesh(lineSystem, options.updatable);
  69314. return lineSystem;
  69315. };
  69316. /**
  69317. * Creates a line mesh
  69318. * 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
  69319. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69320. * * The parameter `points` is an array successive Vector3
  69321. * * 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
  69322. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69323. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69324. * * When updating an instance, remember that only point positions can change, not the number of points
  69325. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69326. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69327. * @param name defines the name of the new line system
  69328. * @param options defines the options used to create the line system
  69329. * @param scene defines the hosting scene
  69330. * @returns a new line mesh
  69331. */
  69332. MeshBuilder.CreateLines = function (name, options, scene) {
  69333. if (scene === void 0) { scene = null; }
  69334. var colors = (options.colors) ? [options.colors] : null;
  69335. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69336. return lines;
  69337. };
  69338. /**
  69339. * Creates a dashed line mesh
  69340. * * 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
  69341. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69342. * * The parameter `points` is an array successive Vector3
  69343. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69344. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69345. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69346. * * 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
  69347. * * When updating an instance, remember that only point positions can change, not the number of points
  69348. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69349. * @param name defines the name of the mesh
  69350. * @param options defines the options used to create the mesh
  69351. * @param scene defines the hosting scene
  69352. * @returns the dashed line mesh
  69353. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69354. */
  69355. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69356. if (scene === void 0) { scene = null; }
  69357. var points = options.points;
  69358. var instance = options.instance;
  69359. var gapSize = options.gapSize || 1;
  69360. var dashSize = options.dashSize || 3;
  69361. if (instance) { // dashed lines update
  69362. var positionFunction = function (positions) {
  69363. var curvect = BABYLON.Vector3.Zero();
  69364. var nbSeg = positions.length / 6;
  69365. var lg = 0;
  69366. var nb = 0;
  69367. var shft = 0;
  69368. var dashshft = 0;
  69369. var curshft = 0;
  69370. var p = 0;
  69371. var i = 0;
  69372. var j = 0;
  69373. for (i = 0; i < points.length - 1; i++) {
  69374. points[i + 1].subtractToRef(points[i], curvect);
  69375. lg += curvect.length();
  69376. }
  69377. shft = lg / nbSeg;
  69378. var dashSize = instance._creationDataStorage.dashSize;
  69379. var gapSize = instance._creationDataStorage.gapSize;
  69380. dashshft = dashSize * shft / (dashSize + gapSize);
  69381. for (i = 0; i < points.length - 1; i++) {
  69382. points[i + 1].subtractToRef(points[i], curvect);
  69383. nb = Math.floor(curvect.length() / shft);
  69384. curvect.normalize();
  69385. j = 0;
  69386. while (j < nb && p < positions.length) {
  69387. curshft = shft * j;
  69388. positions[p] = points[i].x + curshft * curvect.x;
  69389. positions[p + 1] = points[i].y + curshft * curvect.y;
  69390. positions[p + 2] = points[i].z + curshft * curvect.z;
  69391. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69392. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69393. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69394. p += 6;
  69395. j++;
  69396. }
  69397. }
  69398. while (p < positions.length) {
  69399. positions[p] = points[i].x;
  69400. positions[p + 1] = points[i].y;
  69401. positions[p + 2] = points[i].z;
  69402. p += 3;
  69403. }
  69404. };
  69405. instance.updateMeshPositions(positionFunction, false);
  69406. return instance;
  69407. }
  69408. // dashed lines creation
  69409. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69410. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69411. vertexData.applyToMesh(dashedLines, options.updatable);
  69412. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69413. dashedLines._creationDataStorage.dashSize = dashSize;
  69414. dashedLines._creationDataStorage.gapSize = gapSize;
  69415. return dashedLines;
  69416. };
  69417. /**
  69418. * 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.
  69419. * * 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.
  69420. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69421. * * 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.
  69422. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69423. * * 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
  69424. * * 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
  69425. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69426. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69427. * * 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
  69428. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69429. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69430. * @param name defines the name of the mesh
  69431. * @param options defines the options used to create the mesh
  69432. * @param scene defines the hosting scene
  69433. * @returns the extruded shape mesh
  69434. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69435. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69436. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69437. */
  69438. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69439. if (scene === void 0) { scene = null; }
  69440. var path = options.path;
  69441. var shape = options.shape;
  69442. var scale = options.scale || 1;
  69443. var rotation = options.rotation || 0;
  69444. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69445. var updatable = options.updatable;
  69446. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69447. var instance = options.instance || null;
  69448. var invertUV = options.invertUV || false;
  69449. 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);
  69450. };
  69451. /**
  69452. * Creates an custom extruded shape mesh.
  69453. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69454. * * 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.
  69455. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69456. * * 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
  69457. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69458. * * 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
  69459. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69460. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69461. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69462. * * 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
  69463. * * 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
  69464. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69465. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69466. * * 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
  69467. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69468. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69469. * @param name defines the name of the mesh
  69470. * @param options defines the options used to create the mesh
  69471. * @param scene defines the hosting scene
  69472. * @returns the custom extruded shape mesh
  69473. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69474. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69475. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69476. */
  69477. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69478. var path = options.path;
  69479. var shape = options.shape;
  69480. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69481. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69482. var ribbonCloseArray = options.ribbonCloseArray || false;
  69483. var ribbonClosePath = options.ribbonClosePath || false;
  69484. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69485. var updatable = options.updatable;
  69486. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69487. var instance = options.instance;
  69488. var invertUV = options.invertUV || false;
  69489. 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);
  69490. };
  69491. /**
  69492. * Creates lathe mesh.
  69493. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69494. * * 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
  69495. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69496. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69497. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69498. * * 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
  69499. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  69500. * * 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
  69501. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69502. * * 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
  69503. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69504. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69505. * @param name defines the name of the mesh
  69506. * @param options defines the options used to create the mesh
  69507. * @param scene defines the hosting scene
  69508. * @returns the lathe mesh
  69509. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  69510. */
  69511. MeshBuilder.CreateLathe = function (name, options, scene) {
  69512. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  69513. var closed = (options.closed === undefined) ? true : options.closed;
  69514. var shape = options.shape;
  69515. var radius = options.radius || 1;
  69516. var tessellation = options.tessellation || 64;
  69517. var clip = options.clip || 0;
  69518. var updatable = options.updatable;
  69519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69520. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69521. var pi2 = Math.PI * 2;
  69522. var paths = new Array();
  69523. var invertUV = options.invertUV || false;
  69524. var i = 0;
  69525. var p = 0;
  69526. var step = pi2 / tessellation * arc;
  69527. var rotated;
  69528. var path = new Array();
  69529. for (i = 0; i <= tessellation - clip; i++) {
  69530. var path = [];
  69531. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  69532. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  69533. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  69534. }
  69535. for (p = 0; p < shape.length; p++) {
  69536. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  69537. path.push(rotated);
  69538. }
  69539. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  69540. 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));
  69541. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  69542. }
  69543. paths.push(path);
  69544. }
  69545. // lathe ribbon
  69546. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69547. return lathe;
  69548. };
  69549. /**
  69550. * Creates a plane mesh
  69551. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  69552. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  69553. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  69554. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69555. * * 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
  69556. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69557. * @param name defines the name of the mesh
  69558. * @param options defines the options used to create the mesh
  69559. * @param scene defines the hosting scene
  69560. * @returns the plane mesh
  69561. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69562. */
  69563. MeshBuilder.CreatePlane = function (name, options, scene) {
  69564. var plane = new BABYLON.Mesh(name, scene);
  69565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69566. plane._originalBuilderSideOrientation = options.sideOrientation;
  69567. var vertexData = BABYLON.VertexData.CreatePlane(options);
  69568. vertexData.applyToMesh(plane, options.updatable);
  69569. if (options.sourcePlane) {
  69570. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  69571. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  69572. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  69573. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  69574. plane.rotate(vectorProduct, product);
  69575. }
  69576. }
  69577. return plane;
  69578. };
  69579. /**
  69580. * Creates a ground mesh
  69581. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  69582. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  69583. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69584. * @param name defines the name of the mesh
  69585. * @param options defines the options used to create the mesh
  69586. * @param scene defines the hosting scene
  69587. * @returns the ground mesh
  69588. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69589. */
  69590. MeshBuilder.CreateGround = function (name, options, scene) {
  69591. var ground = new BABYLON.GroundMesh(name, scene);
  69592. ground._setReady(false);
  69593. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  69594. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  69595. ground._width = options.width || 1;
  69596. ground._height = options.height || 1;
  69597. ground._maxX = ground._width / 2;
  69598. ground._maxZ = ground._height / 2;
  69599. ground._minX = -ground._maxX;
  69600. ground._minZ = -ground._maxZ;
  69601. var vertexData = BABYLON.VertexData.CreateGround(options);
  69602. vertexData.applyToMesh(ground, options.updatable);
  69603. ground._setReady(true);
  69604. return ground;
  69605. };
  69606. /**
  69607. * Creates a tiled ground mesh
  69608. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  69609. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  69610. * * 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
  69611. * * 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
  69612. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69613. * @param name defines the name of the mesh
  69614. * @param options defines the options used to create the mesh
  69615. * @param scene defines the hosting scene
  69616. * @returns the tiled ground mesh
  69617. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  69618. */
  69619. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  69620. var tiledGround = new BABYLON.Mesh(name, scene);
  69621. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  69622. vertexData.applyToMesh(tiledGround, options.updatable);
  69623. return tiledGround;
  69624. };
  69625. /**
  69626. * Creates a ground mesh from a height map
  69627. * * The parameter `url` sets the URL of the height map image resource.
  69628. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  69629. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  69630. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  69631. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  69632. * * 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.
  69633. * * 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).
  69634. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  69635. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69636. * @param name defines the name of the mesh
  69637. * @param url defines the url to the height map
  69638. * @param options defines the options used to create the mesh
  69639. * @param scene defines the hosting scene
  69640. * @returns the ground mesh
  69641. * @see http://doc.babylonjs.com/babylon101/height_map
  69642. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  69643. */
  69644. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  69645. var width = options.width || 10.0;
  69646. var height = options.height || 10.0;
  69647. var subdivisions = options.subdivisions || 1 | 0;
  69648. var minHeight = options.minHeight || 0.0;
  69649. var maxHeight = options.maxHeight || 1.0;
  69650. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  69651. var alphaFilter = options.alphaFilter || 0.0;
  69652. var updatable = options.updatable;
  69653. var onReady = options.onReady;
  69654. var ground = new BABYLON.GroundMesh(name, scene);
  69655. ground._subdivisionsX = subdivisions;
  69656. ground._subdivisionsY = subdivisions;
  69657. ground._width = width;
  69658. ground._height = height;
  69659. ground._maxX = ground._width / 2.0;
  69660. ground._maxZ = ground._height / 2.0;
  69661. ground._minX = -ground._maxX;
  69662. ground._minZ = -ground._maxZ;
  69663. ground._setReady(false);
  69664. var onload = function (img) {
  69665. // Getting height map data
  69666. var canvas = document.createElement("canvas");
  69667. var context = canvas.getContext("2d");
  69668. if (!context) {
  69669. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  69670. }
  69671. if (scene.isDisposed) {
  69672. return;
  69673. }
  69674. var bufferWidth = img.width;
  69675. var bufferHeight = img.height;
  69676. canvas.width = bufferWidth;
  69677. canvas.height = bufferHeight;
  69678. context.drawImage(img, 0, 0);
  69679. // Create VertexData from map data
  69680. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  69681. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  69682. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  69683. width: width, height: height,
  69684. subdivisions: subdivisions,
  69685. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  69686. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  69687. alphaFilter: alphaFilter
  69688. });
  69689. vertexData.applyToMesh(ground, updatable);
  69690. //execute ready callback, if set
  69691. if (onReady) {
  69692. onReady(ground);
  69693. }
  69694. ground._setReady(true);
  69695. };
  69696. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  69697. return ground;
  69698. };
  69699. /**
  69700. * Creates a polygon mesh
  69701. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  69702. * * 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
  69703. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69704. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69705. * * 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)
  69706. * * Remember you can only change the shape positions, not their number when updating a polygon
  69707. * @param name defines the name of the mesh
  69708. * @param options defines the options used to create the mesh
  69709. * @param scene defines the hosting scene
  69710. * @returns the polygon mesh
  69711. */
  69712. MeshBuilder.CreatePolygon = function (name, options, scene) {
  69713. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69714. var shape = options.shape;
  69715. var holes = options.holes || [];
  69716. var depth = options.depth || 0;
  69717. var contours = [];
  69718. var hole = [];
  69719. for (var i = 0; i < shape.length; i++) {
  69720. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  69721. }
  69722. var epsilon = 0.00000001;
  69723. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  69724. contours.pop();
  69725. }
  69726. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  69727. for (var hNb = 0; hNb < holes.length; hNb++) {
  69728. hole = [];
  69729. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  69730. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  69731. }
  69732. polygonTriangulation.addHole(hole);
  69733. }
  69734. var polygon = polygonTriangulation.build(options.updatable, depth);
  69735. polygon._originalBuilderSideOrientation = options.sideOrientation;
  69736. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  69737. vertexData.applyToMesh(polygon, options.updatable);
  69738. return polygon;
  69739. };
  69740. /**
  69741. * Creates an extruded polygon mesh, with depth in the Y direction.
  69742. * * 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)
  69743. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69744. * @param name defines the name of the mesh
  69745. * @param options defines the options used to create the mesh
  69746. * @param scene defines the hosting scene
  69747. * @returns the polygon mesh
  69748. */
  69749. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  69750. return MeshBuilder.CreatePolygon(name, options, scene);
  69751. };
  69752. /**
  69753. * Creates a tube mesh.
  69754. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69755. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  69756. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  69757. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  69758. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  69759. * * 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)
  69760. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  69761. * * 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
  69762. * * 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
  69763. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69764. * * 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
  69765. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69767. * @param name defines the name of the mesh
  69768. * @param options defines the options used to create the mesh
  69769. * @param scene defines the hosting scene
  69770. * @returns the tube mesh
  69771. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69772. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  69773. */
  69774. MeshBuilder.CreateTube = function (name, options, scene) {
  69775. var path = options.path;
  69776. var instance = options.instance;
  69777. var radius = 1.0;
  69778. if (options.radius !== undefined) {
  69779. radius = options.radius;
  69780. }
  69781. else if (instance) {
  69782. radius = instance._creationDataStorage.radius;
  69783. }
  69784. var tessellation = options.tessellation || 64 | 0;
  69785. var radiusFunction = options.radiusFunction || null;
  69786. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69787. var invertUV = options.invertUV || false;
  69788. var updatable = options.updatable;
  69789. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69790. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  69791. // tube geometry
  69792. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  69793. var tangents = path3D.getTangents();
  69794. var normals = path3D.getNormals();
  69795. var distances = path3D.getDistances();
  69796. var pi2 = Math.PI * 2;
  69797. var step = pi2 / tessellation * arc;
  69798. var returnRadius = function () { return radius; };
  69799. var radiusFunctionFinal = radiusFunction || returnRadius;
  69800. var circlePath;
  69801. var rad;
  69802. var normal;
  69803. var rotated;
  69804. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69805. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69806. for (var i = 0; i < path.length; i++) {
  69807. rad = radiusFunctionFinal(i, distances[i]); // current radius
  69808. circlePath = Array(); // current circle array
  69809. normal = normals[i]; // current normal
  69810. for (var t = 0; t < tessellation; t++) {
  69811. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  69812. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  69813. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  69814. rotated.scaleInPlace(rad).addInPlace(path[i]);
  69815. circlePath[t] = rotated;
  69816. }
  69817. circlePaths[index] = circlePath;
  69818. index++;
  69819. }
  69820. // cap
  69821. var capPath = function (nbPoints, pathIndex) {
  69822. var pointCap = Array();
  69823. for (var i = 0; i < nbPoints; i++) {
  69824. pointCap.push(path[pathIndex]);
  69825. }
  69826. return pointCap;
  69827. };
  69828. switch (cap) {
  69829. case BABYLON.Mesh.NO_CAP:
  69830. break;
  69831. case BABYLON.Mesh.CAP_START:
  69832. circlePaths[0] = capPath(tessellation, 0);
  69833. circlePaths[1] = circlePaths[2].slice(0);
  69834. break;
  69835. case BABYLON.Mesh.CAP_END:
  69836. circlePaths[index] = circlePaths[index - 1].slice(0);
  69837. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69838. break;
  69839. case BABYLON.Mesh.CAP_ALL:
  69840. circlePaths[0] = capPath(tessellation, 0);
  69841. circlePaths[1] = circlePaths[2].slice(0);
  69842. circlePaths[index] = circlePaths[index - 1].slice(0);
  69843. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69844. break;
  69845. default:
  69846. break;
  69847. }
  69848. return circlePaths;
  69849. };
  69850. var path3D;
  69851. var pathArray;
  69852. if (instance) { // tube update
  69853. var storage = instance._creationDataStorage;
  69854. var arc = options.arc || storage.arc;
  69855. path3D = storage.path3D.update(path);
  69856. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  69857. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  69858. // Update mode, no need to recreate the storage.
  69859. storage.path3D = path3D;
  69860. storage.pathArray = pathArray;
  69861. storage.arc = arc;
  69862. storage.radius = radius;
  69863. return instance;
  69864. }
  69865. // tube creation
  69866. path3D = new BABYLON.Path3D(path);
  69867. var newPathArray = new Array();
  69868. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69869. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  69870. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69871. tube._creationDataStorage.pathArray = pathArray;
  69872. tube._creationDataStorage.path3D = path3D;
  69873. tube._creationDataStorage.tessellation = tessellation;
  69874. tube._creationDataStorage.cap = cap;
  69875. tube._creationDataStorage.arc = options.arc;
  69876. tube._creationDataStorage.radius = radius;
  69877. return tube;
  69878. };
  69879. /**
  69880. * Creates a polyhedron mesh
  69881. * * 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
  69882. * * The parameter `size` (positive float, default 1) sets the polygon size
  69883. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  69884. * * 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`
  69885. * * 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
  69886. * * 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)`)
  69887. * * 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
  69888. * * 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
  69889. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69890. * * 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
  69891. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69892. * @param name defines the name of the mesh
  69893. * @param options defines the options used to create the mesh
  69894. * @param scene defines the hosting scene
  69895. * @returns the polyhedron mesh
  69896. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  69897. */
  69898. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  69899. var polyhedron = new BABYLON.Mesh(name, scene);
  69900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69901. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  69902. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  69903. vertexData.applyToMesh(polyhedron, options.updatable);
  69904. return polyhedron;
  69905. };
  69906. /**
  69907. * Creates a decal mesh.
  69908. * 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
  69909. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  69910. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  69911. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  69912. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  69913. * @param name defines the name of the mesh
  69914. * @param sourceMesh defines the mesh where the decal must be applied
  69915. * @param options defines the options used to create the mesh
  69916. * @param scene defines the hosting scene
  69917. * @returns the decal mesh
  69918. * @see http://doc.babylonjs.com/how_to/decals
  69919. */
  69920. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  69921. var indices = sourceMesh.getIndices();
  69922. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69923. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69924. var position = options.position || BABYLON.Vector3.Zero();
  69925. var normal = options.normal || BABYLON.Vector3.Up();
  69926. var size = options.size || BABYLON.Vector3.One();
  69927. var angle = options.angle || 0;
  69928. // Getting correct rotation
  69929. if (!normal) {
  69930. var target = new BABYLON.Vector3(0, 0, 1);
  69931. var camera = sourceMesh.getScene().activeCamera;
  69932. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  69933. normal = camera.globalPosition.subtract(cameraWorldTarget);
  69934. }
  69935. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  69936. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  69937. var pitch = Math.atan2(normal.y, len);
  69938. // Matrix
  69939. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  69940. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  69941. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  69942. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  69943. var vertexData = new BABYLON.VertexData();
  69944. vertexData.indices = [];
  69945. vertexData.positions = [];
  69946. vertexData.normals = [];
  69947. vertexData.uvs = [];
  69948. var currentVertexDataIndex = 0;
  69949. var extractDecalVector3 = function (indexId) {
  69950. var result = new BABYLON.PositionNormalVertex();
  69951. if (!indices || !positions || !normals) {
  69952. return result;
  69953. }
  69954. var vertexId = indices[indexId];
  69955. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  69956. // Send vector to decal local world
  69957. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  69958. // Get normal
  69959. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  69960. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  69961. return result;
  69962. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  69963. var clip = function (vertices, axis) {
  69964. if (vertices.length === 0) {
  69965. return vertices;
  69966. }
  69967. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  69968. var clipVertices = function (v0, v1) {
  69969. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  69970. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  69971. };
  69972. var result = new Array();
  69973. for (var index = 0; index < vertices.length; index += 3) {
  69974. var v1Out;
  69975. var v2Out;
  69976. var v3Out;
  69977. var total = 0;
  69978. var nV1 = null;
  69979. var nV2 = null;
  69980. var nV3 = null;
  69981. var nV4 = null;
  69982. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  69983. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  69984. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  69985. v1Out = d1 > 0;
  69986. v2Out = d2 > 0;
  69987. v3Out = d3 > 0;
  69988. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  69989. switch (total) {
  69990. case 0:
  69991. result.push(vertices[index]);
  69992. result.push(vertices[index + 1]);
  69993. result.push(vertices[index + 2]);
  69994. break;
  69995. case 1:
  69996. if (v1Out) {
  69997. nV1 = vertices[index + 1];
  69998. nV2 = vertices[index + 2];
  69999. nV3 = clipVertices(vertices[index], nV1);
  70000. nV4 = clipVertices(vertices[index], nV2);
  70001. }
  70002. if (v2Out) {
  70003. nV1 = vertices[index];
  70004. nV2 = vertices[index + 2];
  70005. nV3 = clipVertices(vertices[index + 1], nV1);
  70006. nV4 = clipVertices(vertices[index + 1], nV2);
  70007. result.push(nV3);
  70008. result.push(nV2.clone());
  70009. result.push(nV1.clone());
  70010. result.push(nV2.clone());
  70011. result.push(nV3.clone());
  70012. result.push(nV4);
  70013. break;
  70014. }
  70015. if (v3Out) {
  70016. nV1 = vertices[index];
  70017. nV2 = vertices[index + 1];
  70018. nV3 = clipVertices(vertices[index + 2], nV1);
  70019. nV4 = clipVertices(vertices[index + 2], nV2);
  70020. }
  70021. if (nV1 && nV2 && nV3 && nV4) {
  70022. result.push(nV1.clone());
  70023. result.push(nV2.clone());
  70024. result.push(nV3);
  70025. result.push(nV4);
  70026. result.push(nV3.clone());
  70027. result.push(nV2.clone());
  70028. }
  70029. break;
  70030. case 2:
  70031. if (!v1Out) {
  70032. nV1 = vertices[index].clone();
  70033. nV2 = clipVertices(nV1, vertices[index + 1]);
  70034. nV3 = clipVertices(nV1, vertices[index + 2]);
  70035. result.push(nV1);
  70036. result.push(nV2);
  70037. result.push(nV3);
  70038. }
  70039. if (!v2Out) {
  70040. nV1 = vertices[index + 1].clone();
  70041. nV2 = clipVertices(nV1, vertices[index + 2]);
  70042. nV3 = clipVertices(nV1, vertices[index]);
  70043. result.push(nV1);
  70044. result.push(nV2);
  70045. result.push(nV3);
  70046. }
  70047. if (!v3Out) {
  70048. nV1 = vertices[index + 2].clone();
  70049. nV2 = clipVertices(nV1, vertices[index]);
  70050. nV3 = clipVertices(nV1, vertices[index + 1]);
  70051. result.push(nV1);
  70052. result.push(nV2);
  70053. result.push(nV3);
  70054. }
  70055. break;
  70056. case 3:
  70057. break;
  70058. }
  70059. }
  70060. return result;
  70061. };
  70062. for (var index = 0; index < indices.length; index += 3) {
  70063. var faceVertices = new Array();
  70064. faceVertices.push(extractDecalVector3(index));
  70065. faceVertices.push(extractDecalVector3(index + 1));
  70066. faceVertices.push(extractDecalVector3(index + 2));
  70067. // Clip
  70068. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70069. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70070. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70071. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70072. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70073. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70074. if (faceVertices.length === 0) {
  70075. continue;
  70076. }
  70077. // Add UVs and get back to world
  70078. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70079. var vertex = faceVertices[vIndex];
  70080. //TODO check for Int32Array | Uint32Array | Uint16Array
  70081. vertexData.indices.push(currentVertexDataIndex);
  70082. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70083. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70084. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70085. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70086. currentVertexDataIndex++;
  70087. }
  70088. }
  70089. // Return mesh
  70090. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70091. vertexData.applyToMesh(decal);
  70092. decal.position = position.clone();
  70093. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70094. return decal;
  70095. };
  70096. // Privates
  70097. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70098. // extrusion geometry
  70099. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70100. var tangents = path3D.getTangents();
  70101. var normals = path3D.getNormals();
  70102. var binormals = path3D.getBinormals();
  70103. var distances = path3D.getDistances();
  70104. var angle = 0;
  70105. var returnScale = function () { return scale !== null ? scale : 1; };
  70106. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70107. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70108. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70109. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70110. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70111. for (var i = 0; i < curve.length; i++) {
  70112. var shapePath = new Array();
  70113. var angleStep = rotate(i, distances[i]);
  70114. var scaleRatio = scl(i, distances[i]);
  70115. for (var p = 0; p < shape.length; p++) {
  70116. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70117. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70118. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70119. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70120. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70121. shapePath[p] = rotated;
  70122. }
  70123. shapePaths[index] = shapePath;
  70124. angle += angleStep;
  70125. index++;
  70126. }
  70127. // cap
  70128. var capPath = function (shapePath) {
  70129. var pointCap = Array();
  70130. var barycenter = BABYLON.Vector3.Zero();
  70131. var i;
  70132. for (i = 0; i < shapePath.length; i++) {
  70133. barycenter.addInPlace(shapePath[i]);
  70134. }
  70135. barycenter.scaleInPlace(1.0 / shapePath.length);
  70136. for (i = 0; i < shapePath.length; i++) {
  70137. pointCap.push(barycenter);
  70138. }
  70139. return pointCap;
  70140. };
  70141. switch (cap) {
  70142. case BABYLON.Mesh.NO_CAP:
  70143. break;
  70144. case BABYLON.Mesh.CAP_START:
  70145. shapePaths[0] = capPath(shapePaths[2]);
  70146. shapePaths[1] = shapePaths[2];
  70147. break;
  70148. case BABYLON.Mesh.CAP_END:
  70149. shapePaths[index] = shapePaths[index - 1];
  70150. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70151. break;
  70152. case BABYLON.Mesh.CAP_ALL:
  70153. shapePaths[0] = capPath(shapePaths[2]);
  70154. shapePaths[1] = shapePaths[2];
  70155. shapePaths[index] = shapePaths[index - 1];
  70156. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70157. break;
  70158. default:
  70159. break;
  70160. }
  70161. return shapePaths;
  70162. };
  70163. var path3D;
  70164. var pathArray;
  70165. if (instance) { // instance update
  70166. var storage = instance._creationDataStorage;
  70167. path3D = storage.path3D.update(curve);
  70168. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70169. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70170. return instance;
  70171. }
  70172. // extruded shape creation
  70173. path3D = new BABYLON.Path3D(curve);
  70174. var newShapePaths = new Array();
  70175. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70176. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70177. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70178. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70179. extrudedGeneric._creationDataStorage.path3D = path3D;
  70180. extrudedGeneric._creationDataStorage.cap = cap;
  70181. return extrudedGeneric;
  70182. };
  70183. return MeshBuilder;
  70184. }());
  70185. BABYLON.MeshBuilder = MeshBuilder;
  70186. })(BABYLON || (BABYLON = {}));
  70187. //# sourceMappingURL=babylon.meshBuilder.js.map
  70188. var BABYLON;
  70189. (function (BABYLON) {
  70190. /**
  70191. * Draco compression (https://google.github.io/draco/)
  70192. *
  70193. * This class wraps the Draco module.
  70194. *
  70195. * **Encoder**
  70196. *
  70197. * The encoder is not currently implemented.
  70198. *
  70199. * **Decoder**
  70200. *
  70201. * 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.
  70202. *
  70203. * To update the configuration, use the following code:
  70204. * ```javascript
  70205. * BABYLON.DracoCompression.Configuration = {
  70206. * decoder: {
  70207. * wasmUrl: "<url to the WebAssembly library>",
  70208. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70209. * fallbackUrl: "<url to the fallback JavaScript library>",
  70210. * }
  70211. * };
  70212. * ```
  70213. *
  70214. * 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.
  70215. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70216. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70217. *
  70218. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70219. * ```javascript
  70220. * var dracoCompression = new BABYLON.DracoCompression();
  70221. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70222. * [BABYLON.VertexBuffer.PositionKind]: 0
  70223. * });
  70224. * ```
  70225. *
  70226. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70227. */
  70228. var DracoCompression = /** @class */ (function () {
  70229. /**
  70230. * Constructor
  70231. */
  70232. function DracoCompression() {
  70233. }
  70234. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70235. /**
  70236. * Returns true if the decoder is available.
  70237. */
  70238. get: function () {
  70239. if (typeof DracoDecoderModule !== "undefined") {
  70240. return true;
  70241. }
  70242. var decoder = DracoCompression.Configuration.decoder;
  70243. if (decoder) {
  70244. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70245. return true;
  70246. }
  70247. if (decoder.fallbackUrl) {
  70248. return true;
  70249. }
  70250. }
  70251. return false;
  70252. },
  70253. enumerable: true,
  70254. configurable: true
  70255. });
  70256. /**
  70257. * Stop all async operations and release resources.
  70258. */
  70259. DracoCompression.prototype.dispose = function () {
  70260. };
  70261. /**
  70262. * Decode Draco compressed mesh data to vertex data.
  70263. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70264. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70265. * @returns A promise that resolves with the decoded vertex data
  70266. */
  70267. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70268. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70269. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70270. var module = wrappedModule.module;
  70271. var vertexData = new BABYLON.VertexData();
  70272. var buffer = new module.DecoderBuffer();
  70273. buffer.Init(dataView, dataView.byteLength);
  70274. var decoder = new module.Decoder();
  70275. var geometry;
  70276. var status;
  70277. try {
  70278. var type = decoder.GetEncodedGeometryType(buffer);
  70279. switch (type) {
  70280. case module.TRIANGULAR_MESH:
  70281. geometry = new module.Mesh();
  70282. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70283. break;
  70284. case module.POINT_CLOUD:
  70285. geometry = new module.PointCloud();
  70286. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70287. break;
  70288. default:
  70289. throw new Error("Invalid geometry type " + type);
  70290. }
  70291. if (!status.ok() || !geometry.ptr) {
  70292. throw new Error(status.error_msg());
  70293. }
  70294. var numPoints = geometry.num_points();
  70295. if (type === module.TRIANGULAR_MESH) {
  70296. var numFaces = geometry.num_faces();
  70297. var faceIndices = new module.DracoInt32Array();
  70298. try {
  70299. var indices = new Uint32Array(numFaces * 3);
  70300. for (var i = 0; i < numFaces; i++) {
  70301. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70302. var offset = i * 3;
  70303. indices[offset + 0] = faceIndices.GetValue(0);
  70304. indices[offset + 1] = faceIndices.GetValue(1);
  70305. indices[offset + 2] = faceIndices.GetValue(2);
  70306. }
  70307. vertexData.indices = indices;
  70308. }
  70309. finally {
  70310. module.destroy(faceIndices);
  70311. }
  70312. }
  70313. for (var kind in attributes) {
  70314. var uniqueId = attributes[kind];
  70315. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70316. var dracoData = new module.DracoFloat32Array();
  70317. try {
  70318. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70319. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70320. for (var i = 0; i < babylonData.length; i++) {
  70321. babylonData[i] = dracoData.GetValue(i);
  70322. }
  70323. vertexData.set(babylonData, kind);
  70324. }
  70325. finally {
  70326. module.destroy(dracoData);
  70327. }
  70328. }
  70329. }
  70330. finally {
  70331. if (geometry) {
  70332. module.destroy(geometry);
  70333. }
  70334. module.destroy(decoder);
  70335. module.destroy(buffer);
  70336. }
  70337. return vertexData;
  70338. });
  70339. };
  70340. DracoCompression._GetDecoderModule = function () {
  70341. if (!DracoCompression._DecoderModulePromise) {
  70342. var promise = null;
  70343. var config_1 = {};
  70344. if (typeof DracoDecoderModule !== "undefined") {
  70345. promise = Promise.resolve();
  70346. }
  70347. else {
  70348. var decoder = DracoCompression.Configuration.decoder;
  70349. if (decoder) {
  70350. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70351. promise = Promise.all([
  70352. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70353. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70354. config_1.wasmBinary = data;
  70355. })
  70356. ]);
  70357. }
  70358. else if (decoder.fallbackUrl) {
  70359. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70360. }
  70361. }
  70362. }
  70363. if (!promise) {
  70364. throw new Error("Draco decoder module is not available");
  70365. }
  70366. DracoCompression._DecoderModulePromise = promise.then(function () {
  70367. return new Promise(function (resolve) {
  70368. config_1.onModuleLoaded = function (decoderModule) {
  70369. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70370. resolve({ module: decoderModule });
  70371. };
  70372. DracoDecoderModule(config_1);
  70373. });
  70374. });
  70375. }
  70376. return DracoCompression._DecoderModulePromise;
  70377. };
  70378. DracoCompression._LoadScriptAsync = function (url) {
  70379. return new Promise(function (resolve, reject) {
  70380. BABYLON.Tools.LoadScript(url, function () {
  70381. resolve();
  70382. }, function (message) {
  70383. reject(new Error(message));
  70384. });
  70385. });
  70386. };
  70387. DracoCompression._LoadFileAsync = function (url) {
  70388. return new Promise(function (resolve, reject) {
  70389. BABYLON.Tools.LoadFile(url, function (data) {
  70390. resolve(data);
  70391. }, undefined, undefined, true, function (request, exception) {
  70392. reject(exception);
  70393. });
  70394. });
  70395. };
  70396. /**
  70397. * The configuration. Defaults to the following urls:
  70398. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70399. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70400. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70401. */
  70402. DracoCompression.Configuration = {
  70403. decoder: {
  70404. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70405. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70406. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70407. }
  70408. };
  70409. return DracoCompression;
  70410. }());
  70411. BABYLON.DracoCompression = DracoCompression;
  70412. })(BABYLON || (BABYLON = {}));
  70413. //# sourceMappingURL=babylon.dracoCompression.js.map
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. // Sets the default audio engine to Babylon.js
  70417. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70418. /**
  70419. * This represents the default audio engine used in babylon.
  70420. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70421. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70422. */
  70423. var AudioEngine = /** @class */ (function () {
  70424. /**
  70425. * Instantiates a new audio engine.
  70426. *
  70427. * There should be only one per page as some browsers restrict the number
  70428. * of audio contexts you can create.
  70429. * @param hostElement defines the host element where to display the mute icon if necessary
  70430. */
  70431. function AudioEngine(hostElement) {
  70432. if (hostElement === void 0) { hostElement = null; }
  70433. var _this = this;
  70434. this._audioContext = null;
  70435. this._audioContextInitialized = false;
  70436. this._muteButton = null;
  70437. /**
  70438. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70439. */
  70440. this.canUseWebAudio = false;
  70441. /**
  70442. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70443. * @ignoreNaming
  70444. */
  70445. this.WarnedWebAudioUnsupported = false;
  70446. /**
  70447. * Gets whether or not mp3 are supported by your browser.
  70448. */
  70449. this.isMP3supported = false;
  70450. /**
  70451. * Gets whether or not ogg are supported by your browser.
  70452. */
  70453. this.isOGGsupported = false;
  70454. /**
  70455. * Gets whether audio has been unlocked on the device.
  70456. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70457. * a user interaction has happened.
  70458. */
  70459. this.unlocked = true;
  70460. /**
  70461. * Defines if the audio engine relies on a custom unlocked button.
  70462. * In this case, the embedded button will not be displayed.
  70463. */
  70464. this.useCustomUnlockedButton = false;
  70465. /**
  70466. * Event raised when audio has been unlocked on the browser.
  70467. */
  70468. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70469. /**
  70470. * Event raised when audio has been locked on the browser.
  70471. */
  70472. this.onAudioLockedObservable = new BABYLON.Observable();
  70473. this._tryToRun = false;
  70474. this._onResize = function () {
  70475. _this._moveButtonToTopLeft();
  70476. };
  70477. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70478. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70479. this.canUseWebAudio = true;
  70480. }
  70481. var audioElem = document.createElement('audio');
  70482. this._hostElement = hostElement;
  70483. try {
  70484. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70485. this.isMP3supported = true;
  70486. }
  70487. }
  70488. catch (e) {
  70489. // protect error during capability check.
  70490. }
  70491. try {
  70492. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70493. this.isOGGsupported = true;
  70494. }
  70495. }
  70496. catch (e) {
  70497. // protect error during capability check.
  70498. }
  70499. }
  70500. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  70501. /**
  70502. * Gets the current AudioContext if available.
  70503. */
  70504. get: function () {
  70505. if (!this._audioContextInitialized) {
  70506. this._initializeAudioContext();
  70507. }
  70508. else {
  70509. if (!this.unlocked && !this._muteButton) {
  70510. this._displayMuteButton();
  70511. }
  70512. }
  70513. return this._audioContext;
  70514. },
  70515. enumerable: true,
  70516. configurable: true
  70517. });
  70518. /**
  70519. * Flags the audio engine in Locked state.
  70520. * This happens due to new browser policies preventing audio to autoplay.
  70521. */
  70522. AudioEngine.prototype.lock = function () {
  70523. this._triggerSuspendedState();
  70524. };
  70525. /**
  70526. * Unlocks the audio engine once a user action has been done on the dom.
  70527. * This is helpful to resume play once browser policies have been satisfied.
  70528. */
  70529. AudioEngine.prototype.unlock = function () {
  70530. this._triggerRunningState();
  70531. };
  70532. AudioEngine.prototype._resumeAudioContext = function () {
  70533. var result;
  70534. if (this._audioContext.resume) {
  70535. result = this._audioContext.resume();
  70536. }
  70537. return result || Promise.resolve();
  70538. };
  70539. AudioEngine.prototype._initializeAudioContext = function () {
  70540. try {
  70541. if (this.canUseWebAudio) {
  70542. this._audioContext = new AudioContext();
  70543. // create a global volume gain node
  70544. this.masterGain = this._audioContext.createGain();
  70545. this.masterGain.gain.value = 1;
  70546. this.masterGain.connect(this._audioContext.destination);
  70547. this._audioContextInitialized = true;
  70548. if (this._audioContext.state === "running") {
  70549. // Do not wait for the promise to unlock.
  70550. this._triggerRunningState();
  70551. }
  70552. }
  70553. }
  70554. catch (e) {
  70555. this.canUseWebAudio = false;
  70556. BABYLON.Tools.Error("Web Audio: " + e.message);
  70557. }
  70558. };
  70559. AudioEngine.prototype._triggerRunningState = function () {
  70560. var _this = this;
  70561. if (this._tryToRun) {
  70562. return;
  70563. }
  70564. this._tryToRun = true;
  70565. this._resumeAudioContext()
  70566. .then(function () {
  70567. _this._tryToRun = false;
  70568. if (_this._muteButton) {
  70569. _this._hideMuteButton();
  70570. }
  70571. }).catch(function () {
  70572. _this._tryToRun = false;
  70573. _this.unlocked = false;
  70574. });
  70575. // Notify users that the audio stack is unlocked/unmuted
  70576. this.unlocked = true;
  70577. this.onAudioUnlockedObservable.notifyObservers(this);
  70578. };
  70579. AudioEngine.prototype._triggerSuspendedState = function () {
  70580. this.unlocked = false;
  70581. this.onAudioLockedObservable.notifyObservers(this);
  70582. this._displayMuteButton();
  70583. };
  70584. AudioEngine.prototype._displayMuteButton = function () {
  70585. var _this = this;
  70586. if (this.useCustomUnlockedButton) {
  70587. return;
  70588. }
  70589. this._muteButton = document.createElement("BUTTON");
  70590. this._muteButton.className = "babylonUnmuteIcon";
  70591. this._muteButton.id = "babylonUnmuteIconBtn";
  70592. this._muteButton.title = "Unmute";
  70593. 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) }";
  70594. var style = document.createElement('style');
  70595. style.appendChild(document.createTextNode(css));
  70596. document.getElementsByTagName('head')[0].appendChild(style);
  70597. document.body.appendChild(this._muteButton);
  70598. this._moveButtonToTopLeft();
  70599. this._muteButton.addEventListener('touchend', function () {
  70600. _this._triggerRunningState();
  70601. }, true);
  70602. this._muteButton.addEventListener('click', function () {
  70603. _this._triggerRunningState();
  70604. }, true);
  70605. window.addEventListener("resize", this._onResize);
  70606. };
  70607. AudioEngine.prototype._moveButtonToTopLeft = function () {
  70608. if (this._hostElement && this._muteButton) {
  70609. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  70610. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  70611. }
  70612. };
  70613. AudioEngine.prototype._hideMuteButton = function () {
  70614. if (this._muteButton) {
  70615. document.body.removeChild(this._muteButton);
  70616. this._muteButton = null;
  70617. }
  70618. };
  70619. /**
  70620. * Destroy and release the resources associated with the audio ccontext.
  70621. */
  70622. AudioEngine.prototype.dispose = function () {
  70623. if (this.canUseWebAudio && this._audioContextInitialized) {
  70624. if (this._connectedAnalyser && this._audioContext) {
  70625. this._connectedAnalyser.stopDebugCanvas();
  70626. this._connectedAnalyser.dispose();
  70627. this.masterGain.disconnect();
  70628. this.masterGain.connect(this._audioContext.destination);
  70629. this._connectedAnalyser = null;
  70630. }
  70631. this.masterGain.gain.value = 1;
  70632. }
  70633. this.WarnedWebAudioUnsupported = false;
  70634. this._hideMuteButton();
  70635. window.removeEventListener("resize", this._onResize);
  70636. this.onAudioUnlockedObservable.clear();
  70637. this.onAudioLockedObservable.clear();
  70638. };
  70639. /**
  70640. * Gets the global volume sets on the master gain.
  70641. * @returns the global volume if set or -1 otherwise
  70642. */
  70643. AudioEngine.prototype.getGlobalVolume = function () {
  70644. if (this.canUseWebAudio && this._audioContextInitialized) {
  70645. return this.masterGain.gain.value;
  70646. }
  70647. else {
  70648. return -1;
  70649. }
  70650. };
  70651. /**
  70652. * Sets the global volume of your experience (sets on the master gain).
  70653. * @param newVolume Defines the new global volume of the application
  70654. */
  70655. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  70656. if (this.canUseWebAudio && this._audioContextInitialized) {
  70657. this.masterGain.gain.value = newVolume;
  70658. }
  70659. };
  70660. /**
  70661. * Connect the audio engine to an audio analyser allowing some amazing
  70662. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70663. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70664. * @param analyser The analyser to connect to the engine
  70665. */
  70666. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  70667. if (this._connectedAnalyser) {
  70668. this._connectedAnalyser.stopDebugCanvas();
  70669. }
  70670. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  70671. this._connectedAnalyser = analyser;
  70672. this.masterGain.disconnect();
  70673. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  70674. }
  70675. };
  70676. return AudioEngine;
  70677. }());
  70678. BABYLON.AudioEngine = AudioEngine;
  70679. })(BABYLON || (BABYLON = {}));
  70680. //# sourceMappingURL=babylon.audioEngine.js.map
  70681. var BABYLON;
  70682. (function (BABYLON) {
  70683. /**
  70684. * Defines a sound that can be played in the application.
  70685. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  70686. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70687. */
  70688. var Sound = /** @class */ (function () {
  70689. /**
  70690. * Create a sound and attach it to a scene
  70691. * @param name Name of your sound
  70692. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  70693. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  70694. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  70695. */
  70696. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  70697. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  70698. var _this = this;
  70699. /**
  70700. * Does the sound autoplay once loaded.
  70701. */
  70702. this.autoplay = false;
  70703. /**
  70704. * Does the sound loop after it finishes playing once.
  70705. */
  70706. this.loop = false;
  70707. /**
  70708. * Does the sound use a custom attenuation curve to simulate the falloff
  70709. * happening when the source gets further away from the camera.
  70710. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70711. */
  70712. this.useCustomAttenuation = false;
  70713. /**
  70714. * Is this sound currently played.
  70715. */
  70716. this.isPlaying = false;
  70717. /**
  70718. * Is this sound currently paused.
  70719. */
  70720. this.isPaused = false;
  70721. /**
  70722. * Does this sound enables spatial sound.
  70723. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70724. */
  70725. this.spatialSound = false;
  70726. /**
  70727. * Define the reference distance the sound should be heard perfectly.
  70728. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70729. */
  70730. this.refDistance = 1;
  70731. /**
  70732. * Define the roll off factor of spatial sounds.
  70733. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70734. */
  70735. this.rolloffFactor = 1;
  70736. /**
  70737. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  70738. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70739. */
  70740. this.maxDistance = 100;
  70741. /**
  70742. * Define the distance attenuation model the sound will follow.
  70743. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70744. */
  70745. this.distanceModel = "linear";
  70746. /**
  70747. * Observable event when the current playing sound finishes.
  70748. */
  70749. this.onEndedObservable = new BABYLON.Observable();
  70750. this._panningModel = "equalpower";
  70751. this._playbackRate = 1;
  70752. this._streaming = false;
  70753. this._startTime = 0;
  70754. this._startOffset = 0;
  70755. this._position = BABYLON.Vector3.Zero();
  70756. /** @hidden */
  70757. this._positionInEmitterSpace = false;
  70758. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  70759. this._volume = 1;
  70760. this._isReadyToPlay = false;
  70761. this._isDirectional = false;
  70762. // Used if you'd like to create a directional sound.
  70763. // If not set, the sound will be omnidirectional
  70764. this._coneInnerAngle = 360;
  70765. this._coneOuterAngle = 360;
  70766. this._coneOuterGain = 0;
  70767. this._isOutputConnected = false;
  70768. this._urlType = "Unknown";
  70769. this.name = name;
  70770. this._scene = scene;
  70771. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70772. if (!compo) {
  70773. compo = new BABYLON.AudioSceneComponent(scene);
  70774. scene._addComponent(compo);
  70775. }
  70776. this._readyToPlayCallback = readyToPlayCallback;
  70777. // Default custom attenuation function is a linear attenuation
  70778. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  70779. if (currentDistance < maxDistance) {
  70780. return currentVolume * (1 - currentDistance / maxDistance);
  70781. }
  70782. else {
  70783. return 0;
  70784. }
  70785. };
  70786. if (options) {
  70787. this.autoplay = options.autoplay || false;
  70788. this.loop = options.loop || false;
  70789. // if volume === 0, we need another way to check this option
  70790. if (options.volume !== undefined) {
  70791. this._volume = options.volume;
  70792. }
  70793. this.spatialSound = options.spatialSound || false;
  70794. this.maxDistance = options.maxDistance || 100;
  70795. this.useCustomAttenuation = options.useCustomAttenuation || false;
  70796. this.rolloffFactor = options.rolloffFactor || 1;
  70797. this.refDistance = options.refDistance || 1;
  70798. this.distanceModel = options.distanceModel || "linear";
  70799. this._playbackRate = options.playbackRate || 1;
  70800. this._streaming = options.streaming || false;
  70801. }
  70802. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70803. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  70804. this._soundGain.gain.value = this._volume;
  70805. this._inputAudioNode = this._soundGain;
  70806. this._outputAudioNode = this._soundGain;
  70807. if (this.spatialSound) {
  70808. this._createSpatialParameters();
  70809. }
  70810. this._scene.mainSoundTrack.AddSound(this);
  70811. var validParameter = true;
  70812. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  70813. if (urlOrArrayBuffer) {
  70814. try {
  70815. if (typeof (urlOrArrayBuffer) === "string") {
  70816. this._urlType = "String";
  70817. }
  70818. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  70819. this._urlType = "ArrayBuffer";
  70820. }
  70821. else if (urlOrArrayBuffer instanceof MediaStream) {
  70822. this._urlType = "MediaStream";
  70823. }
  70824. else if (Array.isArray(urlOrArrayBuffer)) {
  70825. this._urlType = "Array";
  70826. }
  70827. var urls = [];
  70828. var codecSupportedFound = false;
  70829. switch (this._urlType) {
  70830. case "MediaStream":
  70831. this._streaming = true;
  70832. this._isReadyToPlay = true;
  70833. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  70834. if (this.autoplay) {
  70835. this.play();
  70836. }
  70837. if (this._readyToPlayCallback) {
  70838. this._readyToPlayCallback();
  70839. }
  70840. break;
  70841. case "ArrayBuffer":
  70842. if (urlOrArrayBuffer.byteLength > 0) {
  70843. codecSupportedFound = true;
  70844. this._soundLoaded(urlOrArrayBuffer);
  70845. }
  70846. break;
  70847. case "String":
  70848. urls.push(urlOrArrayBuffer);
  70849. case "Array":
  70850. if (urls.length === 0) {
  70851. urls = urlOrArrayBuffer;
  70852. }
  70853. // If we found a supported format, we load it immediately and stop the loop
  70854. for (var i = 0; i < urls.length; i++) {
  70855. var url = urls[i];
  70856. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  70857. codecSupportedFound = true;
  70858. }
  70859. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  70860. codecSupportedFound = true;
  70861. }
  70862. if (url.indexOf(".wav", url.length - 4) !== -1) {
  70863. codecSupportedFound = true;
  70864. }
  70865. if (url.indexOf("blob:") !== -1) {
  70866. codecSupportedFound = true;
  70867. }
  70868. if (codecSupportedFound) {
  70869. // Loading sound using XHR2
  70870. if (!this._streaming) {
  70871. this._scene._loadFile(url, function (data) {
  70872. _this._soundLoaded(data);
  70873. }, undefined, true, true, function (exception) {
  70874. if (exception) {
  70875. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  70876. }
  70877. BABYLON.Tools.Error("Sound creation aborted.");
  70878. _this._scene.mainSoundTrack.RemoveSound(_this);
  70879. });
  70880. }
  70881. // Streaming sound using HTML5 Audio tag
  70882. else {
  70883. this._htmlAudioElement = new Audio(url);
  70884. this._htmlAudioElement.controls = false;
  70885. this._htmlAudioElement.loop = this.loop;
  70886. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  70887. this._htmlAudioElement.preload = "auto";
  70888. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  70889. _this._isReadyToPlay = true;
  70890. if (_this.autoplay) {
  70891. _this.play();
  70892. }
  70893. if (_this._readyToPlayCallback) {
  70894. _this._readyToPlayCallback();
  70895. }
  70896. });
  70897. document.body.appendChild(this._htmlAudioElement);
  70898. this._htmlAudioElement.load();
  70899. }
  70900. break;
  70901. }
  70902. }
  70903. break;
  70904. default:
  70905. validParameter = false;
  70906. break;
  70907. }
  70908. if (!validParameter) {
  70909. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  70910. }
  70911. else {
  70912. if (!codecSupportedFound) {
  70913. this._isReadyToPlay = true;
  70914. // Simulating a ready to play event to avoid breaking code path
  70915. if (this._readyToPlayCallback) {
  70916. window.setTimeout(function () {
  70917. if (_this._readyToPlayCallback) {
  70918. _this._readyToPlayCallback();
  70919. }
  70920. }, 1000);
  70921. }
  70922. }
  70923. }
  70924. }
  70925. catch (ex) {
  70926. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  70927. this._scene.mainSoundTrack.RemoveSound(this);
  70928. }
  70929. }
  70930. }
  70931. else {
  70932. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  70933. this._scene.mainSoundTrack.AddSound(this);
  70934. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  70935. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  70936. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  70937. }
  70938. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  70939. if (this._readyToPlayCallback) {
  70940. window.setTimeout(function () {
  70941. if (_this._readyToPlayCallback) {
  70942. _this._readyToPlayCallback();
  70943. }
  70944. }, 1000);
  70945. }
  70946. }
  70947. }
  70948. /**
  70949. * Release the sound and its associated resources
  70950. */
  70951. Sound.prototype.dispose = function () {
  70952. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70953. if (this.isPlaying) {
  70954. this.stop();
  70955. }
  70956. this._isReadyToPlay = false;
  70957. if (this.soundTrackId === -1) {
  70958. this._scene.mainSoundTrack.RemoveSound(this);
  70959. }
  70960. else if (this._scene.soundTracks) {
  70961. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  70962. }
  70963. if (this._soundGain) {
  70964. this._soundGain.disconnect();
  70965. this._soundGain = null;
  70966. }
  70967. if (this._soundPanner) {
  70968. this._soundPanner.disconnect();
  70969. this._soundPanner = null;
  70970. }
  70971. if (this._soundSource) {
  70972. this._soundSource.disconnect();
  70973. this._soundSource = null;
  70974. }
  70975. this._audioBuffer = null;
  70976. if (this._htmlAudioElement) {
  70977. this._htmlAudioElement.pause();
  70978. this._htmlAudioElement.src = "";
  70979. document.body.removeChild(this._htmlAudioElement);
  70980. }
  70981. if (this._streamingSource) {
  70982. this._streamingSource.disconnect();
  70983. }
  70984. if (this._connectedMesh && this._registerFunc) {
  70985. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70986. this._connectedMesh = null;
  70987. }
  70988. }
  70989. };
  70990. /**
  70991. * Gets if the sounds is ready to be played or not.
  70992. * @returns true if ready, otherwise false
  70993. */
  70994. Sound.prototype.isReady = function () {
  70995. return this._isReadyToPlay;
  70996. };
  70997. Sound.prototype._soundLoaded = function (audioData) {
  70998. var _this = this;
  70999. if (!BABYLON.Engine.audioEngine.audioContext) {
  71000. return;
  71001. }
  71002. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71003. _this._audioBuffer = buffer;
  71004. _this._isReadyToPlay = true;
  71005. if (_this.autoplay) {
  71006. _this.play();
  71007. }
  71008. if (_this._readyToPlayCallback) {
  71009. _this._readyToPlayCallback();
  71010. }
  71011. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71012. };
  71013. /**
  71014. * Sets the data of the sound from an audiobuffer
  71015. * @param audioBuffer The audioBuffer containing the data
  71016. */
  71017. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71018. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71019. this._audioBuffer = audioBuffer;
  71020. this._isReadyToPlay = true;
  71021. }
  71022. };
  71023. /**
  71024. * Updates the current sounds options such as maxdistance, loop...
  71025. * @param options A JSON object containing values named as the object properties
  71026. */
  71027. Sound.prototype.updateOptions = function (options) {
  71028. if (options) {
  71029. this.loop = options.loop || this.loop;
  71030. this.maxDistance = options.maxDistance || this.maxDistance;
  71031. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71032. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71033. this.refDistance = options.refDistance || this.refDistance;
  71034. this.distanceModel = options.distanceModel || this.distanceModel;
  71035. this._playbackRate = options.playbackRate || this._playbackRate;
  71036. this._updateSpatialParameters();
  71037. if (this.isPlaying) {
  71038. if (this._streaming && this._htmlAudioElement) {
  71039. this._htmlAudioElement.playbackRate = this._playbackRate;
  71040. }
  71041. else {
  71042. if (this._soundSource) {
  71043. this._soundSource.playbackRate.value = this._playbackRate;
  71044. }
  71045. }
  71046. }
  71047. }
  71048. };
  71049. Sound.prototype._createSpatialParameters = function () {
  71050. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71051. if (this._scene.headphone) {
  71052. this._panningModel = "HRTF";
  71053. }
  71054. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71055. this._updateSpatialParameters();
  71056. this._soundPanner.connect(this._outputAudioNode);
  71057. this._inputAudioNode = this._soundPanner;
  71058. }
  71059. };
  71060. Sound.prototype._updateSpatialParameters = function () {
  71061. if (this.spatialSound && this._soundPanner) {
  71062. if (this.useCustomAttenuation) {
  71063. // Tricks to disable in a way embedded Web Audio attenuation
  71064. this._soundPanner.distanceModel = "linear";
  71065. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71066. this._soundPanner.refDistance = 1;
  71067. this._soundPanner.rolloffFactor = 1;
  71068. this._soundPanner.panningModel = this._panningModel;
  71069. }
  71070. else {
  71071. this._soundPanner.distanceModel = this.distanceModel;
  71072. this._soundPanner.maxDistance = this.maxDistance;
  71073. this._soundPanner.refDistance = this.refDistance;
  71074. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71075. this._soundPanner.panningModel = this._panningModel;
  71076. }
  71077. }
  71078. };
  71079. /**
  71080. * Switch the panning model to HRTF:
  71081. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71082. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71083. */
  71084. Sound.prototype.switchPanningModelToHRTF = function () {
  71085. this._panningModel = "HRTF";
  71086. this._switchPanningModel();
  71087. };
  71088. /**
  71089. * Switch the panning model to Equal Power:
  71090. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71091. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71092. */
  71093. Sound.prototype.switchPanningModelToEqualPower = function () {
  71094. this._panningModel = "equalpower";
  71095. this._switchPanningModel();
  71096. };
  71097. Sound.prototype._switchPanningModel = function () {
  71098. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71099. this._soundPanner.panningModel = this._panningModel;
  71100. }
  71101. };
  71102. /**
  71103. * Connect this sound to a sound track audio node like gain...
  71104. * @param soundTrackAudioNode the sound track audio node to connect to
  71105. */
  71106. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71107. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71108. if (this._isOutputConnected) {
  71109. this._outputAudioNode.disconnect();
  71110. }
  71111. this._outputAudioNode.connect(soundTrackAudioNode);
  71112. this._isOutputConnected = true;
  71113. }
  71114. };
  71115. /**
  71116. * Transform this sound into a directional source
  71117. * @param coneInnerAngle Size of the inner cone in degree
  71118. * @param coneOuterAngle Size of the outer cone in degree
  71119. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71120. */
  71121. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71122. if (coneOuterAngle < coneInnerAngle) {
  71123. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71124. return;
  71125. }
  71126. this._coneInnerAngle = coneInnerAngle;
  71127. this._coneOuterAngle = coneOuterAngle;
  71128. this._coneOuterGain = coneOuterGain;
  71129. this._isDirectional = true;
  71130. if (this.isPlaying && this.loop) {
  71131. this.stop();
  71132. this.play();
  71133. }
  71134. };
  71135. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71136. /**
  71137. * Gets or sets the inner angle for the directional cone.
  71138. */
  71139. get: function () {
  71140. return this._coneInnerAngle;
  71141. },
  71142. /**
  71143. * Gets or sets the inner angle for the directional cone.
  71144. */
  71145. set: function (value) {
  71146. if (value != this._coneInnerAngle) {
  71147. if (this._coneOuterAngle < value) {
  71148. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71149. return;
  71150. }
  71151. this._coneInnerAngle = value;
  71152. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71153. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71154. }
  71155. }
  71156. },
  71157. enumerable: true,
  71158. configurable: true
  71159. });
  71160. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71161. /**
  71162. * Gets or sets the outer angle for the directional cone.
  71163. */
  71164. get: function () {
  71165. return this._coneOuterAngle;
  71166. },
  71167. /**
  71168. * Gets or sets the outer angle for the directional cone.
  71169. */
  71170. set: function (value) {
  71171. if (value != this._coneOuterAngle) {
  71172. if (value < this._coneInnerAngle) {
  71173. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71174. return;
  71175. }
  71176. this._coneOuterAngle = value;
  71177. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71178. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71179. }
  71180. }
  71181. },
  71182. enumerable: true,
  71183. configurable: true
  71184. });
  71185. /**
  71186. * Sets the position of the emitter if spatial sound is enabled
  71187. * @param newPosition Defines the new posisiton
  71188. */
  71189. Sound.prototype.setPosition = function (newPosition) {
  71190. this._position = newPosition;
  71191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71192. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71193. }
  71194. };
  71195. /**
  71196. * Sets the local direction of the emitter if spatial sound is enabled
  71197. * @param newLocalDirection Defines the new local direction
  71198. */
  71199. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71200. this._localDirection = newLocalDirection;
  71201. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  71202. this._updateDirection();
  71203. }
  71204. };
  71205. Sound.prototype._updateDirection = function () {
  71206. if (!this._connectedMesh || !this._soundPanner) {
  71207. return;
  71208. }
  71209. var mat = this._connectedMesh.getWorldMatrix();
  71210. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71211. direction.normalize();
  71212. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71213. };
  71214. /** @hidden */
  71215. Sound.prototype.updateDistanceFromListener = function () {
  71216. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71217. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  71218. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71219. }
  71220. };
  71221. /**
  71222. * Sets a new custom attenuation function for the sound.
  71223. * @param callback Defines the function used for the attenuation
  71224. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71225. */
  71226. Sound.prototype.setAttenuationFunction = function (callback) {
  71227. this._customAttenuationFunction = callback;
  71228. };
  71229. /**
  71230. * Play the sound
  71231. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71232. * @param offset (optional) Start the sound setting it at a specific time
  71233. */
  71234. Sound.prototype.play = function (time, offset) {
  71235. var _this = this;
  71236. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71237. try {
  71238. if (this._startOffset < 0) {
  71239. time = -this._startOffset;
  71240. this._startOffset = 0;
  71241. }
  71242. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71243. if (!this._soundSource || !this._streamingSource) {
  71244. if (this.spatialSound && this._soundPanner) {
  71245. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71246. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71247. }
  71248. if (this._isDirectional) {
  71249. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71250. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71251. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71252. if (this._connectedMesh) {
  71253. this._updateDirection();
  71254. }
  71255. else {
  71256. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71257. }
  71258. }
  71259. }
  71260. }
  71261. if (this._streaming) {
  71262. if (!this._streamingSource) {
  71263. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71264. this._htmlAudioElement.onended = function () { _this._onended(); };
  71265. this._htmlAudioElement.playbackRate = this._playbackRate;
  71266. }
  71267. this._streamingSource.disconnect();
  71268. this._streamingSource.connect(this._inputAudioNode);
  71269. if (this._htmlAudioElement) {
  71270. // required to manage properly the new suspended default state of Chrome
  71271. // When the option 'streaming: true' is used, we need first to wait for
  71272. // the audio engine to be unlocked by a user gesture before trying to play
  71273. // an HTML Audio elememt
  71274. var tryToPlay = function () {
  71275. if (BABYLON.Engine.audioEngine.unlocked) {
  71276. var playPromise = _this._htmlAudioElement.play();
  71277. // In browsers that don’t yet support this functionality,
  71278. // playPromise won’t be defined.
  71279. if (playPromise !== undefined) {
  71280. playPromise.catch(function (error) {
  71281. // Automatic playback failed.
  71282. // Waiting for the audio engine to be unlocked by user click on unmute
  71283. BABYLON.Engine.audioEngine.lock();
  71284. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71285. });
  71286. }
  71287. }
  71288. else {
  71289. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71290. }
  71291. };
  71292. tryToPlay();
  71293. }
  71294. }
  71295. else {
  71296. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71297. this._soundSource.buffer = this._audioBuffer;
  71298. this._soundSource.connect(this._inputAudioNode);
  71299. this._soundSource.loop = this.loop;
  71300. this._soundSource.playbackRate.value = this._playbackRate;
  71301. this._soundSource.onended = function () { _this._onended(); };
  71302. if (this._soundSource.buffer) {
  71303. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71304. }
  71305. }
  71306. this._startTime = startTime;
  71307. this.isPlaying = true;
  71308. this.isPaused = false;
  71309. }
  71310. catch (ex) {
  71311. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71312. }
  71313. }
  71314. };
  71315. Sound.prototype._onended = function () {
  71316. this.isPlaying = false;
  71317. if (this.onended) {
  71318. this.onended();
  71319. }
  71320. this.onEndedObservable.notifyObservers(this);
  71321. };
  71322. /**
  71323. * Stop the sound
  71324. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71325. */
  71326. Sound.prototype.stop = function (time) {
  71327. if (this.isPlaying) {
  71328. if (this._streaming) {
  71329. if (this._htmlAudioElement) {
  71330. this._htmlAudioElement.pause();
  71331. // Test needed for Firefox or it will generate an Invalid State Error
  71332. if (this._htmlAudioElement.currentTime > 0) {
  71333. this._htmlAudioElement.currentTime = 0;
  71334. }
  71335. }
  71336. else {
  71337. this._streamingSource.disconnect();
  71338. }
  71339. }
  71340. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71341. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71342. this._soundSource.stop(stopTime);
  71343. this._soundSource.onended = function () { };
  71344. if (!this.isPaused) {
  71345. this._startOffset = 0;
  71346. }
  71347. }
  71348. this.isPlaying = false;
  71349. }
  71350. };
  71351. /**
  71352. * Put the sound in pause
  71353. */
  71354. Sound.prototype.pause = function () {
  71355. if (this.isPlaying) {
  71356. this.isPaused = true;
  71357. if (this._streaming) {
  71358. if (this._htmlAudioElement) {
  71359. this._htmlAudioElement.pause();
  71360. }
  71361. else {
  71362. this._streamingSource.disconnect();
  71363. }
  71364. }
  71365. else if (BABYLON.Engine.audioEngine.audioContext) {
  71366. this.stop(0);
  71367. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71368. }
  71369. }
  71370. };
  71371. /**
  71372. * Sets a dedicated volume for this sounds
  71373. * @param newVolume Define the new volume of the sound
  71374. * @param time Define in how long the sound should be at this value
  71375. */
  71376. Sound.prototype.setVolume = function (newVolume, time) {
  71377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71378. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71379. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71380. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71381. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71382. }
  71383. else {
  71384. this._soundGain.gain.value = newVolume;
  71385. }
  71386. }
  71387. this._volume = newVolume;
  71388. };
  71389. /**
  71390. * Set the sound play back rate
  71391. * @param newPlaybackRate Define the playback rate the sound should be played at
  71392. */
  71393. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71394. this._playbackRate = newPlaybackRate;
  71395. if (this.isPlaying) {
  71396. if (this._streaming && this._htmlAudioElement) {
  71397. this._htmlAudioElement.playbackRate = this._playbackRate;
  71398. }
  71399. else if (this._soundSource) {
  71400. this._soundSource.playbackRate.value = this._playbackRate;
  71401. }
  71402. }
  71403. };
  71404. /**
  71405. * Gets the volume of the sound.
  71406. * @returns the volume of the sound
  71407. */
  71408. Sound.prototype.getVolume = function () {
  71409. return this._volume;
  71410. };
  71411. /**
  71412. * Attach the sound to a dedicated mesh
  71413. * @param meshToConnectTo The mesh to connect the sound with
  71414. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71415. */
  71416. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  71417. var _this = this;
  71418. if (this._connectedMesh && this._registerFunc) {
  71419. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71420. this._registerFunc = null;
  71421. }
  71422. this._connectedMesh = meshToConnectTo;
  71423. if (!this.spatialSound) {
  71424. this.spatialSound = true;
  71425. this._createSpatialParameters();
  71426. if (this.isPlaying && this.loop) {
  71427. this.stop();
  71428. this.play();
  71429. }
  71430. }
  71431. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  71432. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  71433. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  71434. };
  71435. /**
  71436. * Detach the sound from the previously attached mesh
  71437. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71438. */
  71439. Sound.prototype.detachFromMesh = function () {
  71440. if (this._connectedMesh && this._registerFunc) {
  71441. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71442. this._registerFunc = null;
  71443. this._connectedMesh = null;
  71444. }
  71445. };
  71446. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71447. if (!node.getBoundingInfo) {
  71448. return;
  71449. }
  71450. var mesh = node;
  71451. if (this._positionInEmitterSpace) {
  71452. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71453. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71454. }
  71455. else {
  71456. var boundingInfo = mesh.getBoundingInfo();
  71457. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71458. }
  71459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71460. this._updateDirection();
  71461. }
  71462. };
  71463. /**
  71464. * Clone the current sound in the scene.
  71465. * @returns the new sound clone
  71466. */
  71467. Sound.prototype.clone = function () {
  71468. var _this = this;
  71469. if (!this._streaming) {
  71470. var setBufferAndRun = function () {
  71471. if (_this._isReadyToPlay) {
  71472. clonedSound._audioBuffer = _this.getAudioBuffer();
  71473. clonedSound._isReadyToPlay = true;
  71474. if (clonedSound.autoplay) {
  71475. clonedSound.play();
  71476. }
  71477. }
  71478. else {
  71479. window.setTimeout(setBufferAndRun, 300);
  71480. }
  71481. };
  71482. var currentOptions = {
  71483. autoplay: this.autoplay, loop: this.loop,
  71484. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71485. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71486. refDistance: this.refDistance, distanceModel: this.distanceModel
  71487. };
  71488. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71489. if (this.useCustomAttenuation) {
  71490. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71491. }
  71492. clonedSound.setPosition(this._position);
  71493. clonedSound.setPlaybackRate(this._playbackRate);
  71494. setBufferAndRun();
  71495. return clonedSound;
  71496. }
  71497. // Can't clone a streaming sound
  71498. else {
  71499. return null;
  71500. }
  71501. };
  71502. /**
  71503. * Gets the current underlying audio buffer containing the data
  71504. * @returns the audio buffer
  71505. */
  71506. Sound.prototype.getAudioBuffer = function () {
  71507. return this._audioBuffer;
  71508. };
  71509. /**
  71510. * Serializes the Sound in a JSON representation
  71511. * @returns the JSON representation of the sound
  71512. */
  71513. Sound.prototype.serialize = function () {
  71514. var serializationObject = {
  71515. name: this.name,
  71516. url: this.name,
  71517. autoplay: this.autoplay,
  71518. loop: this.loop,
  71519. volume: this._volume,
  71520. spatialSound: this.spatialSound,
  71521. maxDistance: this.maxDistance,
  71522. rolloffFactor: this.rolloffFactor,
  71523. refDistance: this.refDistance,
  71524. distanceModel: this.distanceModel,
  71525. playbackRate: this._playbackRate,
  71526. panningModel: this._panningModel,
  71527. soundTrackId: this.soundTrackId
  71528. };
  71529. if (this.spatialSound) {
  71530. if (this._connectedMesh) {
  71531. serializationObject.connectedMeshId = this._connectedMesh.id;
  71532. }
  71533. serializationObject.position = this._position.asArray();
  71534. serializationObject.refDistance = this.refDistance;
  71535. serializationObject.distanceModel = this.distanceModel;
  71536. serializationObject.isDirectional = this._isDirectional;
  71537. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  71538. serializationObject.coneInnerAngle = this._coneInnerAngle;
  71539. serializationObject.coneOuterAngle = this._coneOuterAngle;
  71540. serializationObject.coneOuterGain = this._coneOuterGain;
  71541. }
  71542. return serializationObject;
  71543. };
  71544. /**
  71545. * Parse a JSON representation of a sound to innstantiate in a given scene
  71546. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  71547. * @param scene Define the scene the new parsed sound should be created in
  71548. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  71549. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  71550. * @returns the newly parsed sound
  71551. */
  71552. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  71553. var soundName = parsedSound.name;
  71554. var soundUrl;
  71555. if (parsedSound.url) {
  71556. soundUrl = rootUrl + parsedSound.url;
  71557. }
  71558. else {
  71559. soundUrl = rootUrl + soundName;
  71560. }
  71561. var options = {
  71562. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  71563. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  71564. rolloffFactor: parsedSound.rolloffFactor,
  71565. refDistance: parsedSound.refDistance,
  71566. distanceModel: parsedSound.distanceModel,
  71567. playbackRate: parsedSound.playbackRate
  71568. };
  71569. var newSound;
  71570. if (!sourceSound) {
  71571. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  71572. scene._addPendingData(newSound);
  71573. }
  71574. else {
  71575. var setBufferAndRun = function () {
  71576. if (sourceSound._isReadyToPlay) {
  71577. newSound._audioBuffer = sourceSound.getAudioBuffer();
  71578. newSound._isReadyToPlay = true;
  71579. if (newSound.autoplay) {
  71580. newSound.play();
  71581. }
  71582. }
  71583. else {
  71584. window.setTimeout(setBufferAndRun, 300);
  71585. }
  71586. };
  71587. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  71588. setBufferAndRun();
  71589. }
  71590. if (parsedSound.position) {
  71591. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  71592. newSound.setPosition(soundPosition);
  71593. }
  71594. if (parsedSound.isDirectional) {
  71595. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  71596. if (parsedSound.localDirectionToMesh) {
  71597. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  71598. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  71599. }
  71600. }
  71601. if (parsedSound.connectedMeshId) {
  71602. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  71603. if (connectedMesh) {
  71604. newSound.attachToMesh(connectedMesh);
  71605. }
  71606. }
  71607. return newSound;
  71608. };
  71609. return Sound;
  71610. }());
  71611. BABYLON.Sound = Sound;
  71612. })(BABYLON || (BABYLON = {}));
  71613. //# sourceMappingURL=babylon.sound.js.map
  71614. var BABYLON;
  71615. (function (BABYLON) {
  71616. /**
  71617. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  71618. * It will be also used in a future release to apply effects on a specific track.
  71619. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71620. */
  71621. var SoundTrack = /** @class */ (function () {
  71622. /**
  71623. * Creates a new sound track.
  71624. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71625. * @param scene Define the scene the sound track belongs to
  71626. * @param options
  71627. */
  71628. function SoundTrack(scene, options) {
  71629. if (options === void 0) { options = {}; }
  71630. /**
  71631. * The unique identifier of the sound track in the scene.
  71632. */
  71633. this.id = -1;
  71634. this._isMainTrack = false;
  71635. this._isInitialized = false;
  71636. this._scene = scene;
  71637. this.soundCollection = new Array();
  71638. this._options = options;
  71639. if (!this._isMainTrack && this._scene.soundTracks) {
  71640. this._scene.soundTracks.push(this);
  71641. this.id = this._scene.soundTracks.length - 1;
  71642. }
  71643. }
  71644. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  71645. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71646. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  71647. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  71648. if (this._options) {
  71649. if (this._options.volume) {
  71650. this._outputAudioNode.gain.value = this._options.volume;
  71651. }
  71652. if (this._options.mainTrack) {
  71653. this._isMainTrack = this._options.mainTrack;
  71654. }
  71655. }
  71656. this._isInitialized = true;
  71657. }
  71658. };
  71659. /**
  71660. * Release the sound track and its associated resources
  71661. */
  71662. SoundTrack.prototype.dispose = function () {
  71663. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  71664. if (this._connectedAnalyser) {
  71665. this._connectedAnalyser.stopDebugCanvas();
  71666. }
  71667. while (this.soundCollection.length) {
  71668. this.soundCollection[0].dispose();
  71669. }
  71670. if (this._outputAudioNode) {
  71671. this._outputAudioNode.disconnect();
  71672. }
  71673. this._outputAudioNode = null;
  71674. }
  71675. };
  71676. /**
  71677. * Adds a sound to this sound track
  71678. * @param sound define the cound to add
  71679. * @ignoreNaming
  71680. */
  71681. SoundTrack.prototype.AddSound = function (sound) {
  71682. if (!this._isInitialized) {
  71683. this._initializeSoundTrackAudioGraph();
  71684. }
  71685. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71686. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  71687. }
  71688. if (sound.soundTrackId) {
  71689. if (sound.soundTrackId === -1) {
  71690. this._scene.mainSoundTrack.RemoveSound(sound);
  71691. }
  71692. else if (this._scene.soundTracks) {
  71693. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  71694. }
  71695. }
  71696. this.soundCollection.push(sound);
  71697. sound.soundTrackId = this.id;
  71698. };
  71699. /**
  71700. * Removes a sound to this sound track
  71701. * @param sound define the cound to remove
  71702. * @ignoreNaming
  71703. */
  71704. SoundTrack.prototype.RemoveSound = function (sound) {
  71705. var index = this.soundCollection.indexOf(sound);
  71706. if (index !== -1) {
  71707. this.soundCollection.splice(index, 1);
  71708. }
  71709. };
  71710. /**
  71711. * Set a global volume for the full sound track.
  71712. * @param newVolume Define the new volume of the sound track
  71713. */
  71714. SoundTrack.prototype.setVolume = function (newVolume) {
  71715. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71716. this._outputAudioNode.gain.value = newVolume;
  71717. }
  71718. };
  71719. /**
  71720. * Switch the panning model to HRTF:
  71721. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71722. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71723. */
  71724. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  71725. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71726. for (var i = 0; i < this.soundCollection.length; i++) {
  71727. this.soundCollection[i].switchPanningModelToHRTF();
  71728. }
  71729. }
  71730. };
  71731. /**
  71732. * Switch the panning model to Equal Power:
  71733. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71734. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71735. */
  71736. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  71737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71738. for (var i = 0; i < this.soundCollection.length; i++) {
  71739. this.soundCollection[i].switchPanningModelToEqualPower();
  71740. }
  71741. }
  71742. };
  71743. /**
  71744. * Connect the sound track to an audio analyser allowing some amazing
  71745. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71746. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71747. * @param analyser The analyser to connect to the engine
  71748. */
  71749. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  71750. if (this._connectedAnalyser) {
  71751. this._connectedAnalyser.stopDebugCanvas();
  71752. }
  71753. this._connectedAnalyser = analyser;
  71754. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71755. this._outputAudioNode.disconnect();
  71756. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  71757. }
  71758. };
  71759. return SoundTrack;
  71760. }());
  71761. BABYLON.SoundTrack = SoundTrack;
  71762. })(BABYLON || (BABYLON = {}));
  71763. //# sourceMappingURL=babylon.soundtrack.js.map
  71764. var BABYLON;
  71765. (function (BABYLON) {
  71766. /**
  71767. * Class used to work with sound analyzer using fast fourier transform (FFT)
  71768. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71769. */
  71770. var Analyser = /** @class */ (function () {
  71771. /**
  71772. * Creates a new analyser
  71773. * @param scene defines hosting scene
  71774. */
  71775. function Analyser(scene) {
  71776. /**
  71777. * Gets or sets the smoothing
  71778. * @ignorenaming
  71779. */
  71780. this.SMOOTHING = 0.75;
  71781. /**
  71782. * Gets or sets the FFT table size
  71783. * @ignorenaming
  71784. */
  71785. this.FFT_SIZE = 512;
  71786. /**
  71787. * Gets or sets the bar graph amplitude
  71788. * @ignorenaming
  71789. */
  71790. this.BARGRAPHAMPLITUDE = 256;
  71791. /**
  71792. * Gets or sets the position of the debug canvas
  71793. * @ignorenaming
  71794. */
  71795. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  71796. /**
  71797. * Gets or sets the debug canvas size
  71798. * @ignorenaming
  71799. */
  71800. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  71801. this._scene = scene;
  71802. this._audioEngine = BABYLON.Engine.audioEngine;
  71803. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  71804. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  71805. this._webAudioAnalyser.minDecibels = -140;
  71806. this._webAudioAnalyser.maxDecibels = 0;
  71807. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71808. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71809. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  71810. }
  71811. }
  71812. /**
  71813. * Get the number of data values you will have to play with for the visualization
  71814. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  71815. * @returns a number
  71816. */
  71817. Analyser.prototype.getFrequencyBinCount = function () {
  71818. if (this._audioEngine.canUseWebAudio) {
  71819. return this._webAudioAnalyser.frequencyBinCount;
  71820. }
  71821. else {
  71822. return 0;
  71823. }
  71824. };
  71825. /**
  71826. * Gets the current frequency data as a byte array
  71827. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71828. * @returns a Uint8Array
  71829. */
  71830. Analyser.prototype.getByteFrequencyData = function () {
  71831. if (this._audioEngine.canUseWebAudio) {
  71832. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71833. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71834. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  71835. }
  71836. return this._byteFreqs;
  71837. };
  71838. /**
  71839. * Gets the current waveform as a byte array
  71840. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  71841. * @returns a Uint8Array
  71842. */
  71843. Analyser.prototype.getByteTimeDomainData = function () {
  71844. if (this._audioEngine.canUseWebAudio) {
  71845. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71846. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71847. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  71848. }
  71849. return this._byteTime;
  71850. };
  71851. /**
  71852. * Gets the current frequency data as a float array
  71853. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71854. * @returns a Float32Array
  71855. */
  71856. Analyser.prototype.getFloatFrequencyData = function () {
  71857. if (this._audioEngine.canUseWebAudio) {
  71858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71860. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  71861. }
  71862. return this._floatFreqs;
  71863. };
  71864. /**
  71865. * Renders the debug canvas
  71866. */
  71867. Analyser.prototype.drawDebugCanvas = function () {
  71868. var _this = this;
  71869. if (this._audioEngine.canUseWebAudio) {
  71870. if (!this._debugCanvas) {
  71871. this._debugCanvas = document.createElement("canvas");
  71872. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  71873. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  71874. this._debugCanvas.style.position = "absolute";
  71875. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  71876. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  71877. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  71878. document.body.appendChild(this._debugCanvas);
  71879. this._registerFunc = function () {
  71880. _this.drawDebugCanvas();
  71881. };
  71882. this._scene.registerBeforeRender(this._registerFunc);
  71883. }
  71884. if (this._registerFunc && this._debugCanvasContext) {
  71885. var workingArray = this.getByteFrequencyData();
  71886. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  71887. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  71888. // Draw the frequency domain chart.
  71889. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  71890. var value = workingArray[i];
  71891. var percent = value / this.BARGRAPHAMPLITUDE;
  71892. var height = this.DEBUGCANVASSIZE.height * percent;
  71893. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  71894. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  71895. var hue = i / this.getFrequencyBinCount() * 360;
  71896. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  71897. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  71898. }
  71899. }
  71900. }
  71901. };
  71902. /**
  71903. * Stops rendering the debug canvas and removes it
  71904. */
  71905. Analyser.prototype.stopDebugCanvas = function () {
  71906. if (this._debugCanvas) {
  71907. if (this._registerFunc) {
  71908. this._scene.unregisterBeforeRender(this._registerFunc);
  71909. this._registerFunc = null;
  71910. }
  71911. document.body.removeChild(this._debugCanvas);
  71912. this._debugCanvas = null;
  71913. this._debugCanvasContext = null;
  71914. }
  71915. };
  71916. /**
  71917. * Connects two audio nodes
  71918. * @param inputAudioNode defines first node to connect
  71919. * @param outputAudioNode defines second node to connect
  71920. */
  71921. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  71922. if (this._audioEngine.canUseWebAudio) {
  71923. inputAudioNode.connect(this._webAudioAnalyser);
  71924. this._webAudioAnalyser.connect(outputAudioNode);
  71925. }
  71926. };
  71927. /**
  71928. * Releases all associated resources
  71929. */
  71930. Analyser.prototype.dispose = function () {
  71931. if (this._audioEngine.canUseWebAudio) {
  71932. this._webAudioAnalyser.disconnect();
  71933. }
  71934. };
  71935. return Analyser;
  71936. }());
  71937. BABYLON.Analyser = Analyser;
  71938. })(BABYLON || (BABYLON = {}));
  71939. //# sourceMappingURL=babylon.analyser.js.map
  71940. var BABYLON;
  71941. (function (BABYLON) {
  71942. /**
  71943. * Wraps one or more Sound objects and selects one with random weight for playback.
  71944. */
  71945. var WeightedSound = /** @class */ (function () {
  71946. /**
  71947. * Creates a new WeightedSound from the list of sounds given.
  71948. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  71949. * @param sounds Array of Sounds that will be selected from.
  71950. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  71951. */
  71952. function WeightedSound(loop, sounds, weights) {
  71953. var _this = this;
  71954. /** When true a Sound will be selected and played when the current playing Sound completes. */
  71955. this.loop = false;
  71956. this._coneInnerAngle = 360;
  71957. this._coneOuterAngle = 360;
  71958. this._volume = 1;
  71959. /** A Sound is currently playing. */
  71960. this.isPlaying = false;
  71961. /** A Sound is currently paused. */
  71962. this.isPaused = false;
  71963. this._sounds = [];
  71964. this._weights = [];
  71965. if (sounds.length !== weights.length) {
  71966. throw new Error('Sounds length does not equal weights length');
  71967. }
  71968. this.loop = loop;
  71969. this._weights = weights;
  71970. // Normalize the weights
  71971. var weightSum = 0;
  71972. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  71973. var weight = weights_1[_i];
  71974. weightSum += weight;
  71975. }
  71976. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  71977. for (var i = 0; i < this._weights.length; i++) {
  71978. this._weights[i] *= invWeightSum;
  71979. }
  71980. this._sounds = sounds;
  71981. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  71982. var sound = _b[_a];
  71983. sound.onEndedObservable.add(function () { _this._onended(); });
  71984. }
  71985. }
  71986. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  71987. /**
  71988. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  71989. */
  71990. get: function () {
  71991. return this._coneInnerAngle;
  71992. },
  71993. /**
  71994. * The size of cone in degress for a directional sound in which there will be no attenuation.
  71995. */
  71996. set: function (value) {
  71997. if (value !== this._coneInnerAngle) {
  71998. if (this._coneOuterAngle < value) {
  71999. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72000. return;
  72001. }
  72002. this._coneInnerAngle = value;
  72003. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72004. var sound = _a[_i];
  72005. sound.directionalConeInnerAngle = value;
  72006. }
  72007. }
  72008. },
  72009. enumerable: true,
  72010. configurable: true
  72011. });
  72012. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72013. /**
  72014. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72015. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72016. */
  72017. get: function () {
  72018. return this._coneOuterAngle;
  72019. },
  72020. /**
  72021. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72022. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72023. */
  72024. set: function (value) {
  72025. if (value !== this._coneOuterAngle) {
  72026. if (value < this._coneInnerAngle) {
  72027. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72028. return;
  72029. }
  72030. this._coneOuterAngle = value;
  72031. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72032. var sound = _a[_i];
  72033. sound.directionalConeOuterAngle = value;
  72034. }
  72035. }
  72036. },
  72037. enumerable: true,
  72038. configurable: true
  72039. });
  72040. Object.defineProperty(WeightedSound.prototype, "volume", {
  72041. /**
  72042. * Playback volume.
  72043. */
  72044. get: function () {
  72045. return this._volume;
  72046. },
  72047. /**
  72048. * Playback volume.
  72049. */
  72050. set: function (value) {
  72051. if (value !== this._volume) {
  72052. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72053. var sound = _a[_i];
  72054. sound.setVolume(value);
  72055. }
  72056. }
  72057. },
  72058. enumerable: true,
  72059. configurable: true
  72060. });
  72061. WeightedSound.prototype._onended = function () {
  72062. if (this._currentIndex !== undefined) {
  72063. this._sounds[this._currentIndex].autoplay = false;
  72064. }
  72065. if (this.loop && this.isPlaying) {
  72066. this.play();
  72067. }
  72068. else {
  72069. this.isPlaying = false;
  72070. }
  72071. };
  72072. /**
  72073. * Suspend playback
  72074. */
  72075. WeightedSound.prototype.pause = function () {
  72076. this.isPaused = true;
  72077. if (this._currentIndex !== undefined) {
  72078. this._sounds[this._currentIndex].pause();
  72079. }
  72080. };
  72081. /**
  72082. * Stop playback
  72083. */
  72084. WeightedSound.prototype.stop = function () {
  72085. this.isPlaying = false;
  72086. if (this._currentIndex !== undefined) {
  72087. this._sounds[this._currentIndex].stop();
  72088. }
  72089. };
  72090. /**
  72091. * Start playback.
  72092. * @param startOffset Position the clip head at a specific time in seconds.
  72093. */
  72094. WeightedSound.prototype.play = function (startOffset) {
  72095. if (!this.isPaused) {
  72096. this.stop();
  72097. var randomValue = Math.random();
  72098. var total = 0;
  72099. for (var i = 0; i < this._weights.length; i++) {
  72100. total += this._weights[i];
  72101. if (randomValue <= total) {
  72102. this._currentIndex = i;
  72103. break;
  72104. }
  72105. }
  72106. }
  72107. var sound = this._sounds[this._currentIndex];
  72108. if (sound.isReady()) {
  72109. sound.play(0, this.isPaused ? undefined : startOffset);
  72110. }
  72111. else {
  72112. sound.autoplay = true;
  72113. }
  72114. this.isPlaying = true;
  72115. this.isPaused = false;
  72116. };
  72117. return WeightedSound;
  72118. }());
  72119. BABYLON.WeightedSound = WeightedSound;
  72120. })(BABYLON || (BABYLON = {}));
  72121. //# sourceMappingURL=babylon.weightedsound.js.map
  72122. var BABYLON;
  72123. (function (BABYLON) {
  72124. // Adds the parser to the scene parsers.
  72125. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72126. // TODO: add sound
  72127. var loadedSounds = [];
  72128. var loadedSound;
  72129. container.sounds = container.sounds || [];
  72130. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72131. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72132. var parsedSound = parsedData.sounds[index];
  72133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72134. if (!parsedSound.url) {
  72135. parsedSound.url = parsedSound.name;
  72136. }
  72137. if (!loadedSounds[parsedSound.url]) {
  72138. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72139. loadedSounds[parsedSound.url] = loadedSound;
  72140. container.sounds.push(loadedSound);
  72141. }
  72142. else {
  72143. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72144. }
  72145. }
  72146. else {
  72147. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72148. }
  72149. }
  72150. }
  72151. loadedSounds = [];
  72152. });
  72153. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72154. get: function () {
  72155. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72156. if (!compo) {
  72157. compo = new AudioSceneComponent(this);
  72158. this._addComponent(compo);
  72159. }
  72160. if (!this._mainSoundTrack) {
  72161. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72162. }
  72163. return this._mainSoundTrack;
  72164. },
  72165. enumerable: true,
  72166. configurable: true
  72167. });
  72168. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72169. var index;
  72170. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72171. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72172. return this.mainSoundTrack.soundCollection[index];
  72173. }
  72174. }
  72175. if (this.soundTracks) {
  72176. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72177. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72178. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72179. return this.soundTracks[sdIndex].soundCollection[index];
  72180. }
  72181. }
  72182. }
  72183. }
  72184. return null;
  72185. };
  72186. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72187. get: function () {
  72188. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72189. if (!compo) {
  72190. compo = new AudioSceneComponent(this);
  72191. this._addComponent(compo);
  72192. }
  72193. return compo.audioEnabled;
  72194. },
  72195. set: function (value) {
  72196. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72197. if (!compo) {
  72198. compo = new AudioSceneComponent(this);
  72199. this._addComponent(compo);
  72200. }
  72201. if (value) {
  72202. compo.enableAudio();
  72203. }
  72204. else {
  72205. compo.disableAudio();
  72206. }
  72207. },
  72208. enumerable: true,
  72209. configurable: true
  72210. });
  72211. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72212. get: function () {
  72213. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72214. if (!compo) {
  72215. compo = new AudioSceneComponent(this);
  72216. this._addComponent(compo);
  72217. }
  72218. return compo.headphone;
  72219. },
  72220. set: function (value) {
  72221. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72222. if (!compo) {
  72223. compo = new AudioSceneComponent(this);
  72224. this._addComponent(compo);
  72225. }
  72226. if (value) {
  72227. compo.switchAudioModeForHeadphones();
  72228. }
  72229. else {
  72230. compo.switchAudioModeForNormalSpeakers();
  72231. }
  72232. },
  72233. enumerable: true,
  72234. configurable: true
  72235. });
  72236. /**
  72237. * Defines the sound scene component responsible to manage any sounds
  72238. * in a given scene.
  72239. */
  72240. var AudioSceneComponent = /** @class */ (function () {
  72241. /**
  72242. * Creates a new instance of the component for the given scene
  72243. * @param scene Defines the scene to register the component in
  72244. */
  72245. function AudioSceneComponent(scene) {
  72246. /**
  72247. * The component name helpfull to identify the component in the list of scene components.
  72248. */
  72249. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72250. this._audioEnabled = true;
  72251. this._headphone = false;
  72252. this.scene = scene;
  72253. scene.soundTracks = new Array();
  72254. scene.sounds = new Array();
  72255. }
  72256. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72257. /**
  72258. * Gets whether audio is enabled or not.
  72259. * Please use related enable/disable method to switch state.
  72260. */
  72261. get: function () {
  72262. return this._audioEnabled;
  72263. },
  72264. enumerable: true,
  72265. configurable: true
  72266. });
  72267. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72268. /**
  72269. * Gets whether audio is outputing to headphone or not.
  72270. * Please use the according Switch methods to change output.
  72271. */
  72272. get: function () {
  72273. return this._headphone;
  72274. },
  72275. enumerable: true,
  72276. configurable: true
  72277. });
  72278. /**
  72279. * Registers the component in a given scene
  72280. */
  72281. AudioSceneComponent.prototype.register = function () {
  72282. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72283. };
  72284. /**
  72285. * Rebuilds the elements related to this component in case of
  72286. * context lost for instance.
  72287. */
  72288. AudioSceneComponent.prototype.rebuild = function () {
  72289. // Nothing to do here. (Not rendering related)
  72290. };
  72291. /**
  72292. * Serializes the component data to the specified json object
  72293. * @param serializationObject The object to serialize to
  72294. */
  72295. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72296. serializationObject.sounds = [];
  72297. if (this.scene.soundTracks) {
  72298. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72299. var soundtrack = this.scene.soundTracks[index];
  72300. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72301. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72302. }
  72303. }
  72304. }
  72305. };
  72306. /**
  72307. * Adds all the element from the container to the scene
  72308. * @param container the container holding the elements
  72309. */
  72310. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72311. var _this = this;
  72312. if (!container.sounds) {
  72313. return;
  72314. }
  72315. container.sounds.forEach(function (sound) {
  72316. sound.play();
  72317. sound.autoplay = true;
  72318. _this.scene.mainSoundTrack.AddSound(sound);
  72319. });
  72320. };
  72321. /**
  72322. * Removes all the elements in the container from the scene
  72323. * @param container contains the elements to remove
  72324. */
  72325. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72326. var _this = this;
  72327. if (!container.sounds) {
  72328. return;
  72329. }
  72330. container.sounds.forEach(function (sound) {
  72331. sound.stop();
  72332. sound.autoplay = false;
  72333. _this.scene.mainSoundTrack.RemoveSound(sound);
  72334. });
  72335. };
  72336. /**
  72337. * Disposes the component and the associated ressources.
  72338. */
  72339. AudioSceneComponent.prototype.dispose = function () {
  72340. var scene = this.scene;
  72341. if (scene._mainSoundTrack) {
  72342. scene.mainSoundTrack.dispose();
  72343. }
  72344. if (scene.soundTracks) {
  72345. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72346. scene.soundTracks[scIndex].dispose();
  72347. }
  72348. }
  72349. };
  72350. /**
  72351. * Disables audio in the associated scene.
  72352. */
  72353. AudioSceneComponent.prototype.disableAudio = function () {
  72354. var scene = this.scene;
  72355. this._audioEnabled = false;
  72356. var i;
  72357. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72358. scene.mainSoundTrack.soundCollection[i].pause();
  72359. }
  72360. if (scene.soundTracks) {
  72361. for (i = 0; i < scene.soundTracks.length; i++) {
  72362. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72363. scene.soundTracks[i].soundCollection[j].pause();
  72364. }
  72365. }
  72366. }
  72367. };
  72368. /**
  72369. * Enables audio in the associated scene.
  72370. */
  72371. AudioSceneComponent.prototype.enableAudio = function () {
  72372. var scene = this.scene;
  72373. this._audioEnabled = true;
  72374. var i;
  72375. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72376. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72377. scene.mainSoundTrack.soundCollection[i].play();
  72378. }
  72379. }
  72380. if (scene.soundTracks) {
  72381. for (i = 0; i < scene.soundTracks.length; i++) {
  72382. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72383. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72384. scene.soundTracks[i].soundCollection[j].play();
  72385. }
  72386. }
  72387. }
  72388. }
  72389. };
  72390. /**
  72391. * Switch audio to headphone output.
  72392. */
  72393. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72394. var scene = this.scene;
  72395. this._headphone = true;
  72396. scene.mainSoundTrack.switchPanningModelToHRTF();
  72397. if (scene.soundTracks) {
  72398. for (var i = 0; i < scene.soundTracks.length; i++) {
  72399. scene.soundTracks[i].switchPanningModelToHRTF();
  72400. }
  72401. }
  72402. };
  72403. /**
  72404. * Switch audio to normal speakers.
  72405. */
  72406. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72407. var scene = this.scene;
  72408. this._headphone = false;
  72409. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72410. if (scene.soundTracks) {
  72411. for (var i = 0; i < scene.soundTracks.length; i++) {
  72412. scene.soundTracks[i].switchPanningModelToEqualPower();
  72413. }
  72414. }
  72415. };
  72416. AudioSceneComponent.prototype._afterRender = function () {
  72417. var scene = this.scene;
  72418. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72419. return;
  72420. }
  72421. var listeningCamera;
  72422. var audioEngine = BABYLON.Engine.audioEngine;
  72423. if (scene.activeCameras.length > 0) {
  72424. listeningCamera = scene.activeCameras[0];
  72425. }
  72426. else {
  72427. listeningCamera = scene.activeCamera;
  72428. }
  72429. if (listeningCamera && audioEngine.audioContext) {
  72430. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72431. // for VR cameras
  72432. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72433. listeningCamera = listeningCamera.rigCameras[0];
  72434. }
  72435. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72436. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72437. cameraDirection.normalize();
  72438. // To avoid some errors on GearVR
  72439. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72440. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72441. }
  72442. var i;
  72443. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72444. var sound = scene.mainSoundTrack.soundCollection[i];
  72445. if (sound.useCustomAttenuation) {
  72446. sound.updateDistanceFromListener();
  72447. }
  72448. }
  72449. if (scene.soundTracks) {
  72450. for (i = 0; i < scene.soundTracks.length; i++) {
  72451. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72452. sound = scene.soundTracks[i].soundCollection[j];
  72453. if (sound.useCustomAttenuation) {
  72454. sound.updateDistanceFromListener();
  72455. }
  72456. }
  72457. }
  72458. }
  72459. }
  72460. };
  72461. return AudioSceneComponent;
  72462. }());
  72463. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72464. })(BABYLON || (BABYLON = {}));
  72465. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  72466. var BABYLON;
  72467. (function (BABYLON) {
  72468. /**
  72469. * This defines an action helpful to play a defined sound on a triggered action.
  72470. */
  72471. var PlaySoundAction = /** @class */ (function (_super) {
  72472. __extends(PlaySoundAction, _super);
  72473. /**
  72474. * Instantiate the action
  72475. * @param triggerOptions defines the trigger options
  72476. * @param sound defines the sound to play
  72477. * @param condition defines the trigger related conditions
  72478. */
  72479. function PlaySoundAction(triggerOptions, sound, condition) {
  72480. var _this = _super.call(this, triggerOptions, condition) || this;
  72481. _this._sound = sound;
  72482. return _this;
  72483. }
  72484. /** @hidden */
  72485. PlaySoundAction.prototype._prepare = function () {
  72486. };
  72487. /**
  72488. * Execute the action and play the sound.
  72489. */
  72490. PlaySoundAction.prototype.execute = function () {
  72491. if (this._sound !== undefined) {
  72492. this._sound.play();
  72493. }
  72494. };
  72495. /**
  72496. * Serializes the actions and its related information.
  72497. * @param parent defines the object to serialize in
  72498. * @returns the serialized object
  72499. */
  72500. PlaySoundAction.prototype.serialize = function (parent) {
  72501. return _super.prototype._serialize.call(this, {
  72502. name: "PlaySoundAction",
  72503. properties: [{ name: "sound", value: this._sound.name }]
  72504. }, parent);
  72505. };
  72506. return PlaySoundAction;
  72507. }(BABYLON.Action));
  72508. BABYLON.PlaySoundAction = PlaySoundAction;
  72509. /**
  72510. * This defines an action helpful to stop a defined sound on a triggered action.
  72511. */
  72512. var StopSoundAction = /** @class */ (function (_super) {
  72513. __extends(StopSoundAction, _super);
  72514. /**
  72515. * Instantiate the action
  72516. * @param triggerOptions defines the trigger options
  72517. * @param sound defines the sound to stop
  72518. * @param condition defines the trigger related conditions
  72519. */
  72520. function StopSoundAction(triggerOptions, sound, condition) {
  72521. var _this = _super.call(this, triggerOptions, condition) || this;
  72522. _this._sound = sound;
  72523. return _this;
  72524. }
  72525. /** @hidden */
  72526. StopSoundAction.prototype._prepare = function () {
  72527. };
  72528. /**
  72529. * Execute the action and stop the sound.
  72530. */
  72531. StopSoundAction.prototype.execute = function () {
  72532. if (this._sound !== undefined) {
  72533. this._sound.stop();
  72534. }
  72535. };
  72536. /**
  72537. * Serializes the actions and its related information.
  72538. * @param parent defines the object to serialize in
  72539. * @returns the serialized object
  72540. */
  72541. StopSoundAction.prototype.serialize = function (parent) {
  72542. return _super.prototype._serialize.call(this, {
  72543. name: "StopSoundAction",
  72544. properties: [{ name: "sound", value: this._sound.name }]
  72545. }, parent);
  72546. };
  72547. return StopSoundAction;
  72548. }(BABYLON.Action));
  72549. BABYLON.StopSoundAction = StopSoundAction;
  72550. })(BABYLON || (BABYLON = {}));
  72551. //# sourceMappingURL=babylon.directAudioActions.js.map
  72552. var BABYLON;
  72553. (function (BABYLON) {
  72554. /**
  72555. * Class for creating a cube texture
  72556. */
  72557. var CubeTexture = /** @class */ (function (_super) {
  72558. __extends(CubeTexture, _super);
  72559. /**
  72560. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  72561. * as prefiltered data.
  72562. * @param rootUrl defines the url of the texture or the root name of the six images
  72563. * @param scene defines the scene the texture is attached to
  72564. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  72565. * @param noMipmap defines if mipmaps should be created or not
  72566. * @param files defines the six files to load for the different faces
  72567. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  72568. * @param onError defines a callback triggered in case of error during load
  72569. * @param format defines the internal format to use for the texture once loaded
  72570. * @param prefiltered defines whether or not the texture is created from prefiltered data
  72571. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  72572. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72573. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72574. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72575. * @return the cube texture
  72576. */
  72577. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  72578. if (extensions === void 0) { extensions = null; }
  72579. if (noMipmap === void 0) { noMipmap = false; }
  72580. if (files === void 0) { files = null; }
  72581. if (onLoad === void 0) { onLoad = null; }
  72582. if (onError === void 0) { onError = null; }
  72583. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72584. if (prefiltered === void 0) { prefiltered = false; }
  72585. if (forcedExtension === void 0) { forcedExtension = null; }
  72586. if (createPolynomials === void 0) { createPolynomials = false; }
  72587. if (lodScale === void 0) { lodScale = 0.8; }
  72588. if (lodOffset === void 0) { lodOffset = 0; }
  72589. var _this = _super.call(this, scene) || this;
  72590. /**
  72591. * Gets or sets the center of the bounding box associated with the cube texture.
  72592. * It must define where the camera used to render the texture was set
  72593. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72594. */
  72595. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72596. _this._rotationY = 0;
  72597. /** @hidden */
  72598. _this._prefiltered = false;
  72599. _this.name = rootUrl;
  72600. _this.url = rootUrl;
  72601. _this._noMipmap = noMipmap;
  72602. _this.hasAlpha = false;
  72603. _this._format = format;
  72604. _this.isCube = true;
  72605. _this._textureMatrix = BABYLON.Matrix.Identity();
  72606. _this._createPolynomials = createPolynomials;
  72607. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72608. if (!rootUrl && !files) {
  72609. return _this;
  72610. }
  72611. var lastDot = rootUrl.lastIndexOf(".");
  72612. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  72613. var isDDS = (extension === ".dds");
  72614. var isEnv = (extension === ".env");
  72615. if (isEnv) {
  72616. _this.gammaSpace = false;
  72617. _this._prefiltered = false;
  72618. }
  72619. else {
  72620. _this._prefiltered = prefiltered;
  72621. if (prefiltered) {
  72622. _this.gammaSpace = false;
  72623. }
  72624. }
  72625. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  72626. if (!files) {
  72627. if (!isEnv && !isDDS && !extensions) {
  72628. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  72629. }
  72630. files = [];
  72631. if (extensions) {
  72632. for (var index = 0; index < extensions.length; index++) {
  72633. files.push(rootUrl + extensions[index]);
  72634. }
  72635. }
  72636. }
  72637. _this._files = files;
  72638. if (!_this._texture) {
  72639. if (!scene.useDelayedTextureLoading) {
  72640. if (prefiltered) {
  72641. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  72642. }
  72643. else {
  72644. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  72645. }
  72646. }
  72647. else {
  72648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72649. }
  72650. }
  72651. else if (onLoad) {
  72652. if (_this._texture.isReady) {
  72653. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  72654. }
  72655. else {
  72656. _this._texture.onLoadedObservable.add(onLoad);
  72657. }
  72658. }
  72659. return _this;
  72660. }
  72661. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  72662. /**
  72663. * Returns the bounding box size
  72664. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72665. */
  72666. get: function () {
  72667. return this._boundingBoxSize;
  72668. },
  72669. /**
  72670. * Gets or sets the size of the bounding box associated with the cube texture
  72671. * When defined, the cubemap will switch to local mode
  72672. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72673. * @example https://www.babylonjs-playground.com/#RNASML
  72674. */
  72675. set: function (value) {
  72676. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72677. return;
  72678. }
  72679. this._boundingBoxSize = value;
  72680. var scene = this.getScene();
  72681. if (scene) {
  72682. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72683. }
  72684. },
  72685. enumerable: true,
  72686. configurable: true
  72687. });
  72688. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  72689. /**
  72690. * Gets texture matrix rotation angle around Y axis radians.
  72691. */
  72692. get: function () {
  72693. return this._rotationY;
  72694. },
  72695. /**
  72696. * Sets texture matrix rotation angle around Y axis in radians.
  72697. */
  72698. set: function (value) {
  72699. this._rotationY = value;
  72700. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  72701. },
  72702. enumerable: true,
  72703. configurable: true
  72704. });
  72705. /**
  72706. * Creates a cube texture from an array of image urls
  72707. * @param files defines an array of image urls
  72708. * @param scene defines the hosting scene
  72709. * @param noMipmap specifies if mip maps are not used
  72710. * @returns a cube texture
  72711. */
  72712. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  72713. var rootUrlKey = "";
  72714. files.forEach(function (url) { return rootUrlKey += url; });
  72715. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  72716. };
  72717. /**
  72718. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  72719. * @param url defines the url of the prefiltered texture
  72720. * @param scene defines the scene the texture is attached to
  72721. * @param forcedExtension defines the extension of the file if different from the url
  72722. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72723. * @return the prefiltered texture
  72724. */
  72725. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  72726. if (forcedExtension === void 0) { forcedExtension = null; }
  72727. if (createPolynomials === void 0) { createPolynomials = true; }
  72728. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  72729. };
  72730. /**
  72731. * Delays loading of the cube texture
  72732. */
  72733. CubeTexture.prototype.delayLoad = function () {
  72734. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72735. return;
  72736. }
  72737. var scene = this.getScene();
  72738. if (!scene) {
  72739. return;
  72740. }
  72741. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72742. this._texture = this._getFromCache(this.url, this._noMipmap);
  72743. if (!this._texture) {
  72744. if (this._prefiltered) {
  72745. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  72746. }
  72747. else {
  72748. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  72749. }
  72750. }
  72751. };
  72752. /**
  72753. * Returns the reflection texture matrix
  72754. * @returns the reflection texture matrix
  72755. */
  72756. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  72757. return this._textureMatrix;
  72758. };
  72759. /**
  72760. * Sets the reflection texture matrix
  72761. * @param value Reflection texture matrix
  72762. */
  72763. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72764. this._textureMatrix = value;
  72765. };
  72766. /**
  72767. * Parses text to create a cube texture
  72768. * @param parsedTexture define the serialized text to read from
  72769. * @param scene defines the hosting scene
  72770. * @param rootUrl defines the root url of the cube texture
  72771. * @returns a cube texture
  72772. */
  72773. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72774. var texture = BABYLON.SerializationHelper.Parse(function () {
  72775. var prefiltered = false;
  72776. if (parsedTexture.prefiltered) {
  72777. prefiltered = parsedTexture.prefiltered;
  72778. }
  72779. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  72780. }, parsedTexture, scene);
  72781. // Local Cubemaps
  72782. if (parsedTexture.boundingBoxPosition) {
  72783. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72784. }
  72785. if (parsedTexture.boundingBoxSize) {
  72786. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72787. }
  72788. // Animations
  72789. if (parsedTexture.animations) {
  72790. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  72791. var parsedAnimation = parsedTexture.animations[animationIndex];
  72792. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  72793. }
  72794. }
  72795. return texture;
  72796. };
  72797. /**
  72798. * Makes a clone, or deep copy, of the cube texture
  72799. * @returns a new cube texture
  72800. */
  72801. CubeTexture.prototype.clone = function () {
  72802. var _this = this;
  72803. return BABYLON.SerializationHelper.Clone(function () {
  72804. var scene = _this.getScene();
  72805. if (!scene) {
  72806. return _this;
  72807. }
  72808. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  72809. }, this);
  72810. };
  72811. __decorate([
  72812. BABYLON.serialize("rotationY")
  72813. ], CubeTexture.prototype, "rotationY", null);
  72814. return CubeTexture;
  72815. }(BABYLON.BaseTexture));
  72816. BABYLON.CubeTexture = CubeTexture;
  72817. })(BABYLON || (BABYLON = {}));
  72818. //# sourceMappingURL=babylon.cubeTexture.js.map
  72819. var BABYLON;
  72820. (function (BABYLON) {
  72821. /**
  72822. * Raw cube texture where the raw buffers are passed in
  72823. */
  72824. var RawCubeTexture = /** @class */ (function (_super) {
  72825. __extends(RawCubeTexture, _super);
  72826. /**
  72827. * Creates a cube texture where the raw buffers are passed in.
  72828. * @param scene defines the scene the texture is attached to
  72829. * @param data defines the array of data to use to create each face
  72830. * @param size defines the size of the textures
  72831. * @param format defines the format of the data
  72832. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  72833. * @param generateMipMaps defines if the engine should generate the mip levels
  72834. * @param invertY defines if data must be stored with Y axis inverted
  72835. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  72836. * @param compression defines the compression used (null by default)
  72837. */
  72838. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  72839. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72840. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72841. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72842. if (invertY === void 0) { invertY = false; }
  72843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72844. if (compression === void 0) { compression = null; }
  72845. var _this = _super.call(this, "", scene) || this;
  72846. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  72847. return _this;
  72848. }
  72849. /**
  72850. * Updates the raw cube texture.
  72851. * @param data defines the data to store
  72852. * @param format defines the data format
  72853. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  72854. * @param invertY defines if data must be stored with Y axis inverted
  72855. * @param compression defines the compression used (null by default)
  72856. * @param level defines which level of the texture to update
  72857. */
  72858. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  72859. if (compression === void 0) { compression = null; }
  72860. if (level === void 0) { level = 0; }
  72861. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  72862. };
  72863. /**
  72864. * Updates a raw cube texture with RGBD encoded data.
  72865. * @param data defines the array of data [mipmap][face] to use to create each face
  72866. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  72867. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72868. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72869. * @returns a promsie that resolves when the operation is complete
  72870. */
  72871. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  72872. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  72873. if (lodScale === void 0) { lodScale = 0.8; }
  72874. if (lodOffset === void 0) { lodOffset = 0; }
  72875. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  72876. };
  72877. /**
  72878. * Clones the raw cube texture.
  72879. * @return a new cube texture
  72880. */
  72881. RawCubeTexture.prototype.clone = function () {
  72882. var _this = this;
  72883. return BABYLON.SerializationHelper.Clone(function () {
  72884. var scene = _this.getScene();
  72885. var internalTexture = _this._texture;
  72886. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  72887. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  72888. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  72889. }
  72890. return texture;
  72891. }, this);
  72892. };
  72893. /** @hidden */
  72894. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  72895. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  72896. internalTexture._bufferViewArrayArray = data;
  72897. internalTexture._lodGenerationScale = lodScale;
  72898. internalTexture._lodGenerationOffset = lodOffset;
  72899. internalTexture._sphericalPolynomial = sphericalPolynomial;
  72900. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  72901. internalTexture.isReady = true;
  72902. });
  72903. };
  72904. return RawCubeTexture;
  72905. }(BABYLON.CubeTexture));
  72906. BABYLON.RawCubeTexture = RawCubeTexture;
  72907. })(BABYLON || (BABYLON = {}));
  72908. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  72909. var BABYLON;
  72910. (function (BABYLON) {
  72911. /**
  72912. * This Helps creating a texture that will be created from a camera in your scene.
  72913. * It is basically a dynamic texture that could be used to create special effects for instance.
  72914. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  72915. */
  72916. var RenderTargetTexture = /** @class */ (function (_super) {
  72917. __extends(RenderTargetTexture, _super);
  72918. /**
  72919. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  72920. * or used a shadow, depth texture...
  72921. * @param name The friendly name of the texture
  72922. * @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)
  72923. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  72924. * @param generateMipMaps True if mip maps need to be generated after render.
  72925. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  72926. * @param type The type of the buffer in the RTT (int, half float, float...)
  72927. * @param isCube True if a cube texture needs to be created
  72928. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  72929. * @param generateDepthBuffer True to generate a depth buffer
  72930. * @param generateStencilBuffer True to generate a stencil buffer
  72931. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  72932. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  72933. */
  72934. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  72935. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  72936. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72937. if (isCube === void 0) { isCube = false; }
  72938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72939. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72940. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  72941. if (isMulti === void 0) { isMulti = false; }
  72942. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72943. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72944. _this.isCube = isCube;
  72945. /**
  72946. * Define if particles should be rendered in your texture.
  72947. */
  72948. _this.renderParticles = true;
  72949. /**
  72950. * Define if sprites should be rendered in your texture.
  72951. */
  72952. _this.renderSprites = false;
  72953. /**
  72954. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  72955. */
  72956. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  72957. /**
  72958. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  72959. */
  72960. _this.ignoreCameraViewport = false;
  72961. /**
  72962. * An event triggered when the texture is unbind.
  72963. */
  72964. _this.onBeforeBindObservable = new BABYLON.Observable();
  72965. /**
  72966. * An event triggered when the texture is unbind.
  72967. */
  72968. _this.onAfterUnbindObservable = new BABYLON.Observable();
  72969. /**
  72970. * An event triggered before rendering the texture
  72971. */
  72972. _this.onBeforeRenderObservable = new BABYLON.Observable();
  72973. /**
  72974. * An event triggered after rendering the texture
  72975. */
  72976. _this.onAfterRenderObservable = new BABYLON.Observable();
  72977. /**
  72978. * An event triggered after the texture clear
  72979. */
  72980. _this.onClearObservable = new BABYLON.Observable();
  72981. _this._currentRefreshId = -1;
  72982. _this._refreshRate = 1;
  72983. _this._samples = 1;
  72984. /**
  72985. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  72986. * It must define where the camera used to render the texture is set
  72987. */
  72988. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72989. scene = _this.getScene();
  72990. if (!scene) {
  72991. return _this;
  72992. }
  72993. _this.renderList = new Array();
  72994. _this._engine = scene.getEngine();
  72995. _this.name = name;
  72996. _this.isRenderTarget = true;
  72997. _this._initialSizeParameter = size;
  72998. _this._processSizeParameter(size);
  72999. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73000. });
  73001. _this._generateMipMaps = generateMipMaps ? true : false;
  73002. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73003. // Rendering groups
  73004. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73005. _this._renderingManager._useSceneAutoClearSetup = true;
  73006. if (isMulti) {
  73007. return _this;
  73008. }
  73009. _this._renderTargetOptions = {
  73010. generateMipMaps: generateMipMaps,
  73011. type: type,
  73012. format: format,
  73013. samplingMode: samplingMode,
  73014. generateDepthBuffer: generateDepthBuffer,
  73015. generateStencilBuffer: generateStencilBuffer
  73016. };
  73017. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73018. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73019. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73020. }
  73021. if (isCube) {
  73022. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73023. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73024. _this._textureMatrix = BABYLON.Matrix.Identity();
  73025. }
  73026. else {
  73027. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73028. }
  73029. return _this;
  73030. }
  73031. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73032. /**
  73033. * Use this list to define the list of mesh you want to render.
  73034. */
  73035. get: function () {
  73036. return this._renderList;
  73037. },
  73038. set: function (value) {
  73039. this._renderList = value;
  73040. if (this._renderList) {
  73041. this._hookArray(this._renderList);
  73042. }
  73043. },
  73044. enumerable: true,
  73045. configurable: true
  73046. });
  73047. RenderTargetTexture.prototype._hookArray = function (array) {
  73048. var _this = this;
  73049. var oldPush = array.push;
  73050. array.push = function () {
  73051. var items = [];
  73052. for (var _i = 0; _i < arguments.length; _i++) {
  73053. items[_i] = arguments[_i];
  73054. }
  73055. var wasEmpty = array.length === 0;
  73056. var result = oldPush.apply(array, items);
  73057. if (wasEmpty) {
  73058. _this.getScene().meshes.forEach(function (mesh) {
  73059. mesh._markSubMeshesAsLightDirty();
  73060. });
  73061. }
  73062. return result;
  73063. };
  73064. var oldSplice = array.splice;
  73065. array.splice = function (index, deleteCount) {
  73066. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73067. if (array.length === 0) {
  73068. _this.getScene().meshes.forEach(function (mesh) {
  73069. mesh._markSubMeshesAsLightDirty();
  73070. });
  73071. }
  73072. return deleted;
  73073. };
  73074. };
  73075. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73076. /**
  73077. * Set a after unbind callback in the texture.
  73078. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73079. */
  73080. set: function (callback) {
  73081. if (this._onAfterUnbindObserver) {
  73082. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73083. }
  73084. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73085. },
  73086. enumerable: true,
  73087. configurable: true
  73088. });
  73089. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73090. /**
  73091. * Set a before render callback in the texture.
  73092. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73093. */
  73094. set: function (callback) {
  73095. if (this._onBeforeRenderObserver) {
  73096. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73097. }
  73098. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73099. },
  73100. enumerable: true,
  73101. configurable: true
  73102. });
  73103. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73104. /**
  73105. * Set a after render callback in the texture.
  73106. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73107. */
  73108. set: function (callback) {
  73109. if (this._onAfterRenderObserver) {
  73110. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73111. }
  73112. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73113. },
  73114. enumerable: true,
  73115. configurable: true
  73116. });
  73117. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73118. /**
  73119. * Set a clear callback in the texture.
  73120. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73121. */
  73122. set: function (callback) {
  73123. if (this._onClearObserver) {
  73124. this.onClearObservable.remove(this._onClearObserver);
  73125. }
  73126. this._onClearObserver = this.onClearObservable.add(callback);
  73127. },
  73128. enumerable: true,
  73129. configurable: true
  73130. });
  73131. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73132. /**
  73133. * Gets render target creation options that were used.
  73134. */
  73135. get: function () {
  73136. return this._renderTargetOptions;
  73137. },
  73138. enumerable: true,
  73139. configurable: true
  73140. });
  73141. RenderTargetTexture.prototype._onRatioRescale = function () {
  73142. if (this._sizeRatio) {
  73143. this.resize(this._initialSizeParameter);
  73144. }
  73145. };
  73146. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73147. get: function () {
  73148. return this._boundingBoxSize;
  73149. },
  73150. /**
  73151. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73152. * When defined, the cubemap will switch to local mode
  73153. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73154. * @example https://www.babylonjs-playground.com/#RNASML
  73155. */
  73156. set: function (value) {
  73157. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73158. return;
  73159. }
  73160. this._boundingBoxSize = value;
  73161. var scene = this.getScene();
  73162. if (scene) {
  73163. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73164. }
  73165. },
  73166. enumerable: true,
  73167. configurable: true
  73168. });
  73169. /**
  73170. * Creates a depth stencil texture.
  73171. * This is only available in WebGL 2 or with the depth texture extension available.
  73172. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73173. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73174. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73175. */
  73176. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73177. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73178. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73179. if (generateStencil === void 0) { generateStencil = false; }
  73180. if (!this.getScene()) {
  73181. return;
  73182. }
  73183. var engine = this.getScene().getEngine();
  73184. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73185. bilinearFiltering: bilinearFiltering,
  73186. comparisonFunction: comparisonFunction,
  73187. generateStencil: generateStencil,
  73188. isCube: this.isCube
  73189. });
  73190. engine.setFrameBufferDepthStencilTexture(this);
  73191. };
  73192. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73193. if (size.ratio) {
  73194. this._sizeRatio = size.ratio;
  73195. this._size = {
  73196. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73197. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73198. };
  73199. }
  73200. else {
  73201. this._size = size;
  73202. }
  73203. };
  73204. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73205. /**
  73206. * Define the number of samples to use in case of MSAA.
  73207. * It defaults to one meaning no MSAA has been enabled.
  73208. */
  73209. get: function () {
  73210. return this._samples;
  73211. },
  73212. set: function (value) {
  73213. if (this._samples === value) {
  73214. return;
  73215. }
  73216. var scene = this.getScene();
  73217. if (!scene) {
  73218. return;
  73219. }
  73220. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73221. },
  73222. enumerable: true,
  73223. configurable: true
  73224. });
  73225. /**
  73226. * Resets the refresh counter of the texture and start bak from scratch.
  73227. * Could be usefull to regenerate the texture if it is setup to render only once.
  73228. */
  73229. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73230. this._currentRefreshId = -1;
  73231. };
  73232. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73233. /**
  73234. * Define the refresh rate of the texture or the rendering frequency.
  73235. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73236. */
  73237. get: function () {
  73238. return this._refreshRate;
  73239. },
  73240. set: function (value) {
  73241. this._refreshRate = value;
  73242. this.resetRefreshCounter();
  73243. },
  73244. enumerable: true,
  73245. configurable: true
  73246. });
  73247. /**
  73248. * Adds a post process to the render target rendering passes.
  73249. * @param postProcess define the post process to add
  73250. */
  73251. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73252. if (!this._postProcessManager) {
  73253. var scene = this.getScene();
  73254. if (!scene) {
  73255. return;
  73256. }
  73257. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73258. this._postProcesses = new Array();
  73259. }
  73260. this._postProcesses.push(postProcess);
  73261. this._postProcesses[0].autoClear = false;
  73262. };
  73263. /**
  73264. * Clear all the post processes attached to the render target
  73265. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73266. */
  73267. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73268. if (dispose === void 0) { dispose = false; }
  73269. if (!this._postProcesses) {
  73270. return;
  73271. }
  73272. if (dispose) {
  73273. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73274. var postProcess = _a[_i];
  73275. postProcess.dispose();
  73276. }
  73277. }
  73278. this._postProcesses = [];
  73279. };
  73280. /**
  73281. * Remove one of the post process from the list of attached post processes to the texture
  73282. * @param postProcess define the post process to remove from the list
  73283. */
  73284. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73285. if (!this._postProcesses) {
  73286. return;
  73287. }
  73288. var index = this._postProcesses.indexOf(postProcess);
  73289. if (index === -1) {
  73290. return;
  73291. }
  73292. this._postProcesses.splice(index, 1);
  73293. if (this._postProcesses.length > 0) {
  73294. this._postProcesses[0].autoClear = false;
  73295. }
  73296. };
  73297. /** @hidden */
  73298. RenderTargetTexture.prototype._shouldRender = function () {
  73299. if (this._currentRefreshId === -1) { // At least render once
  73300. this._currentRefreshId = 1;
  73301. return true;
  73302. }
  73303. if (this.refreshRate === this._currentRefreshId) {
  73304. this._currentRefreshId = 1;
  73305. return true;
  73306. }
  73307. this._currentRefreshId++;
  73308. return false;
  73309. };
  73310. /**
  73311. * Gets the actual render size of the texture.
  73312. * @returns the width of the render size
  73313. */
  73314. RenderTargetTexture.prototype.getRenderSize = function () {
  73315. return this.getRenderWidth();
  73316. };
  73317. /**
  73318. * Gets the actual render width of the texture.
  73319. * @returns the width of the render size
  73320. */
  73321. RenderTargetTexture.prototype.getRenderWidth = function () {
  73322. if (this._size.width) {
  73323. return this._size.width;
  73324. }
  73325. return this._size;
  73326. };
  73327. /**
  73328. * Gets the actual render height of the texture.
  73329. * @returns the height of the render size
  73330. */
  73331. RenderTargetTexture.prototype.getRenderHeight = function () {
  73332. if (this._size.width) {
  73333. return this._size.height;
  73334. }
  73335. return this._size;
  73336. };
  73337. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73338. /**
  73339. * Get if the texture can be rescaled or not.
  73340. */
  73341. get: function () {
  73342. return true;
  73343. },
  73344. enumerable: true,
  73345. configurable: true
  73346. });
  73347. /**
  73348. * Resize the texture using a ratio.
  73349. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73350. */
  73351. RenderTargetTexture.prototype.scale = function (ratio) {
  73352. var newSize = this.getRenderSize() * ratio;
  73353. this.resize(newSize);
  73354. };
  73355. /**
  73356. * Get the texture reflection matrix used to rotate/transform the reflection.
  73357. * @returns the reflection matrix
  73358. */
  73359. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73360. if (this.isCube) {
  73361. return this._textureMatrix;
  73362. }
  73363. return _super.prototype.getReflectionTextureMatrix.call(this);
  73364. };
  73365. /**
  73366. * Resize the texture to a new desired size.
  73367. * Be carrefull as it will recreate all the data in the new texture.
  73368. * @param size Define the new size. It can be:
  73369. * - a number for squared texture,
  73370. * - an object containing { width: number, height: number }
  73371. * - or an object containing a ratio { ratio: number }
  73372. */
  73373. RenderTargetTexture.prototype.resize = function (size) {
  73374. this.releaseInternalTexture();
  73375. var scene = this.getScene();
  73376. if (!scene) {
  73377. return;
  73378. }
  73379. this._processSizeParameter(size);
  73380. if (this.isCube) {
  73381. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73382. }
  73383. else {
  73384. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73385. }
  73386. };
  73387. /**
  73388. * Renders all the objects from the render list into the texture.
  73389. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73390. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73391. */
  73392. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73393. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73394. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73395. var scene = this.getScene();
  73396. if (!scene) {
  73397. return;
  73398. }
  73399. var engine = scene.getEngine();
  73400. if (this.useCameraPostProcesses !== undefined) {
  73401. useCameraPostProcess = this.useCameraPostProcesses;
  73402. }
  73403. if (this._waitingRenderList) {
  73404. this.renderList = [];
  73405. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73406. var id = this._waitingRenderList[index];
  73407. var mesh_1 = scene.getMeshByID(id);
  73408. if (mesh_1) {
  73409. this.renderList.push(mesh_1);
  73410. }
  73411. }
  73412. delete this._waitingRenderList;
  73413. }
  73414. // Is predicate defined?
  73415. if (this.renderListPredicate) {
  73416. if (this.renderList) {
  73417. this.renderList.splice(0); // Clear previous renderList
  73418. }
  73419. else {
  73420. this.renderList = [];
  73421. }
  73422. var scene = this.getScene();
  73423. if (!scene) {
  73424. return;
  73425. }
  73426. var sceneMeshes = scene.meshes;
  73427. for (var index = 0; index < sceneMeshes.length; index++) {
  73428. var mesh = sceneMeshes[index];
  73429. if (this.renderListPredicate(mesh)) {
  73430. this.renderList.push(mesh);
  73431. }
  73432. }
  73433. }
  73434. this.onBeforeBindObservable.notifyObservers(this);
  73435. // Set custom projection.
  73436. // Needs to be before binding to prevent changing the aspect ratio.
  73437. var camera;
  73438. if (this.activeCamera) {
  73439. camera = this.activeCamera;
  73440. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73441. if (this.activeCamera !== scene.activeCamera) {
  73442. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73443. }
  73444. }
  73445. else {
  73446. camera = scene.activeCamera;
  73447. if (camera) {
  73448. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73449. }
  73450. }
  73451. // Prepare renderingManager
  73452. this._renderingManager.reset();
  73453. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73454. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73455. var sceneRenderId = scene.getRenderId();
  73456. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73457. var mesh = currentRenderList[meshIndex];
  73458. if (mesh) {
  73459. if (!mesh.isReady(this.refreshRate === 0)) {
  73460. this.resetRefreshCounter();
  73461. continue;
  73462. }
  73463. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73464. var isMasked = void 0;
  73465. if (!this.renderList && camera) {
  73466. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73467. }
  73468. else {
  73469. isMasked = false;
  73470. }
  73471. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73472. mesh._activate(sceneRenderId);
  73473. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73474. var subMesh = mesh.subMeshes[subIndex];
  73475. scene._activeIndices.addCount(subMesh.indexCount, false);
  73476. this._renderingManager.dispatch(subMesh, mesh);
  73477. }
  73478. }
  73479. }
  73480. }
  73481. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73482. var particleSystem = scene.particleSystems[particleIndex];
  73483. var emitter = particleSystem.emitter;
  73484. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73485. continue;
  73486. }
  73487. if (currentRenderList.indexOf(emitter) >= 0) {
  73488. this._renderingManager.dispatchParticles(particleSystem);
  73489. }
  73490. }
  73491. if (this.isCube) {
  73492. for (var face = 0; face < 6; face++) {
  73493. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73494. scene.incrementRenderId();
  73495. scene.resetCachedMaterial();
  73496. }
  73497. }
  73498. else {
  73499. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73500. }
  73501. this.onAfterUnbindObservable.notifyObservers(this);
  73502. if (scene.activeCamera) {
  73503. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  73504. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  73505. }
  73506. engine.setViewport(scene.activeCamera.viewport);
  73507. }
  73508. scene.resetCachedMaterial();
  73509. };
  73510. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  73511. var minimum = 128;
  73512. var x = renderDimension * scale;
  73513. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  73514. // Ensure we don't exceed the render dimension (while staying POT)
  73515. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  73516. };
  73517. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73518. var _this = this;
  73519. if (!this._texture) {
  73520. return;
  73521. }
  73522. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  73523. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73524. });
  73525. };
  73526. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  73527. var scene = this.getScene();
  73528. if (!scene) {
  73529. return;
  73530. }
  73531. var engine = scene.getEngine();
  73532. if (!this._texture) {
  73533. return;
  73534. }
  73535. // Bind
  73536. if (this._postProcessManager) {
  73537. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  73538. }
  73539. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  73540. if (this._texture) {
  73541. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  73542. }
  73543. }
  73544. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  73545. // Clear
  73546. if (this.onClearObservable.hasObservers()) {
  73547. this.onClearObservable.notifyObservers(engine);
  73548. }
  73549. else {
  73550. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  73551. }
  73552. if (!this._doNotChangeAspectRatio) {
  73553. scene.updateTransformMatrix(true);
  73554. }
  73555. // Render
  73556. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  73557. if (this._postProcessManager) {
  73558. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  73559. }
  73560. else if (useCameraPostProcess) {
  73561. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  73562. }
  73563. if (!this._doNotChangeAspectRatio) {
  73564. scene.updateTransformMatrix(true);
  73565. }
  73566. // Dump ?
  73567. if (dumpForDebug) {
  73568. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  73569. }
  73570. // Unbind
  73571. if (!this.isCube || faceIndex === 5) {
  73572. if (this.isCube) {
  73573. if (faceIndex === 5) {
  73574. engine.generateMipMapsForCubemap(this._texture);
  73575. }
  73576. }
  73577. this.unbindFrameBuffer(engine, faceIndex);
  73578. }
  73579. else {
  73580. this.onAfterRenderObservable.notifyObservers(faceIndex);
  73581. }
  73582. };
  73583. /**
  73584. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  73585. * This allowed control for front to back rendering or reversly depending of the special needs.
  73586. *
  73587. * @param renderingGroupId The rendering group id corresponding to its index
  73588. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  73589. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  73590. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  73591. */
  73592. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  73593. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  73594. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  73595. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  73596. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  73597. };
  73598. /**
  73599. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73600. *
  73601. * @param renderingGroupId The rendering group id corresponding to its index
  73602. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73603. */
  73604. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73605. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73606. this._renderingManager._useSceneAutoClearSetup = false;
  73607. };
  73608. /**
  73609. * Clones the texture.
  73610. * @returns the cloned texture
  73611. */
  73612. RenderTargetTexture.prototype.clone = function () {
  73613. var textureSize = this.getSize();
  73614. 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);
  73615. // Base texture
  73616. newTexture.hasAlpha = this.hasAlpha;
  73617. newTexture.level = this.level;
  73618. // RenderTarget Texture
  73619. newTexture.coordinatesMode = this.coordinatesMode;
  73620. if (this.renderList) {
  73621. newTexture.renderList = this.renderList.slice(0);
  73622. }
  73623. return newTexture;
  73624. };
  73625. /**
  73626. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  73627. * @returns The JSON representation of the texture
  73628. */
  73629. RenderTargetTexture.prototype.serialize = function () {
  73630. if (!this.name) {
  73631. return null;
  73632. }
  73633. var serializationObject = _super.prototype.serialize.call(this);
  73634. serializationObject.renderTargetSize = this.getRenderSize();
  73635. serializationObject.renderList = [];
  73636. if (this.renderList) {
  73637. for (var index = 0; index < this.renderList.length; index++) {
  73638. serializationObject.renderList.push(this.renderList[index].id);
  73639. }
  73640. }
  73641. return serializationObject;
  73642. };
  73643. /**
  73644. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  73645. */
  73646. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  73647. var objBuffer = this.getInternalTexture();
  73648. var scene = this.getScene();
  73649. if (objBuffer && scene) {
  73650. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  73651. }
  73652. };
  73653. /**
  73654. * Dispose the texture and release its associated resources.
  73655. */
  73656. RenderTargetTexture.prototype.dispose = function () {
  73657. if (this._postProcessManager) {
  73658. this._postProcessManager.dispose();
  73659. this._postProcessManager = null;
  73660. }
  73661. this.clearPostProcesses(true);
  73662. if (this._resizeObserver) {
  73663. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  73664. this._resizeObserver = null;
  73665. }
  73666. this.renderList = null;
  73667. // Remove from custom render targets
  73668. var scene = this.getScene();
  73669. if (!scene) {
  73670. return;
  73671. }
  73672. var index = scene.customRenderTargets.indexOf(this);
  73673. if (index >= 0) {
  73674. scene.customRenderTargets.splice(index, 1);
  73675. }
  73676. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  73677. var camera = _a[_i];
  73678. index = camera.customRenderTargets.indexOf(this);
  73679. if (index >= 0) {
  73680. camera.customRenderTargets.splice(index, 1);
  73681. }
  73682. }
  73683. _super.prototype.dispose.call(this);
  73684. };
  73685. /** @hidden */
  73686. RenderTargetTexture.prototype._rebuild = function () {
  73687. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73688. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73689. }
  73690. if (this._postProcessManager) {
  73691. this._postProcessManager._rebuild();
  73692. }
  73693. };
  73694. /**
  73695. * Clear the info related to rendering groups preventing retention point in material dispose.
  73696. */
  73697. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  73698. if (this._renderingManager) {
  73699. this._renderingManager.freeRenderingGroups();
  73700. }
  73701. };
  73702. /**
  73703. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  73704. */
  73705. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  73706. /**
  73707. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  73708. */
  73709. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  73710. /**
  73711. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  73712. * the central point of your effect and can save a lot of performances.
  73713. */
  73714. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  73715. return RenderTargetTexture;
  73716. }(BABYLON.Texture));
  73717. BABYLON.RenderTargetTexture = RenderTargetTexture;
  73718. })(BABYLON || (BABYLON = {}));
  73719. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  73720. var BABYLON;
  73721. (function (BABYLON) {
  73722. /**
  73723. * A multi render target, like a render target provides the ability to render to a texture.
  73724. * Unlike the render target, it can render to several draw buffers in one draw.
  73725. * This is specially interesting in deferred rendering or for any effects requiring more than
  73726. * just one color from a single pass.
  73727. */
  73728. var MultiRenderTarget = /** @class */ (function (_super) {
  73729. __extends(MultiRenderTarget, _super);
  73730. /**
  73731. * Instantiate a new multi render target texture.
  73732. * A multi render target, like a render target provides the ability to render to a texture.
  73733. * Unlike the render target, it can render to several draw buffers in one draw.
  73734. * This is specially interesting in deferred rendering or for any effects requiring more than
  73735. * just one color from a single pass.
  73736. * @param name Define the name of the texture
  73737. * @param size Define the size of the buffers to render to
  73738. * @param count Define the number of target we are rendering into
  73739. * @param scene Define the scene the texture belongs to
  73740. * @param options Define the options used to create the multi render target
  73741. */
  73742. function MultiRenderTarget(name, size, count, scene, options) {
  73743. var _this = this;
  73744. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  73745. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  73746. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  73747. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  73748. _this._engine = scene.getEngine();
  73749. if (!_this.isSupported) {
  73750. _this.dispose();
  73751. return;
  73752. }
  73753. var types = [];
  73754. var samplingModes = [];
  73755. for (var i = 0; i < count; i++) {
  73756. if (options && options.types && options.types[i] !== undefined) {
  73757. types.push(options.types[i]);
  73758. }
  73759. else {
  73760. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73761. }
  73762. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  73763. samplingModes.push(options.samplingModes[i]);
  73764. }
  73765. else {
  73766. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73767. }
  73768. }
  73769. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73770. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  73771. _this._size = size;
  73772. _this._multiRenderTargetOptions = {
  73773. samplingModes: samplingModes,
  73774. generateMipMaps: generateMipMaps,
  73775. generateDepthBuffer: generateDepthBuffer,
  73776. generateStencilBuffer: generateStencilBuffer,
  73777. generateDepthTexture: generateDepthTexture,
  73778. types: types,
  73779. textureCount: count
  73780. };
  73781. _this._createInternalTextures();
  73782. _this._createTextures();
  73783. return _this;
  73784. }
  73785. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  73786. /**
  73787. * Get if draw buffers are currently supported by the used hardware and browser.
  73788. */
  73789. get: function () {
  73790. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  73791. },
  73792. enumerable: true,
  73793. configurable: true
  73794. });
  73795. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  73796. /**
  73797. * Get the list of textures generated by the multi render target.
  73798. */
  73799. get: function () {
  73800. return this._textures;
  73801. },
  73802. enumerable: true,
  73803. configurable: true
  73804. });
  73805. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  73806. /**
  73807. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  73808. */
  73809. get: function () {
  73810. return this._textures[this._textures.length - 1];
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  73816. /**
  73817. * Set the wrapping mode on U of all the textures we are rendering to.
  73818. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73819. */
  73820. set: function (wrap) {
  73821. if (this._textures) {
  73822. for (var i = 0; i < this._textures.length; i++) {
  73823. this._textures[i].wrapU = wrap;
  73824. }
  73825. }
  73826. },
  73827. enumerable: true,
  73828. configurable: true
  73829. });
  73830. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  73831. /**
  73832. * Set the wrapping mode on V of all the textures we are rendering to.
  73833. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73834. */
  73835. set: function (wrap) {
  73836. if (this._textures) {
  73837. for (var i = 0; i < this._textures.length; i++) {
  73838. this._textures[i].wrapV = wrap;
  73839. }
  73840. }
  73841. },
  73842. enumerable: true,
  73843. configurable: true
  73844. });
  73845. /** @hidden */
  73846. MultiRenderTarget.prototype._rebuild = function () {
  73847. this.releaseInternalTextures();
  73848. this._createInternalTextures();
  73849. for (var i = 0; i < this._internalTextures.length; i++) {
  73850. var texture = this._textures[i];
  73851. texture._texture = this._internalTextures[i];
  73852. }
  73853. // Keeps references to frame buffer and stencil/depth buffer
  73854. this._texture = this._internalTextures[0];
  73855. };
  73856. MultiRenderTarget.prototype._createInternalTextures = function () {
  73857. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  73858. };
  73859. MultiRenderTarget.prototype._createTextures = function () {
  73860. this._textures = [];
  73861. for (var i = 0; i < this._internalTextures.length; i++) {
  73862. var texture = new BABYLON.Texture(null, this.getScene());
  73863. texture._texture = this._internalTextures[i];
  73864. this._textures.push(texture);
  73865. }
  73866. // Keeps references to frame buffer and stencil/depth buffer
  73867. this._texture = this._internalTextures[0];
  73868. };
  73869. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  73870. /**
  73871. * Define the number of samples used if MSAA is enabled.
  73872. */
  73873. get: function () {
  73874. return this._samples;
  73875. },
  73876. set: function (value) {
  73877. if (this._samples === value) {
  73878. return;
  73879. }
  73880. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  73881. },
  73882. enumerable: true,
  73883. configurable: true
  73884. });
  73885. /**
  73886. * Resize all the textures in the multi render target.
  73887. * Be carrefull as it will recreate all the data in the new texture.
  73888. * @param size Define the new size
  73889. */
  73890. MultiRenderTarget.prototype.resize = function (size) {
  73891. this.releaseInternalTextures();
  73892. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  73893. this._createInternalTextures();
  73894. };
  73895. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73896. var _this = this;
  73897. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  73898. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73899. });
  73900. };
  73901. /**
  73902. * Dispose the render targets and their associated resources
  73903. */
  73904. MultiRenderTarget.prototype.dispose = function () {
  73905. this.releaseInternalTextures();
  73906. _super.prototype.dispose.call(this);
  73907. };
  73908. /**
  73909. * Release all the underlying texture used as draw buffers.
  73910. */
  73911. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  73912. if (!this._internalTextures) {
  73913. return;
  73914. }
  73915. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  73916. if (this._internalTextures[i] !== undefined) {
  73917. this._internalTextures[i].dispose();
  73918. this._internalTextures.splice(i, 1);
  73919. }
  73920. }
  73921. };
  73922. return MultiRenderTarget;
  73923. }(BABYLON.RenderTargetTexture));
  73924. BABYLON.MultiRenderTarget = MultiRenderTarget;
  73925. })(BABYLON || (BABYLON = {}));
  73926. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  73927. var BABYLON;
  73928. (function (BABYLON) {
  73929. /**
  73930. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73931. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73932. * You can then easily use it as a reflectionTexture on a flat surface.
  73933. * In case the surface is not a plane, please consider relying on reflection probes.
  73934. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73935. */
  73936. var MirrorTexture = /** @class */ (function (_super) {
  73937. __extends(MirrorTexture, _super);
  73938. /**
  73939. * Instantiates a Mirror Texture.
  73940. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73941. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73942. * You can then easily use it as a reflectionTexture on a flat surface.
  73943. * In case the surface is not a plane, please consider relying on reflection probes.
  73944. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73945. * @param name
  73946. * @param size
  73947. * @param scene
  73948. * @param generateMipMaps
  73949. * @param type
  73950. * @param samplingMode
  73951. * @param generateDepthBuffer
  73952. */
  73953. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  73954. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73956. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73957. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  73958. _this.scene = scene;
  73959. /**
  73960. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  73961. * 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.
  73962. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73963. */
  73964. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  73965. _this._transformMatrix = BABYLON.Matrix.Zero();
  73966. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  73967. _this._adaptiveBlurKernel = 0;
  73968. _this._blurKernelX = 0;
  73969. _this._blurKernelY = 0;
  73970. _this._blurRatio = 1.0;
  73971. _this.ignoreCameraViewport = true;
  73972. _this._updateGammaSpace();
  73973. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73974. _this._updateGammaSpace;
  73975. });
  73976. _this.onBeforeRenderObservable.add(function () {
  73977. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  73978. _this._savedViewMatrix = scene.getViewMatrix();
  73979. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  73980. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  73981. scene.clipPlane = _this.mirrorPlane;
  73982. scene.getEngine().cullBackFaces = false;
  73983. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  73984. });
  73985. _this.onAfterRenderObservable.add(function () {
  73986. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  73987. scene.getEngine().cullBackFaces = true;
  73988. scene._mirroredCameraPosition = null;
  73989. delete scene.clipPlane;
  73990. });
  73991. return _this;
  73992. }
  73993. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  73994. get: function () {
  73995. return this._blurRatio;
  73996. },
  73997. /**
  73998. * Define the blur ratio used to blur the reflection if needed.
  73999. */
  74000. set: function (value) {
  74001. if (this._blurRatio === value) {
  74002. return;
  74003. }
  74004. this._blurRatio = value;
  74005. this._preparePostProcesses();
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74011. /**
  74012. * Define the adaptive blur kernel used to blur the reflection if needed.
  74013. * This will autocompute the closest best match for the `blurKernel`
  74014. */
  74015. set: function (value) {
  74016. this._adaptiveBlurKernel = value;
  74017. this._autoComputeBlurKernel();
  74018. },
  74019. enumerable: true,
  74020. configurable: true
  74021. });
  74022. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74023. /**
  74024. * Define the blur kernel used to blur the reflection if needed.
  74025. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74026. */
  74027. set: function (value) {
  74028. this.blurKernelX = value;
  74029. this.blurKernelY = value;
  74030. },
  74031. enumerable: true,
  74032. configurable: true
  74033. });
  74034. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74035. get: function () {
  74036. return this._blurKernelX;
  74037. },
  74038. /**
  74039. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74040. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74041. */
  74042. set: function (value) {
  74043. if (this._blurKernelX === value) {
  74044. return;
  74045. }
  74046. this._blurKernelX = value;
  74047. this._preparePostProcesses();
  74048. },
  74049. enumerable: true,
  74050. configurable: true
  74051. });
  74052. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74053. get: function () {
  74054. return this._blurKernelY;
  74055. },
  74056. /**
  74057. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74058. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74059. */
  74060. set: function (value) {
  74061. if (this._blurKernelY === value) {
  74062. return;
  74063. }
  74064. this._blurKernelY = value;
  74065. this._preparePostProcesses();
  74066. },
  74067. enumerable: true,
  74068. configurable: true
  74069. });
  74070. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74071. var engine = this.getScene().getEngine();
  74072. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74073. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74074. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74075. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74076. };
  74077. MirrorTexture.prototype._onRatioRescale = function () {
  74078. if (this._sizeRatio) {
  74079. this.resize(this._initialSizeParameter);
  74080. if (!this._adaptiveBlurKernel) {
  74081. this._preparePostProcesses();
  74082. }
  74083. }
  74084. if (this._adaptiveBlurKernel) {
  74085. this._autoComputeBlurKernel();
  74086. }
  74087. };
  74088. MirrorTexture.prototype._updateGammaSpace = function () {
  74089. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74090. };
  74091. MirrorTexture.prototype._preparePostProcesses = function () {
  74092. this.clearPostProcesses(true);
  74093. if (this._blurKernelX && this._blurKernelY) {
  74094. var engine = this.getScene().getEngine();
  74095. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74096. 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);
  74097. this._blurX.autoClear = false;
  74098. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74099. this._blurX.inputTexture = this._texture;
  74100. }
  74101. else {
  74102. this._blurX.alwaysForcePOT = true;
  74103. }
  74104. 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);
  74105. this._blurY.autoClear = false;
  74106. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74107. this.addPostProcess(this._blurX);
  74108. this.addPostProcess(this._blurY);
  74109. }
  74110. else {
  74111. if (this._blurY) {
  74112. this.removePostProcess(this._blurY);
  74113. this._blurY.dispose();
  74114. this._blurY = null;
  74115. }
  74116. if (this._blurX) {
  74117. this.removePostProcess(this._blurX);
  74118. this._blurX.dispose();
  74119. this._blurX = null;
  74120. }
  74121. }
  74122. };
  74123. /**
  74124. * Clone the mirror texture.
  74125. * @returns the cloned texture
  74126. */
  74127. MirrorTexture.prototype.clone = function () {
  74128. var scene = this.getScene();
  74129. if (!scene) {
  74130. return this;
  74131. }
  74132. var textureSize = this.getSize();
  74133. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74134. // Base texture
  74135. newTexture.hasAlpha = this.hasAlpha;
  74136. newTexture.level = this.level;
  74137. // Mirror Texture
  74138. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74139. if (this.renderList) {
  74140. newTexture.renderList = this.renderList.slice(0);
  74141. }
  74142. return newTexture;
  74143. };
  74144. /**
  74145. * Serialize the texture to a JSON representation you could use in Parse later on
  74146. * @returns the serialized JSON representation
  74147. */
  74148. MirrorTexture.prototype.serialize = function () {
  74149. if (!this.name) {
  74150. return null;
  74151. }
  74152. var serializationObject = _super.prototype.serialize.call(this);
  74153. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74154. return serializationObject;
  74155. };
  74156. /**
  74157. * Dispose the texture and release its associated resources.
  74158. */
  74159. MirrorTexture.prototype.dispose = function () {
  74160. _super.prototype.dispose.call(this);
  74161. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74162. };
  74163. return MirrorTexture;
  74164. }(BABYLON.RenderTargetTexture));
  74165. BABYLON.MirrorTexture = MirrorTexture;
  74166. })(BABYLON || (BABYLON = {}));
  74167. //# sourceMappingURL=babylon.mirrorTexture.js.map
  74168. var BABYLON;
  74169. (function (BABYLON) {
  74170. /**
  74171. * Creates a refraction texture used by refraction channel of the standard material.
  74172. * It is like a mirror but to see through a material.
  74173. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74174. */
  74175. var RefractionTexture = /** @class */ (function (_super) {
  74176. __extends(RefractionTexture, _super);
  74177. /**
  74178. * Creates a refraction texture used by refraction channel of the standard material.
  74179. * It is like a mirror but to see through a material.
  74180. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74181. * @param name Define the texture name
  74182. * @param size Define the size of the underlying texture
  74183. * @param scene Define the scene the refraction belongs to
  74184. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74185. */
  74186. function RefractionTexture(name, size, scene, generateMipMaps) {
  74187. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74188. /**
  74189. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74190. * 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.
  74191. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74192. */
  74193. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74194. /**
  74195. * Define how deep under the surface we should see.
  74196. */
  74197. _this.depth = 2.0;
  74198. _this.onBeforeRenderObservable.add(function () {
  74199. scene.clipPlane = _this.refractionPlane;
  74200. });
  74201. _this.onAfterRenderObservable.add(function () {
  74202. delete scene.clipPlane;
  74203. });
  74204. return _this;
  74205. }
  74206. /**
  74207. * Clone the refraction texture.
  74208. * @returns the cloned texture
  74209. */
  74210. RefractionTexture.prototype.clone = function () {
  74211. var scene = this.getScene();
  74212. if (!scene) {
  74213. return this;
  74214. }
  74215. var textureSize = this.getSize();
  74216. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74217. // Base texture
  74218. newTexture.hasAlpha = this.hasAlpha;
  74219. newTexture.level = this.level;
  74220. // Refraction Texture
  74221. newTexture.refractionPlane = this.refractionPlane.clone();
  74222. if (this.renderList) {
  74223. newTexture.renderList = this.renderList.slice(0);
  74224. }
  74225. newTexture.depth = this.depth;
  74226. return newTexture;
  74227. };
  74228. /**
  74229. * Serialize the texture to a JSON representation you could use in Parse later on
  74230. * @returns the serialized JSON representation
  74231. */
  74232. RefractionTexture.prototype.serialize = function () {
  74233. if (!this.name) {
  74234. return null;
  74235. }
  74236. var serializationObject = _super.prototype.serialize.call(this);
  74237. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74238. serializationObject.depth = this.depth;
  74239. return serializationObject;
  74240. };
  74241. return RefractionTexture;
  74242. }(BABYLON.RenderTargetTexture));
  74243. BABYLON.RefractionTexture = RefractionTexture;
  74244. })(BABYLON || (BABYLON = {}));
  74245. //# sourceMappingURL=babylon.refractionTexture.js.map
  74246. var BABYLON;
  74247. (function (BABYLON) {
  74248. /**
  74249. * A class extending Texture allowing drawing on a texture
  74250. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74251. */
  74252. var DynamicTexture = /** @class */ (function (_super) {
  74253. __extends(DynamicTexture, _super);
  74254. /**
  74255. * Creates a DynamicTexture
  74256. * @param name defines the name of the texture
  74257. * @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
  74258. * @param scene defines the scene where you want the texture
  74259. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74260. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74261. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74262. */
  74263. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74264. if (scene === void 0) { scene = null; }
  74265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74266. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74267. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74268. _this.name = name;
  74269. _this._engine = _this.getScene().getEngine();
  74270. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74271. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74272. _this._generateMipMaps = generateMipMaps;
  74273. if (options.getContext) {
  74274. _this._canvas = options;
  74275. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74276. }
  74277. else {
  74278. _this._canvas = document.createElement("canvas");
  74279. if (options.width || options.width === 0) {
  74280. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74281. }
  74282. else {
  74283. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74284. }
  74285. }
  74286. var textureSize = _this.getSize();
  74287. _this._canvas.width = textureSize.width;
  74288. _this._canvas.height = textureSize.height;
  74289. _this._context = _this._canvas.getContext("2d");
  74290. return _this;
  74291. }
  74292. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74293. /**
  74294. * Gets the current state of canRescale
  74295. */
  74296. get: function () {
  74297. return true;
  74298. },
  74299. enumerable: true,
  74300. configurable: true
  74301. });
  74302. DynamicTexture.prototype._recreate = function (textureSize) {
  74303. this._canvas.width = textureSize.width;
  74304. this._canvas.height = textureSize.height;
  74305. this.releaseInternalTexture();
  74306. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74307. };
  74308. /**
  74309. * Scales the texture
  74310. * @param ratio the scale factor to apply to both width and height
  74311. */
  74312. DynamicTexture.prototype.scale = function (ratio) {
  74313. var textureSize = this.getSize();
  74314. textureSize.width *= ratio;
  74315. textureSize.height *= ratio;
  74316. this._recreate(textureSize);
  74317. };
  74318. /**
  74319. * Resizes the texture
  74320. * @param width the new width
  74321. * @param height the new height
  74322. */
  74323. DynamicTexture.prototype.scaleTo = function (width, height) {
  74324. var textureSize = this.getSize();
  74325. textureSize.width = width;
  74326. textureSize.height = height;
  74327. this._recreate(textureSize);
  74328. };
  74329. /**
  74330. * Gets the context of the canvas used by the texture
  74331. * @returns the canvas context of the dynamic texture
  74332. */
  74333. DynamicTexture.prototype.getContext = function () {
  74334. return this._context;
  74335. };
  74336. /**
  74337. * Clears the texture
  74338. */
  74339. DynamicTexture.prototype.clear = function () {
  74340. var size = this.getSize();
  74341. this._context.fillRect(0, 0, size.width, size.height);
  74342. };
  74343. /**
  74344. * Updates the texture
  74345. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74346. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74347. */
  74348. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74349. if (premulAlpha === void 0) { premulAlpha = false; }
  74350. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74351. };
  74352. /**
  74353. * Draws text onto the texture
  74354. * @param text defines the text to be drawn
  74355. * @param x defines the placement of the text from the left
  74356. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74357. * @param font defines the font to be used with font-style, font-size, font-name
  74358. * @param color defines the color used for the text
  74359. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74360. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74361. * @param update defines whether texture is immediately update (default is true)
  74362. */
  74363. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74364. if (update === void 0) { update = true; }
  74365. var size = this.getSize();
  74366. if (clearColor) {
  74367. this._context.fillStyle = clearColor;
  74368. this._context.fillRect(0, 0, size.width, size.height);
  74369. }
  74370. this._context.font = font;
  74371. if (x === null || x === undefined) {
  74372. var textSize = this._context.measureText(text);
  74373. x = (size.width - textSize.width) / 2;
  74374. }
  74375. if (y === null || y === undefined) {
  74376. var fontSize = parseInt((font.replace(/\D/g, '')));
  74377. y = (size.height / 2) + (fontSize / 3.65);
  74378. }
  74379. this._context.fillStyle = color;
  74380. this._context.fillText(text, x, y);
  74381. if (update) {
  74382. this.update(invertY);
  74383. }
  74384. };
  74385. /**
  74386. * Clones the texture
  74387. * @returns the clone of the texture.
  74388. */
  74389. DynamicTexture.prototype.clone = function () {
  74390. var scene = this.getScene();
  74391. if (!scene) {
  74392. return this;
  74393. }
  74394. var textureSize = this.getSize();
  74395. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74396. // Base texture
  74397. newTexture.hasAlpha = this.hasAlpha;
  74398. newTexture.level = this.level;
  74399. // Dynamic Texture
  74400. newTexture.wrapU = this.wrapU;
  74401. newTexture.wrapV = this.wrapV;
  74402. return newTexture;
  74403. };
  74404. /**
  74405. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74406. * @returns a serialized dynamic texture object
  74407. */
  74408. DynamicTexture.prototype.serialize = function () {
  74409. var scene = this.getScene();
  74410. if (scene && !scene.isReady()) {
  74411. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74412. }
  74413. var serializationObject = _super.prototype.serialize.call(this);
  74414. serializationObject.base64String = this._canvas.toDataURL();
  74415. serializationObject.invertY = this._invertY;
  74416. serializationObject.samplingMode = this.samplingMode;
  74417. return serializationObject;
  74418. };
  74419. /** @hidden */
  74420. DynamicTexture.prototype._rebuild = function () {
  74421. this.update();
  74422. };
  74423. return DynamicTexture;
  74424. }(BABYLON.Texture));
  74425. BABYLON.DynamicTexture = DynamicTexture;
  74426. })(BABYLON || (BABYLON = {}));
  74427. //# sourceMappingURL=babylon.dynamicTexture.js.map
  74428. var BABYLON;
  74429. (function (BABYLON) {
  74430. /**
  74431. * If you want to display a video in your scene, this is the special texture for that.
  74432. * This special texture works similar to other textures, with the exception of a few parameters.
  74433. * @see https://doc.babylonjs.com/how_to/video_texture
  74434. */
  74435. var VideoTexture = /** @class */ (function (_super) {
  74436. __extends(VideoTexture, _super);
  74437. /**
  74438. * Creates a video texture.
  74439. * If you want to display a video in your scene, this is the special texture for that.
  74440. * This special texture works similar to other textures, with the exception of a few parameters.
  74441. * @see https://doc.babylonjs.com/how_to/video_texture
  74442. * @param name optional name, will detect from video source, if not defined
  74443. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74444. * @param scene is obviously the current scene.
  74445. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74446. * @param invertY is false by default but can be used to invert video on Y axis
  74447. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74448. * @param settings allows finer control over video usage
  74449. */
  74450. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74451. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74452. if (invertY === void 0) { invertY = false; }
  74453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74454. if (settings === void 0) { settings = {
  74455. autoPlay: true,
  74456. loop: true,
  74457. autoUpdateTexture: true,
  74458. }; }
  74459. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74460. _this._onUserActionRequestedObservable = null;
  74461. _this._stillImageCaptured = false;
  74462. _this._poster = false;
  74463. _this._createInternalTexture = function () {
  74464. if (_this._texture != null) {
  74465. if (_this._poster) {
  74466. _this._texture.dispose();
  74467. _this._poster = false;
  74468. }
  74469. else {
  74470. return;
  74471. }
  74472. }
  74473. if (!_this._engine.needPOTTextures ||
  74474. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74475. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74476. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74477. }
  74478. else {
  74479. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74480. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74481. _this._generateMipMaps = false;
  74482. }
  74483. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74484. if (!_this.video.autoplay) {
  74485. var oldHandler_1 = _this.video.onplaying;
  74486. var error_1 = false;
  74487. _this.video.onplaying = function () {
  74488. _this.video.onplaying = oldHandler_1;
  74489. _this._texture.isReady = true;
  74490. _this._updateInternalTexture();
  74491. if (!error_1) {
  74492. _this.video.pause();
  74493. }
  74494. if (_this.onLoadObservable.hasObservers()) {
  74495. _this.onLoadObservable.notifyObservers(_this);
  74496. }
  74497. };
  74498. var playing = _this.video.play();
  74499. if (playing) {
  74500. playing.then(function () {
  74501. // Everything is good.
  74502. })
  74503. .catch(function () {
  74504. error_1 = true;
  74505. // On Chrome for instance, new policies might prevent playing without user interaction.
  74506. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  74507. _this._onUserActionRequestedObservable.notifyObservers(_this);
  74508. }
  74509. });
  74510. }
  74511. else {
  74512. _this.video.onplaying = oldHandler_1;
  74513. _this._texture.isReady = true;
  74514. _this._updateInternalTexture();
  74515. if (_this.onLoadObservable.hasObservers()) {
  74516. _this.onLoadObservable.notifyObservers(_this);
  74517. }
  74518. }
  74519. }
  74520. else {
  74521. _this._texture.isReady = true;
  74522. _this._updateInternalTexture();
  74523. if (_this.onLoadObservable.hasObservers()) {
  74524. _this.onLoadObservable.notifyObservers(_this);
  74525. }
  74526. }
  74527. };
  74528. _this.reset = function () {
  74529. if (_this._texture == null) {
  74530. return;
  74531. }
  74532. if (!_this._poster) {
  74533. _this._texture.dispose();
  74534. _this._texture = null;
  74535. }
  74536. };
  74537. _this._updateInternalTexture = function (e) {
  74538. if (_this._texture == null || !_this._texture.isReady) {
  74539. return;
  74540. }
  74541. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  74542. return;
  74543. }
  74544. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  74545. };
  74546. _this._engine = _this.getScene().getEngine();
  74547. _this._generateMipMaps = generateMipMaps;
  74548. _this._samplingMode = samplingMode;
  74549. _this.autoUpdateTexture = settings.autoUpdateTexture;
  74550. _this.name = name || _this._getName(src);
  74551. _this.video = _this._getVideo(src);
  74552. if (settings.poster) {
  74553. _this.video.poster = settings.poster;
  74554. }
  74555. if (settings.autoPlay !== undefined) {
  74556. _this.video.autoplay = settings.autoPlay;
  74557. }
  74558. if (settings.loop !== undefined) {
  74559. _this.video.loop = settings.loop;
  74560. }
  74561. _this.video.setAttribute("playsinline", "");
  74562. _this.video.addEventListener("canplay", _this._createInternalTexture);
  74563. _this.video.addEventListener("paused", _this._updateInternalTexture);
  74564. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  74565. _this.video.addEventListener("emptied", _this.reset);
  74566. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  74567. _this._createInternalTexture();
  74568. }
  74569. if (settings.poster) {
  74570. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  74571. _this._poster = true;
  74572. }
  74573. return _this;
  74574. }
  74575. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  74576. /**
  74577. * Event triggerd when a dom action is required by the user to play the video.
  74578. * This happens due to recent changes in browser policies preventing video to auto start.
  74579. */
  74580. get: function () {
  74581. if (!this._onUserActionRequestedObservable) {
  74582. this._onUserActionRequestedObservable = new BABYLON.Observable();
  74583. }
  74584. return this._onUserActionRequestedObservable;
  74585. },
  74586. enumerable: true,
  74587. configurable: true
  74588. });
  74589. VideoTexture.prototype._getName = function (src) {
  74590. if (src instanceof HTMLVideoElement) {
  74591. return src.currentSrc;
  74592. }
  74593. if (typeof src === "object") {
  74594. return src.toString();
  74595. }
  74596. return src;
  74597. };
  74598. VideoTexture.prototype._getVideo = function (src) {
  74599. if (src instanceof HTMLVideoElement) {
  74600. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  74601. return src;
  74602. }
  74603. var video = document.createElement("video");
  74604. if (typeof src === "string") {
  74605. BABYLON.Tools.SetCorsBehavior(src, video);
  74606. video.src = src;
  74607. }
  74608. else {
  74609. BABYLON.Tools.SetCorsBehavior(src[0], video);
  74610. src.forEach(function (url) {
  74611. var source = document.createElement("source");
  74612. source.src = url;
  74613. video.appendChild(source);
  74614. });
  74615. }
  74616. return video;
  74617. };
  74618. /**
  74619. * @hidden Internal method to initiate `update`.
  74620. */
  74621. VideoTexture.prototype._rebuild = function () {
  74622. this.update();
  74623. };
  74624. /**
  74625. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  74626. */
  74627. VideoTexture.prototype.update = function () {
  74628. if (!this.autoUpdateTexture) {
  74629. // Expecting user to call `updateTexture` manually
  74630. return;
  74631. }
  74632. this.updateTexture(true);
  74633. };
  74634. /**
  74635. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  74636. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  74637. */
  74638. VideoTexture.prototype.updateTexture = function (isVisible) {
  74639. if (!isVisible) {
  74640. return;
  74641. }
  74642. if (this.video.paused && this._stillImageCaptured) {
  74643. return;
  74644. }
  74645. this._stillImageCaptured = true;
  74646. this._updateInternalTexture();
  74647. };
  74648. /**
  74649. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  74650. * @param url New url.
  74651. */
  74652. VideoTexture.prototype.updateURL = function (url) {
  74653. this.video.src = url;
  74654. };
  74655. /**
  74656. * Dispose the texture and release its associated resources.
  74657. */
  74658. VideoTexture.prototype.dispose = function () {
  74659. _super.prototype.dispose.call(this);
  74660. if (this._onUserActionRequestedObservable) {
  74661. this._onUserActionRequestedObservable.clear();
  74662. this._onUserActionRequestedObservable = null;
  74663. }
  74664. this.video.removeEventListener("canplay", this._createInternalTexture);
  74665. this.video.removeEventListener("paused", this._updateInternalTexture);
  74666. this.video.removeEventListener("seeked", this._updateInternalTexture);
  74667. this.video.removeEventListener("emptied", this.reset);
  74668. this.video.pause();
  74669. };
  74670. /**
  74671. * Creates a video texture straight from your WebCam video feed.
  74672. * @param scene Define the scene the texture should be created in
  74673. * @param onReady Define a callback to triggered once the texture will be ready
  74674. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  74675. */
  74676. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  74677. var video = document.createElement("video");
  74678. video.setAttribute('autoplay', '');
  74679. video.setAttribute('muted', '');
  74680. video.setAttribute('playsinline', '');
  74681. var constraintsDeviceId;
  74682. if (constraints && constraints.deviceId) {
  74683. constraintsDeviceId = {
  74684. exact: constraints.deviceId,
  74685. };
  74686. }
  74687. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  74688. if (navigator.mediaDevices) {
  74689. navigator.mediaDevices.getUserMedia({ video: constraints })
  74690. .then(function (stream) {
  74691. if (video.mozSrcObject !== undefined) {
  74692. // hack for Firefox < 19
  74693. video.mozSrcObject = stream;
  74694. }
  74695. else {
  74696. video.srcObject = stream;
  74697. }
  74698. var onPlaying = function () {
  74699. if (onReady) {
  74700. onReady(new VideoTexture("video", video, scene, true, true));
  74701. }
  74702. video.removeEventListener("playing", onPlaying);
  74703. };
  74704. video.addEventListener("playing", onPlaying);
  74705. video.play();
  74706. })
  74707. .catch(function (err) {
  74708. BABYLON.Tools.Error(err.name);
  74709. });
  74710. }
  74711. else {
  74712. navigator.getUserMedia =
  74713. navigator.getUserMedia ||
  74714. navigator.webkitGetUserMedia ||
  74715. navigator.mozGetUserMedia ||
  74716. navigator.msGetUserMedia;
  74717. if (navigator.getUserMedia) {
  74718. navigator.getUserMedia({
  74719. video: {
  74720. deviceId: constraintsDeviceId,
  74721. width: {
  74722. min: (constraints && constraints.minWidth) || 256,
  74723. max: (constraints && constraints.maxWidth) || 640,
  74724. },
  74725. height: {
  74726. min: (constraints && constraints.minHeight) || 256,
  74727. max: (constraints && constraints.maxHeight) || 480,
  74728. },
  74729. },
  74730. }, function (stream) {
  74731. if (video.mozSrcObject !== undefined) {
  74732. // hack for Firefox < 19
  74733. video.mozSrcObject = stream;
  74734. }
  74735. else {
  74736. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  74737. }
  74738. video.play();
  74739. if (onReady) {
  74740. onReady(new VideoTexture("video", video, scene, true, true));
  74741. }
  74742. }, function (e) {
  74743. BABYLON.Tools.Error(e.name);
  74744. });
  74745. }
  74746. }
  74747. };
  74748. return VideoTexture;
  74749. }(BABYLON.Texture));
  74750. BABYLON.VideoTexture = VideoTexture;
  74751. })(BABYLON || (BABYLON = {}));
  74752. //# sourceMappingURL=babylon.videoTexture.js.map
  74753. var BABYLON;
  74754. (function (BABYLON) {
  74755. /**
  74756. * Raw texture can help creating a texture directly from an array of data.
  74757. * This can be super useful if you either get the data from an uncompressed source or
  74758. * if you wish to create your texture pixel by pixel.
  74759. */
  74760. var RawTexture = /** @class */ (function (_super) {
  74761. __extends(RawTexture, _super);
  74762. /**
  74763. * Instantiates a new RawTexture.
  74764. * Raw texture can help creating a texture directly from an array of data.
  74765. * This can be super useful if you either get the data from an uncompressed source or
  74766. * if you wish to create your texture pixel by pixel.
  74767. * @param data define the array of data to use to create the texture
  74768. * @param width define the width of the texture
  74769. * @param height define the height of the texture
  74770. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74771. * @param scene define the scene the texture belongs to
  74772. * @param generateMipMaps define whether mip maps should be generated or not
  74773. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74774. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74775. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74776. */
  74777. function RawTexture(data, width, height,
  74778. /**
  74779. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74780. */
  74781. format, scene, generateMipMaps, invertY, samplingMode, type) {
  74782. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74783. if (invertY === void 0) { invertY = false; }
  74784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74785. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74786. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74787. _this.format = format;
  74788. _this._engine = scene.getEngine();
  74789. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  74790. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74791. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74792. return _this;
  74793. }
  74794. /**
  74795. * Updates the texture underlying data.
  74796. * @param data Define the new data of the texture
  74797. */
  74798. RawTexture.prototype.update = function (data) {
  74799. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74800. };
  74801. /**
  74802. * Creates a luminance texture from some data.
  74803. * @param data Define the texture data
  74804. * @param width Define the width of the texture
  74805. * @param height Define the height of the texture
  74806. * @param scene Define the scene the texture belongs to
  74807. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74808. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74809. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74810. * @returns the luminance texture
  74811. */
  74812. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74813. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74814. if (invertY === void 0) { invertY = false; }
  74815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74816. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  74817. };
  74818. /**
  74819. * Creates a luminance alpha texture from some data.
  74820. * @param data Define the texture data
  74821. * @param width Define the width of the texture
  74822. * @param height Define the height of the texture
  74823. * @param scene Define the scene the texture belongs to
  74824. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74825. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74826. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74827. * @returns the luminance alpha texture
  74828. */
  74829. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74830. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74831. if (invertY === void 0) { invertY = false; }
  74832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74833. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74834. };
  74835. /**
  74836. * Creates an alpha texture from some data.
  74837. * @param data Define the texture data
  74838. * @param width Define the width of the texture
  74839. * @param height Define the height of the texture
  74840. * @param scene Define the scene the texture belongs to
  74841. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74842. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74843. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74844. * @returns the alpha texture
  74845. */
  74846. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74848. if (invertY === void 0) { invertY = false; }
  74849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74850. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74851. };
  74852. /**
  74853. * Creates a RGB texture from some data.
  74854. * @param data Define the texture data
  74855. * @param width Define the width of the texture
  74856. * @param height Define the height of the texture
  74857. * @param scene Define the scene the texture belongs to
  74858. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74859. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74860. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74861. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74862. * @returns the RGB alpha texture
  74863. */
  74864. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74865. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74866. if (invertY === void 0) { invertY = false; }
  74867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74868. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74869. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  74870. };
  74871. /**
  74872. * Creates a RGBA texture from some data.
  74873. * @param data Define the texture data
  74874. * @param width Define the width of the texture
  74875. * @param height Define the height of the texture
  74876. * @param scene Define the scene the texture belongs to
  74877. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74878. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74879. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74880. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74881. * @returns the RGBA texture
  74882. */
  74883. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74884. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74885. if (invertY === void 0) { invertY = false; }
  74886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74887. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74888. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  74889. };
  74890. /**
  74891. * Creates a R texture from some data.
  74892. * @param data Define the texture data
  74893. * @param width Define the width of the texture
  74894. * @param height Define the height of the texture
  74895. * @param scene Define the scene the texture belongs to
  74896. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74897. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74898. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74899. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74900. * @returns the R texture
  74901. */
  74902. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74903. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74904. if (invertY === void 0) { invertY = false; }
  74905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74906. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74907. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  74908. };
  74909. return RawTexture;
  74910. }(BABYLON.Texture));
  74911. BABYLON.RawTexture = RawTexture;
  74912. })(BABYLON || (BABYLON = {}));
  74913. //# sourceMappingURL=babylon.rawTexture.js.map
  74914. var BABYLON;
  74915. (function (BABYLON) {
  74916. /**
  74917. * Class used to store 3D textures containing user data
  74918. */
  74919. var RawTexture3D = /** @class */ (function (_super) {
  74920. __extends(RawTexture3D, _super);
  74921. /**
  74922. * Create a new RawTexture3D
  74923. * @param data defines the data of the texture
  74924. * @param width defines the width of the texture
  74925. * @param height defines the height of the texture
  74926. * @param depth defines the depth of the texture
  74927. * @param format defines the texture format to use
  74928. * @param scene defines the hosting scene
  74929. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  74930. * @param invertY defines if texture must be stored with Y axis inverted
  74931. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  74932. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  74933. */
  74934. function RawTexture3D(data, width, height, depth,
  74935. /** Gets or sets the texture format to use */
  74936. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  74937. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74938. if (invertY === void 0) { invertY = false; }
  74939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74941. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74942. _this.format = format;
  74943. _this._engine = scene.getEngine();
  74944. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  74945. _this.is3D = true;
  74946. return _this;
  74947. }
  74948. /**
  74949. * Update the texture with new data
  74950. * @param data defines the data to store in the texture
  74951. */
  74952. RawTexture3D.prototype.update = function (data) {
  74953. if (!this._texture) {
  74954. return;
  74955. }
  74956. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74957. };
  74958. return RawTexture3D;
  74959. }(BABYLON.Texture));
  74960. BABYLON.RawTexture3D = RawTexture3D;
  74961. })(BABYLON || (BABYLON = {}));
  74962. //# sourceMappingURL=babylon.rawTexture3D.js.map
  74963. var BABYLON;
  74964. (function (BABYLON) {
  74965. /**
  74966. * PostProcessManager is used to manage one or more post processes or post process pipelines
  74967. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74968. */
  74969. var PostProcessManager = /** @class */ (function () {
  74970. /**
  74971. * Creates a new instance PostProcess
  74972. * @param scene The scene that the post process is associated with.
  74973. */
  74974. function PostProcessManager(scene) {
  74975. this._vertexBuffers = {};
  74976. this._scene = scene;
  74977. }
  74978. PostProcessManager.prototype._prepareBuffers = function () {
  74979. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  74980. return;
  74981. }
  74982. // VBO
  74983. var vertices = [];
  74984. vertices.push(1, 1);
  74985. vertices.push(-1, 1);
  74986. vertices.push(-1, -1);
  74987. vertices.push(1, -1);
  74988. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74989. this._buildIndexBuffer();
  74990. };
  74991. PostProcessManager.prototype._buildIndexBuffer = function () {
  74992. // Indices
  74993. var indices = [];
  74994. indices.push(0);
  74995. indices.push(1);
  74996. indices.push(2);
  74997. indices.push(0);
  74998. indices.push(2);
  74999. indices.push(3);
  75000. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75001. };
  75002. /**
  75003. * Rebuilds the vertex buffers of the manager.
  75004. * @hidden
  75005. */
  75006. PostProcessManager.prototype._rebuild = function () {
  75007. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75008. if (!vb) {
  75009. return;
  75010. }
  75011. vb._rebuild();
  75012. this._buildIndexBuffer();
  75013. };
  75014. // Methods
  75015. /**
  75016. * Prepares a frame to be run through a post process.
  75017. * @param sourceTexture The input texture to the post procesess. (default: null)
  75018. * @param postProcesses An array of post processes to be run. (default: null)
  75019. * @returns True if the post processes were able to be run.
  75020. * @hidden
  75021. */
  75022. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75023. if (sourceTexture === void 0) { sourceTexture = null; }
  75024. if (postProcesses === void 0) { postProcesses = null; }
  75025. var camera = this._scene.activeCamera;
  75026. if (!camera) {
  75027. return false;
  75028. }
  75029. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75030. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75031. return false;
  75032. }
  75033. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75034. return true;
  75035. };
  75036. /**
  75037. * Manually render a set of post processes to a texture.
  75038. * @param postProcesses An array of post processes to be run.
  75039. * @param targetTexture The target texture to render to.
  75040. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75041. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75042. * @param lodLevel defines which lod of the texture to render to
  75043. */
  75044. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75045. if (targetTexture === void 0) { targetTexture = null; }
  75046. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75047. if (faceIndex === void 0) { faceIndex = 0; }
  75048. if (lodLevel === void 0) { lodLevel = 0; }
  75049. var engine = this._scene.getEngine();
  75050. for (var index = 0; index < postProcesses.length; index++) {
  75051. if (index < postProcesses.length - 1) {
  75052. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75053. }
  75054. else {
  75055. if (targetTexture) {
  75056. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75057. }
  75058. else {
  75059. engine.restoreDefaultFramebuffer();
  75060. }
  75061. }
  75062. var pp = postProcesses[index];
  75063. var effect = pp.apply();
  75064. if (effect) {
  75065. pp.onBeforeRenderObservable.notifyObservers(effect);
  75066. // VBOs
  75067. this._prepareBuffers();
  75068. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75069. // Draw order
  75070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75071. pp.onAfterRenderObservable.notifyObservers(effect);
  75072. }
  75073. }
  75074. // Restore depth buffer
  75075. engine.setDepthBuffer(true);
  75076. engine.setDepthWrite(true);
  75077. };
  75078. /**
  75079. * Finalize the result of the output of the postprocesses.
  75080. * @param doNotPresent If true the result will not be displayed to the screen.
  75081. * @param targetTexture The target texture to render to.
  75082. * @param faceIndex The index of the face to bind the target texture to.
  75083. * @param postProcesses The array of post processes to render.
  75084. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75085. * @hidden
  75086. */
  75087. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75088. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75089. var camera = this._scene.activeCamera;
  75090. if (!camera) {
  75091. return;
  75092. }
  75093. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75094. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75095. return;
  75096. }
  75097. var engine = this._scene.getEngine();
  75098. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75099. var pp = postProcesses[index];
  75100. if (index < len - 1) {
  75101. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75102. }
  75103. else {
  75104. if (targetTexture) {
  75105. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75106. pp._outputTexture = targetTexture;
  75107. }
  75108. else {
  75109. engine.restoreDefaultFramebuffer();
  75110. pp._outputTexture = null;
  75111. }
  75112. }
  75113. if (doNotPresent) {
  75114. break;
  75115. }
  75116. var effect = pp.apply();
  75117. if (effect) {
  75118. pp.onBeforeRenderObservable.notifyObservers(effect);
  75119. // VBOs
  75120. this._prepareBuffers();
  75121. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75122. // Draw order
  75123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75124. pp.onAfterRenderObservable.notifyObservers(effect);
  75125. }
  75126. }
  75127. // Restore states
  75128. engine.setDepthBuffer(true);
  75129. engine.setDepthWrite(true);
  75130. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75131. };
  75132. /**
  75133. * Disposes of the post process manager.
  75134. */
  75135. PostProcessManager.prototype.dispose = function () {
  75136. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75137. if (buffer) {
  75138. buffer.dispose();
  75139. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75140. }
  75141. if (this._indexBuffer) {
  75142. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75143. this._indexBuffer = null;
  75144. }
  75145. };
  75146. return PostProcessManager;
  75147. }());
  75148. BABYLON.PostProcessManager = PostProcessManager;
  75149. })(BABYLON || (BABYLON = {}));
  75150. //# sourceMappingURL=babylon.postProcessManager.js.map
  75151. var BABYLON;
  75152. (function (BABYLON) {
  75153. /**
  75154. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75155. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75156. */
  75157. var PostProcess = /** @class */ (function () {
  75158. /**
  75159. * Creates a new instance PostProcess
  75160. * @param name The name of the PostProcess.
  75161. * @param fragmentUrl The url of the fragment shader to be used.
  75162. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75163. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75164. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75165. * @param camera The camera to apply the render pass to.
  75166. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75167. * @param engine The engine which the post process will be applied. (default: current engine)
  75168. * @param reusable If the post process can be reused on the same frame. (default: false)
  75169. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75170. * @param textureType Type of textures used when performing the post process. (default: 0)
  75171. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75172. * @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
  75173. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75174. */
  75175. function PostProcess(
  75176. /** Name of the PostProcess. */
  75177. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75179. if (defines === void 0) { defines = null; }
  75180. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75181. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75182. if (blockCompilation === void 0) { blockCompilation = false; }
  75183. this.name = name;
  75184. /**
  75185. * Width of the texture to apply the post process on
  75186. */
  75187. this.width = -1;
  75188. /**
  75189. * Height of the texture to apply the post process on
  75190. */
  75191. this.height = -1;
  75192. /**
  75193. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75194. * @hidden
  75195. */
  75196. this._outputTexture = null;
  75197. /**
  75198. * If the buffer needs to be cleared before applying the post process. (default: true)
  75199. * Should be set to false if shader will overwrite all previous pixels.
  75200. */
  75201. this.autoClear = true;
  75202. /**
  75203. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75204. */
  75205. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75206. /**
  75207. * Animations to be used for the post processing
  75208. */
  75209. this.animations = new Array();
  75210. /**
  75211. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75212. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75213. */
  75214. this.enablePixelPerfectMode = false;
  75215. /**
  75216. * Force the postprocess to be applied without taking in account viewport
  75217. */
  75218. this.forceFullscreenViewport = true;
  75219. /**
  75220. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75221. *
  75222. * | Value | Type | Description |
  75223. * | ----- | ----------------------------------- | ----------- |
  75224. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75225. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75226. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75227. *
  75228. */
  75229. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75230. /**
  75231. * Force textures to be a power of two (default: false)
  75232. */
  75233. this.alwaysForcePOT = false;
  75234. this._samples = 1;
  75235. /**
  75236. * Modify the scale of the post process to be the same as the viewport (default: false)
  75237. */
  75238. this.adaptScaleToCurrentViewport = false;
  75239. this._reusable = false;
  75240. /**
  75241. * Smart array of input and output textures for the post process.
  75242. * @hidden
  75243. */
  75244. this._textures = new BABYLON.SmartArray(2);
  75245. /**
  75246. * The index in _textures that corresponds to the output texture.
  75247. * @hidden
  75248. */
  75249. this._currentRenderTextureInd = 0;
  75250. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75251. this._texelSize = BABYLON.Vector2.Zero();
  75252. // Events
  75253. /**
  75254. * An event triggered when the postprocess is activated.
  75255. */
  75256. this.onActivateObservable = new BABYLON.Observable();
  75257. /**
  75258. * An event triggered when the postprocess changes its size.
  75259. */
  75260. this.onSizeChangedObservable = new BABYLON.Observable();
  75261. /**
  75262. * An event triggered when the postprocess applies its effect.
  75263. */
  75264. this.onApplyObservable = new BABYLON.Observable();
  75265. /**
  75266. * An event triggered before rendering the postprocess
  75267. */
  75268. this.onBeforeRenderObservable = new BABYLON.Observable();
  75269. /**
  75270. * An event triggered after rendering the postprocess
  75271. */
  75272. this.onAfterRenderObservable = new BABYLON.Observable();
  75273. if (camera != null) {
  75274. this._camera = camera;
  75275. this._scene = camera.getScene();
  75276. camera.attachPostProcess(this);
  75277. this._engine = this._scene.getEngine();
  75278. this._scene.postProcesses.push(this);
  75279. }
  75280. else if (engine) {
  75281. this._engine = engine;
  75282. this._engine.postProcesses.push(this);
  75283. }
  75284. this._options = options;
  75285. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75286. this._reusable = reusable || false;
  75287. this._textureType = textureType;
  75288. this._samplers = samplers || [];
  75289. this._samplers.push("textureSampler");
  75290. this._fragmentUrl = fragmentUrl;
  75291. this._vertexUrl = vertexUrl;
  75292. this._parameters = parameters || [];
  75293. this._parameters.push("scale");
  75294. this._indexParameters = indexParameters;
  75295. if (!blockCompilation) {
  75296. this.updateEffect(defines);
  75297. }
  75298. }
  75299. Object.defineProperty(PostProcess.prototype, "samples", {
  75300. /**
  75301. * Number of sample textures (default: 1)
  75302. */
  75303. get: function () {
  75304. return this._samples;
  75305. },
  75306. set: function (n) {
  75307. var _this = this;
  75308. this._samples = n;
  75309. this._textures.forEach(function (texture) {
  75310. if (texture.samples !== _this._samples) {
  75311. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75312. }
  75313. });
  75314. },
  75315. enumerable: true,
  75316. configurable: true
  75317. });
  75318. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75319. /**
  75320. * A function that is added to the onActivateObservable
  75321. */
  75322. set: function (callback) {
  75323. if (this._onActivateObserver) {
  75324. this.onActivateObservable.remove(this._onActivateObserver);
  75325. }
  75326. if (callback) {
  75327. this._onActivateObserver = this.onActivateObservable.add(callback);
  75328. }
  75329. },
  75330. enumerable: true,
  75331. configurable: true
  75332. });
  75333. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75334. /**
  75335. * A function that is added to the onSizeChangedObservable
  75336. */
  75337. set: function (callback) {
  75338. if (this._onSizeChangedObserver) {
  75339. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75340. }
  75341. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75342. },
  75343. enumerable: true,
  75344. configurable: true
  75345. });
  75346. Object.defineProperty(PostProcess.prototype, "onApply", {
  75347. /**
  75348. * A function that is added to the onApplyObservable
  75349. */
  75350. set: function (callback) {
  75351. if (this._onApplyObserver) {
  75352. this.onApplyObservable.remove(this._onApplyObserver);
  75353. }
  75354. this._onApplyObserver = this.onApplyObservable.add(callback);
  75355. },
  75356. enumerable: true,
  75357. configurable: true
  75358. });
  75359. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75360. /**
  75361. * A function that is added to the onBeforeRenderObservable
  75362. */
  75363. set: function (callback) {
  75364. if (this._onBeforeRenderObserver) {
  75365. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75366. }
  75367. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75368. },
  75369. enumerable: true,
  75370. configurable: true
  75371. });
  75372. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75373. /**
  75374. * A function that is added to the onAfterRenderObservable
  75375. */
  75376. set: function (callback) {
  75377. if (this._onAfterRenderObserver) {
  75378. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75379. }
  75380. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75381. },
  75382. enumerable: true,
  75383. configurable: true
  75384. });
  75385. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75386. /**
  75387. * 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
  75388. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75389. */
  75390. get: function () {
  75391. return this._textures.data[this._currentRenderTextureInd];
  75392. },
  75393. set: function (value) {
  75394. this._forcedOutputTexture = value;
  75395. },
  75396. enumerable: true,
  75397. configurable: true
  75398. });
  75399. /**
  75400. * Gets the camera which post process is applied to.
  75401. * @returns The camera the post process is applied to.
  75402. */
  75403. PostProcess.prototype.getCamera = function () {
  75404. return this._camera;
  75405. };
  75406. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75407. /**
  75408. * Gets the texel size of the postprocess.
  75409. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75410. */
  75411. get: function () {
  75412. if (this._shareOutputWithPostProcess) {
  75413. return this._shareOutputWithPostProcess.texelSize;
  75414. }
  75415. if (this._forcedOutputTexture) {
  75416. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75417. }
  75418. return this._texelSize;
  75419. },
  75420. enumerable: true,
  75421. configurable: true
  75422. });
  75423. /**
  75424. * Gets the engine which this post process belongs to.
  75425. * @returns The engine the post process was enabled with.
  75426. */
  75427. PostProcess.prototype.getEngine = function () {
  75428. return this._engine;
  75429. };
  75430. /**
  75431. * The effect that is created when initializing the post process.
  75432. * @returns The created effect corrisponding the the postprocess.
  75433. */
  75434. PostProcess.prototype.getEffect = function () {
  75435. return this._effect;
  75436. };
  75437. /**
  75438. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75439. * @param postProcess The post process to share the output with.
  75440. * @returns This post process.
  75441. */
  75442. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75443. this._disposeTextures();
  75444. this._shareOutputWithPostProcess = postProcess;
  75445. return this;
  75446. };
  75447. /**
  75448. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75449. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75450. */
  75451. PostProcess.prototype.useOwnOutput = function () {
  75452. if (this._textures.length == 0) {
  75453. this._textures = new BABYLON.SmartArray(2);
  75454. }
  75455. this._shareOutputWithPostProcess = null;
  75456. };
  75457. /**
  75458. * Updates the effect with the current post process compile time values and recompiles the shader.
  75459. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75460. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75461. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75462. * @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
  75463. * @param onCompiled Called when the shader has been compiled.
  75464. * @param onError Called if there is an error when compiling a shader.
  75465. */
  75466. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75467. if (defines === void 0) { defines = null; }
  75468. if (uniforms === void 0) { uniforms = null; }
  75469. if (samplers === void 0) { samplers = null; }
  75470. 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);
  75471. };
  75472. /**
  75473. * The post process is reusable if it can be used multiple times within one frame.
  75474. * @returns If the post process is reusable
  75475. */
  75476. PostProcess.prototype.isReusable = function () {
  75477. return this._reusable;
  75478. };
  75479. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  75480. PostProcess.prototype.markTextureDirty = function () {
  75481. this.width = -1;
  75482. };
  75483. /**
  75484. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  75485. * 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.
  75486. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  75487. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  75488. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  75489. * @returns The target texture that was bound to be written to.
  75490. */
  75491. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  75492. var _this = this;
  75493. if (sourceTexture === void 0) { sourceTexture = null; }
  75494. camera = camera || this._camera;
  75495. var scene = camera.getScene();
  75496. var engine = scene.getEngine();
  75497. var maxSize = engine.getCaps().maxTextureSize;
  75498. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  75499. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  75500. // 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
  75501. var webVRCamera = camera.parent;
  75502. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  75503. requiredWidth /= 2;
  75504. }
  75505. var desiredWidth = (this._options.width || requiredWidth);
  75506. var desiredHeight = this._options.height || requiredHeight;
  75507. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  75508. if (this.adaptScaleToCurrentViewport) {
  75509. var currentViewport = engine.currentViewport;
  75510. if (currentViewport) {
  75511. desiredWidth *= currentViewport.width;
  75512. desiredHeight *= currentViewport.height;
  75513. }
  75514. }
  75515. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  75516. if (!this._options.width) {
  75517. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  75518. }
  75519. if (!this._options.height) {
  75520. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  75521. }
  75522. }
  75523. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  75524. if (this._textures.length > 0) {
  75525. for (var i = 0; i < this._textures.length; i++) {
  75526. this._engine._releaseTexture(this._textures.data[i]);
  75527. }
  75528. this._textures.reset();
  75529. }
  75530. this.width = desiredWidth;
  75531. this.height = desiredHeight;
  75532. var textureSize = { width: this.width, height: this.height };
  75533. var textureOptions = {
  75534. generateMipMaps: false,
  75535. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  75536. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  75537. samplingMode: this.renderTargetSamplingMode,
  75538. type: this._textureType
  75539. };
  75540. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75541. if (this._reusable) {
  75542. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75543. }
  75544. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  75545. this.onSizeChangedObservable.notifyObservers(this);
  75546. }
  75547. this._textures.forEach(function (texture) {
  75548. if (texture.samples !== _this.samples) {
  75549. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  75550. }
  75551. });
  75552. }
  75553. var target;
  75554. if (this._shareOutputWithPostProcess) {
  75555. target = this._shareOutputWithPostProcess.inputTexture;
  75556. }
  75557. else if (this._forcedOutputTexture) {
  75558. target = this._forcedOutputTexture;
  75559. this.width = this._forcedOutputTexture.width;
  75560. this.height = this._forcedOutputTexture.height;
  75561. }
  75562. else {
  75563. target = this.inputTexture;
  75564. }
  75565. // Bind the input of this post process to be used as the output of the previous post process.
  75566. if (this.enablePixelPerfectMode) {
  75567. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  75568. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  75569. }
  75570. else {
  75571. this._scaleRatio.copyFromFloats(1, 1);
  75572. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  75573. }
  75574. this.onActivateObservable.notifyObservers(camera);
  75575. // Clear
  75576. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  75577. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  75578. }
  75579. if (this._reusable) {
  75580. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  75581. }
  75582. return target;
  75583. };
  75584. Object.defineProperty(PostProcess.prototype, "isSupported", {
  75585. /**
  75586. * If the post process is supported.
  75587. */
  75588. get: function () {
  75589. return this._effect.isSupported;
  75590. },
  75591. enumerable: true,
  75592. configurable: true
  75593. });
  75594. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  75595. /**
  75596. * The aspect ratio of the output texture.
  75597. */
  75598. get: function () {
  75599. if (this._shareOutputWithPostProcess) {
  75600. return this._shareOutputWithPostProcess.aspectRatio;
  75601. }
  75602. if (this._forcedOutputTexture) {
  75603. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  75604. }
  75605. return this.width / this.height;
  75606. },
  75607. enumerable: true,
  75608. configurable: true
  75609. });
  75610. /**
  75611. * Get a value indicating if the post-process is ready to be used
  75612. * @returns true if the post-process is ready (shader is compiled)
  75613. */
  75614. PostProcess.prototype.isReady = function () {
  75615. return this._effect && this._effect.isReady();
  75616. };
  75617. /**
  75618. * Binds all textures and uniforms to the shader, this will be run on every pass.
  75619. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  75620. */
  75621. PostProcess.prototype.apply = function () {
  75622. // Check
  75623. if (!this._effect || !this._effect.isReady()) {
  75624. return null;
  75625. }
  75626. // States
  75627. this._engine.enableEffect(this._effect);
  75628. this._engine.setState(false);
  75629. this._engine.setDepthBuffer(false);
  75630. this._engine.setDepthWrite(false);
  75631. // Alpha
  75632. this._engine.setAlphaMode(this.alphaMode);
  75633. if (this.alphaConstants) {
  75634. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  75635. }
  75636. // Bind the output texture of the preivous post process as the input to this post process.
  75637. var source;
  75638. if (this._shareOutputWithPostProcess) {
  75639. source = this._shareOutputWithPostProcess.inputTexture;
  75640. }
  75641. else if (this._forcedOutputTexture) {
  75642. source = this._forcedOutputTexture;
  75643. }
  75644. else {
  75645. source = this.inputTexture;
  75646. }
  75647. this._effect._bindTexture("textureSampler", source);
  75648. // Parameters
  75649. this._effect.setVector2("scale", this._scaleRatio);
  75650. this.onApplyObservable.notifyObservers(this._effect);
  75651. return this._effect;
  75652. };
  75653. PostProcess.prototype._disposeTextures = function () {
  75654. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  75655. return;
  75656. }
  75657. if (this._textures.length > 0) {
  75658. for (var i = 0; i < this._textures.length; i++) {
  75659. this._engine._releaseTexture(this._textures.data[i]);
  75660. }
  75661. }
  75662. this._textures.dispose();
  75663. };
  75664. /**
  75665. * Disposes the post process.
  75666. * @param camera The camera to dispose the post process on.
  75667. */
  75668. PostProcess.prototype.dispose = function (camera) {
  75669. camera = camera || this._camera;
  75670. this._disposeTextures();
  75671. if (this._scene) {
  75672. var index_1 = this._scene.postProcesses.indexOf(this);
  75673. if (index_1 !== -1) {
  75674. this._scene.postProcesses.splice(index_1, 1);
  75675. }
  75676. }
  75677. else {
  75678. var index_2 = this._engine.postProcesses.indexOf(this);
  75679. if (index_2 !== -1) {
  75680. this._engine.postProcesses.splice(index_2, 1);
  75681. }
  75682. }
  75683. if (!camera) {
  75684. return;
  75685. }
  75686. camera.detachPostProcess(this);
  75687. var index = camera._postProcesses.indexOf(this);
  75688. if (index === 0 && camera._postProcesses.length > 0) {
  75689. var firstPostProcess = this._camera._getFirstPostProcess();
  75690. if (firstPostProcess) {
  75691. firstPostProcess.markTextureDirty();
  75692. }
  75693. }
  75694. this.onActivateObservable.clear();
  75695. this.onAfterRenderObservable.clear();
  75696. this.onApplyObservable.clear();
  75697. this.onBeforeRenderObservable.clear();
  75698. this.onSizeChangedObservable.clear();
  75699. };
  75700. return PostProcess;
  75701. }());
  75702. BABYLON.PostProcess = PostProcess;
  75703. })(BABYLON || (BABYLON = {}));
  75704. //# sourceMappingURL=babylon.postProcess.js.map
  75705. var BABYLON;
  75706. (function (BABYLON) {
  75707. /**
  75708. * PassPostProcess which produces an output the same as it's input
  75709. */
  75710. var PassPostProcess = /** @class */ (function (_super) {
  75711. __extends(PassPostProcess, _super);
  75712. /**
  75713. * Creates the PassPostProcess
  75714. * @param name The name of the effect.
  75715. * @param options The required width/height ratio to downsize to before computing the render pass.
  75716. * @param camera The camera to apply the render pass to.
  75717. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75718. * @param engine The engine which the post process will be applied. (default: current engine)
  75719. * @param reusable If the post process can be reused on the same frame. (default: false)
  75720. * @param textureType The type of texture to be used when performing the post processing.
  75721. * @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)
  75722. */
  75723. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75724. if (camera === void 0) { camera = null; }
  75725. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75726. if (blockCompilation === void 0) { blockCompilation = false; }
  75727. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  75728. }
  75729. return PassPostProcess;
  75730. }(BABYLON.PostProcess));
  75731. BABYLON.PassPostProcess = PassPostProcess;
  75732. })(BABYLON || (BABYLON = {}));
  75733. //# sourceMappingURL=babylon.passPostProcess.js.map
  75734. var __assign = (this && this.__assign) || function () {
  75735. __assign = Object.assign || function(t) {
  75736. for (var s, i = 1, n = arguments.length; i < n; i++) {
  75737. s = arguments[i];
  75738. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  75739. t[p] = s[p];
  75740. }
  75741. return t;
  75742. };
  75743. return __assign.apply(this, arguments);
  75744. };
  75745. var BABYLON;
  75746. (function (BABYLON) {
  75747. /**
  75748. * Default implementation IShadowGenerator.
  75749. * This is the main object responsible of generating shadows in the framework.
  75750. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  75751. */
  75752. var ShadowGenerator = /** @class */ (function () {
  75753. /**
  75754. * Creates a ShadowGenerator object.
  75755. * A ShadowGenerator is the required tool to use the shadows.
  75756. * Each light casting shadows needs to use its own ShadowGenerator.
  75757. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  75758. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  75759. * @param light The light object generating the shadows.
  75760. * @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.
  75761. */
  75762. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  75763. this._bias = 0.00005;
  75764. this._normalBias = 0;
  75765. this._blurBoxOffset = 1;
  75766. this._blurScale = 2;
  75767. this._blurKernel = 1;
  75768. this._useKernelBlur = false;
  75769. this._filter = ShadowGenerator.FILTER_NONE;
  75770. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  75771. this._contactHardeningLightSizeUVRatio = 0.1;
  75772. this._darkness = 0;
  75773. this._transparencyShadow = false;
  75774. /**
  75775. * Controls the extent to which the shadows fade out at the edge of the frustum
  75776. * Used only by directionals and spots
  75777. */
  75778. this.frustumEdgeFalloff = 0;
  75779. /**
  75780. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  75781. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  75782. * It might on the other hand introduce peter panning.
  75783. */
  75784. this.forceBackFacesOnly = false;
  75785. this._lightDirection = BABYLON.Vector3.Zero();
  75786. this._viewMatrix = BABYLON.Matrix.Zero();
  75787. this._projectionMatrix = BABYLON.Matrix.Zero();
  75788. this._transformMatrix = BABYLON.Matrix.Zero();
  75789. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75790. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75791. this._currentFaceIndex = 0;
  75792. this._currentFaceIndexCache = 0;
  75793. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  75794. this._mapSize = mapSize;
  75795. this._light = light;
  75796. this._scene = light.getScene();
  75797. light._shadowGenerator = this;
  75798. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  75799. if (!component) {
  75800. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  75801. this._scene._addComponent(component);
  75802. }
  75803. // Texture type fallback from float to int if not supported.
  75804. var caps = this._scene.getEngine().getCaps();
  75805. if (!useFullFloatFirst) {
  75806. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75807. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75808. }
  75809. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75810. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75811. }
  75812. else {
  75813. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75814. }
  75815. }
  75816. else {
  75817. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75818. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75819. }
  75820. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75821. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75822. }
  75823. else {
  75824. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75825. }
  75826. }
  75827. this._initializeGenerator();
  75828. this._applyFilterValues();
  75829. }
  75830. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  75831. /**
  75832. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  75833. */
  75834. get: function () {
  75835. return this._bias;
  75836. },
  75837. /**
  75838. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  75839. */
  75840. set: function (bias) {
  75841. this._bias = bias;
  75842. },
  75843. enumerable: true,
  75844. configurable: true
  75845. });
  75846. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  75847. /**
  75848. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75849. */
  75850. get: function () {
  75851. return this._normalBias;
  75852. },
  75853. /**
  75854. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75855. */
  75856. set: function (normalBias) {
  75857. this._normalBias = normalBias;
  75858. },
  75859. enumerable: true,
  75860. configurable: true
  75861. });
  75862. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  75863. /**
  75864. * Gets the blur box offset: offset applied during the blur pass.
  75865. * Only usefull if useKernelBlur = false
  75866. */
  75867. get: function () {
  75868. return this._blurBoxOffset;
  75869. },
  75870. /**
  75871. * Sets the blur box offset: offset applied during the blur pass.
  75872. * Only usefull if useKernelBlur = false
  75873. */
  75874. set: function (value) {
  75875. if (this._blurBoxOffset === value) {
  75876. return;
  75877. }
  75878. this._blurBoxOffset = value;
  75879. this._disposeBlurPostProcesses();
  75880. },
  75881. enumerable: true,
  75882. configurable: true
  75883. });
  75884. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  75885. /**
  75886. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  75887. * 2 means half of the size.
  75888. */
  75889. get: function () {
  75890. return this._blurScale;
  75891. },
  75892. /**
  75893. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  75894. * 2 means half of the size.
  75895. */
  75896. set: function (value) {
  75897. if (this._blurScale === value) {
  75898. return;
  75899. }
  75900. this._blurScale = value;
  75901. this._disposeBlurPostProcesses();
  75902. },
  75903. enumerable: true,
  75904. configurable: true
  75905. });
  75906. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  75907. /**
  75908. * Gets the blur kernel: kernel size of the blur pass.
  75909. * Only usefull if useKernelBlur = true
  75910. */
  75911. get: function () {
  75912. return this._blurKernel;
  75913. },
  75914. /**
  75915. * Sets the blur kernel: kernel size of the blur pass.
  75916. * Only usefull if useKernelBlur = true
  75917. */
  75918. set: function (value) {
  75919. if (this._blurKernel === value) {
  75920. return;
  75921. }
  75922. this._blurKernel = value;
  75923. this._disposeBlurPostProcesses();
  75924. },
  75925. enumerable: true,
  75926. configurable: true
  75927. });
  75928. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  75929. /**
  75930. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  75931. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75932. */
  75933. get: function () {
  75934. return this._useKernelBlur;
  75935. },
  75936. /**
  75937. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  75938. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75939. */
  75940. set: function (value) {
  75941. if (this._useKernelBlur === value) {
  75942. return;
  75943. }
  75944. this._useKernelBlur = value;
  75945. this._disposeBlurPostProcesses();
  75946. },
  75947. enumerable: true,
  75948. configurable: true
  75949. });
  75950. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  75951. /**
  75952. * Gets the depth scale used in ESM mode.
  75953. */
  75954. get: function () {
  75955. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  75956. },
  75957. /**
  75958. * Sets the depth scale used in ESM mode.
  75959. * This can override the scale stored on the light.
  75960. */
  75961. set: function (value) {
  75962. this._depthScale = value;
  75963. },
  75964. enumerable: true,
  75965. configurable: true
  75966. });
  75967. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  75968. /**
  75969. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  75970. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  75971. */
  75972. get: function () {
  75973. return this._filter;
  75974. },
  75975. /**
  75976. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  75977. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  75978. */
  75979. set: function (value) {
  75980. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  75981. if (this._light.needCube()) {
  75982. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75983. this.useExponentialShadowMap = true;
  75984. return;
  75985. }
  75986. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75987. this.useCloseExponentialShadowMap = true;
  75988. return;
  75989. }
  75990. // PCF on cubemap would also be expensive
  75991. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  75992. this.usePoissonSampling = true;
  75993. return;
  75994. }
  75995. }
  75996. // Weblg1 fallback for PCF.
  75997. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  75998. if (this._scene.getEngine().webGLVersion === 1) {
  75999. this.usePoissonSampling = true;
  76000. return;
  76001. }
  76002. }
  76003. if (this._filter === value) {
  76004. return;
  76005. }
  76006. this._filter = value;
  76007. this._disposeBlurPostProcesses();
  76008. this._applyFilterValues();
  76009. this._light._markMeshesAsLightDirty();
  76010. },
  76011. enumerable: true,
  76012. configurable: true
  76013. });
  76014. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76015. /**
  76016. * Gets if the current filter is set to Poisson Sampling.
  76017. */
  76018. get: function () {
  76019. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76020. },
  76021. /**
  76022. * Sets the current filter to Poisson Sampling.
  76023. */
  76024. set: function (value) {
  76025. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76026. return;
  76027. }
  76028. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76029. },
  76030. enumerable: true,
  76031. configurable: true
  76032. });
  76033. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  76034. /**
  76035. * Gets if the current filter is set to VSM.
  76036. * DEPRECATED. Should use useExponentialShadowMap instead.
  76037. */
  76038. get: function () {
  76039. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  76040. return this.useExponentialShadowMap;
  76041. },
  76042. /**
  76043. * Sets the current filter is to VSM.
  76044. * DEPRECATED. Should use useExponentialShadowMap instead.
  76045. */
  76046. set: function (value) {
  76047. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  76048. this.useExponentialShadowMap = value;
  76049. },
  76050. enumerable: true,
  76051. configurable: true
  76052. });
  76053. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  76054. /**
  76055. * Gets if the current filter is set to blurred VSM.
  76056. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  76057. */
  76058. get: function () {
  76059. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  76060. return this.useBlurExponentialShadowMap;
  76061. },
  76062. /**
  76063. * Sets the current filter is to blurred VSM.
  76064. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  76065. */
  76066. set: function (value) {
  76067. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  76068. this.useBlurExponentialShadowMap = value;
  76069. },
  76070. enumerable: true,
  76071. configurable: true
  76072. });
  76073. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76074. /**
  76075. * Gets if the current filter is set to ESM.
  76076. */
  76077. get: function () {
  76078. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76079. },
  76080. /**
  76081. * Sets the current filter is to ESM.
  76082. */
  76083. set: function (value) {
  76084. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76085. return;
  76086. }
  76087. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76088. },
  76089. enumerable: true,
  76090. configurable: true
  76091. });
  76092. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76093. /**
  76094. * Gets if the current filter is set to filtered ESM.
  76095. */
  76096. get: function () {
  76097. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76098. },
  76099. /**
  76100. * Gets if the current filter is set to filtered ESM.
  76101. */
  76102. set: function (value) {
  76103. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76104. return;
  76105. }
  76106. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76107. },
  76108. enumerable: true,
  76109. configurable: true
  76110. });
  76111. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76112. /**
  76113. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76114. * exponential to prevent steep falloff artifacts).
  76115. */
  76116. get: function () {
  76117. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76118. },
  76119. /**
  76120. * Sets the current filter to "close ESM" (using the inverse of the
  76121. * exponential to prevent steep falloff artifacts).
  76122. */
  76123. set: function (value) {
  76124. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76125. return;
  76126. }
  76127. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76128. },
  76129. enumerable: true,
  76130. configurable: true
  76131. });
  76132. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76133. /**
  76134. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76135. * exponential to prevent steep falloff artifacts).
  76136. */
  76137. get: function () {
  76138. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76139. },
  76140. /**
  76141. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76142. * exponential to prevent steep falloff artifacts).
  76143. */
  76144. set: function (value) {
  76145. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76146. return;
  76147. }
  76148. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76149. },
  76150. enumerable: true,
  76151. configurable: true
  76152. });
  76153. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76154. /**
  76155. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76156. */
  76157. get: function () {
  76158. return this.filter === ShadowGenerator.FILTER_PCF;
  76159. },
  76160. /**
  76161. * Sets the current filter to "PCF" (percentage closer filtering).
  76162. */
  76163. set: function (value) {
  76164. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76165. return;
  76166. }
  76167. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76168. },
  76169. enumerable: true,
  76170. configurable: true
  76171. });
  76172. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76173. /**
  76174. * Gets the PCF or PCSS Quality.
  76175. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76176. */
  76177. get: function () {
  76178. return this._filteringQuality;
  76179. },
  76180. /**
  76181. * Sets the PCF or PCSS Quality.
  76182. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76183. */
  76184. set: function (filteringQuality) {
  76185. this._filteringQuality = filteringQuality;
  76186. },
  76187. enumerable: true,
  76188. configurable: true
  76189. });
  76190. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76191. /**
  76192. * Gets if the current filter is set to "PCSS" (contact hardening).
  76193. */
  76194. get: function () {
  76195. return this.filter === ShadowGenerator.FILTER_PCSS;
  76196. },
  76197. /**
  76198. * Sets the current filter to "PCSS" (contact hardening).
  76199. */
  76200. set: function (value) {
  76201. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76202. return;
  76203. }
  76204. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76205. },
  76206. enumerable: true,
  76207. configurable: true
  76208. });
  76209. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76210. /**
  76211. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76212. * Using a ratio helps keeping shape stability independently of the map size.
  76213. *
  76214. * It does not account for the light projection as it was having too much
  76215. * instability during the light setup or during light position changes.
  76216. *
  76217. * Only valid if useContactHardeningShadow is true.
  76218. */
  76219. get: function () {
  76220. return this._contactHardeningLightSizeUVRatio;
  76221. },
  76222. /**
  76223. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76224. * Using a ratio helps keeping shape stability independently of the map size.
  76225. *
  76226. * It does not account for the light projection as it was having too much
  76227. * instability during the light setup or during light position changes.
  76228. *
  76229. * Only valid if useContactHardeningShadow is true.
  76230. */
  76231. set: function (contactHardeningLightSizeUVRatio) {
  76232. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76233. },
  76234. enumerable: true,
  76235. configurable: true
  76236. });
  76237. /**
  76238. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76239. * 0 means strongest and 1 would means no shadow.
  76240. * @returns the darkness.
  76241. */
  76242. ShadowGenerator.prototype.getDarkness = function () {
  76243. return this._darkness;
  76244. };
  76245. /**
  76246. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76247. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76248. * @returns the shadow generator allowing fluent coding.
  76249. */
  76250. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76251. if (darkness >= 1.0) {
  76252. this._darkness = 1.0;
  76253. }
  76254. else if (darkness <= 0.0) {
  76255. this._darkness = 0.0;
  76256. }
  76257. else {
  76258. this._darkness = darkness;
  76259. }
  76260. return this;
  76261. };
  76262. /**
  76263. * Sets the ability to have transparent shadow (boolean).
  76264. * @param transparent True if transparent else False
  76265. * @returns the shadow generator allowing fluent coding
  76266. */
  76267. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76268. this._transparencyShadow = transparent;
  76269. return this;
  76270. };
  76271. /**
  76272. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76273. * @returns The render target texture if present otherwise, null
  76274. */
  76275. ShadowGenerator.prototype.getShadowMap = function () {
  76276. return this._shadowMap;
  76277. };
  76278. /**
  76279. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76280. * @returns The render target texture if the shadow map is present otherwise, null
  76281. */
  76282. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76283. if (this._shadowMap2) {
  76284. return this._shadowMap2;
  76285. }
  76286. return this._shadowMap;
  76287. };
  76288. /**
  76289. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76290. * @param mesh Mesh to add
  76291. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76292. * @returns the Shadow Generator itself
  76293. */
  76294. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76295. if (includeDescendants === void 0) { includeDescendants = true; }
  76296. var _a;
  76297. if (!this._shadowMap) {
  76298. return this;
  76299. }
  76300. if (!this._shadowMap.renderList) {
  76301. this._shadowMap.renderList = [];
  76302. }
  76303. this._shadowMap.renderList.push(mesh);
  76304. if (includeDescendants) {
  76305. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76306. }
  76307. return this;
  76308. };
  76309. /**
  76310. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76311. * @param mesh Mesh to remove
  76312. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76313. * @returns the Shadow Generator itself
  76314. */
  76315. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76316. if (includeDescendants === void 0) { includeDescendants = true; }
  76317. if (!this._shadowMap || !this._shadowMap.renderList) {
  76318. return this;
  76319. }
  76320. var index = this._shadowMap.renderList.indexOf(mesh);
  76321. if (index !== -1) {
  76322. this._shadowMap.renderList.splice(index, 1);
  76323. }
  76324. if (includeDescendants) {
  76325. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76326. var child = _a[_i];
  76327. this.removeShadowCaster(child);
  76328. }
  76329. }
  76330. return this;
  76331. };
  76332. /**
  76333. * Returns the associated light object.
  76334. * @returns the light generating the shadow
  76335. */
  76336. ShadowGenerator.prototype.getLight = function () {
  76337. return this._light;
  76338. };
  76339. ShadowGenerator.prototype._initializeGenerator = function () {
  76340. this._light._markMeshesAsLightDirty();
  76341. this._initializeShadowMap();
  76342. };
  76343. ShadowGenerator.prototype._initializeShadowMap = function () {
  76344. var _this = this;
  76345. // Render target
  76346. var engine = this._scene.getEngine();
  76347. if (engine.webGLVersion > 1) {
  76348. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76349. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76350. }
  76351. else {
  76352. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76353. }
  76354. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76355. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76356. this._shadowMap.anisotropicFilteringLevel = 1;
  76357. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76358. this._shadowMap.renderParticles = false;
  76359. this._shadowMap.ignoreCameraViewport = true;
  76360. // Record Face Index before render.
  76361. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76362. _this._currentFaceIndex = faceIndex;
  76363. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76364. engine.setColorWrite(false);
  76365. }
  76366. });
  76367. // Custom render function.
  76368. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76369. // Blur if required afer render.
  76370. this._shadowMap.onAfterUnbindObservable.add(function () {
  76371. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76372. engine.setColorWrite(true);
  76373. }
  76374. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76375. return;
  76376. }
  76377. var shadowMap = _this.getShadowMapForRendering();
  76378. if (shadowMap) {
  76379. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76380. }
  76381. });
  76382. // Clear according to the chosen filter.
  76383. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76384. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76385. this._shadowMap.onClearObservable.add(function (engine) {
  76386. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76387. engine.clear(clearOne, false, true, false);
  76388. }
  76389. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76390. engine.clear(clearZero, true, true, false);
  76391. }
  76392. else {
  76393. engine.clear(clearOne, true, true, false);
  76394. }
  76395. });
  76396. };
  76397. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76398. var _this = this;
  76399. var engine = this._scene.getEngine();
  76400. var targetSize = this._mapSize / this.blurScale;
  76401. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76402. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76403. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76404. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76405. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76406. }
  76407. if (this.useKernelBlur) {
  76408. 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);
  76409. this._kernelBlurXPostprocess.width = targetSize;
  76410. this._kernelBlurXPostprocess.height = targetSize;
  76411. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76412. effect.setTexture("textureSampler", _this._shadowMap);
  76413. });
  76414. 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);
  76415. this._kernelBlurXPostprocess.autoClear = false;
  76416. this._kernelBlurYPostprocess.autoClear = false;
  76417. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76418. this._kernelBlurXPostprocess.packedFloat = true;
  76419. this._kernelBlurYPostprocess.packedFloat = true;
  76420. }
  76421. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76422. }
  76423. else {
  76424. 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);
  76425. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76426. effect.setFloat2("screenSize", targetSize, targetSize);
  76427. effect.setTexture("textureSampler", _this._shadowMap);
  76428. });
  76429. this._boxBlurPostprocess.autoClear = false;
  76430. this._blurPostProcesses = [this._boxBlurPostprocess];
  76431. }
  76432. };
  76433. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76434. var index;
  76435. var engine = this._scene.getEngine();
  76436. if (depthOnlySubMeshes.length) {
  76437. engine.setColorWrite(false);
  76438. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76439. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76440. }
  76441. engine.setColorWrite(true);
  76442. }
  76443. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76444. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76445. }
  76446. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76447. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76448. }
  76449. if (this._transparencyShadow) {
  76450. for (index = 0; index < transparentSubMeshes.length; index++) {
  76451. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  76452. }
  76453. }
  76454. };
  76455. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  76456. var _this = this;
  76457. var mesh = subMesh.getRenderingMesh();
  76458. var scene = this._scene;
  76459. var engine = scene.getEngine();
  76460. var material = subMesh.getMaterial();
  76461. if (!material) {
  76462. return;
  76463. }
  76464. // Culling
  76465. engine.setState(material.backFaceCulling);
  76466. // Managing instances
  76467. var batch = mesh._getInstancesRenderList(subMesh._id);
  76468. if (batch.mustReturn) {
  76469. return;
  76470. }
  76471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76472. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  76473. engine.enableEffect(this._effect);
  76474. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76475. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  76476. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  76477. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76478. this._effect.setVector3("lightData", this._cachedDirection);
  76479. }
  76480. else {
  76481. this._effect.setVector3("lightData", this._cachedPosition);
  76482. }
  76483. if (scene.activeCamera) {
  76484. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  76485. }
  76486. // Alpha test
  76487. if (material && material.needAlphaTesting()) {
  76488. var alphaTexture = material.getAlphaTestTexture();
  76489. if (alphaTexture) {
  76490. this._effect.setTexture("diffuseSampler", alphaTexture);
  76491. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  76492. }
  76493. }
  76494. // Bones
  76495. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76496. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  76497. }
  76498. // Morph targets
  76499. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  76500. if (this.forceBackFacesOnly) {
  76501. engine.setState(true, 0, false, true);
  76502. }
  76503. // Draw
  76504. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76505. if (this.forceBackFacesOnly) {
  76506. engine.setState(true, 0, false, false);
  76507. }
  76508. }
  76509. else {
  76510. // Need to reset refresh rate of the shadowMap
  76511. if (this._shadowMap) {
  76512. this._shadowMap.resetRefreshCounter();
  76513. }
  76514. }
  76515. };
  76516. ShadowGenerator.prototype._applyFilterValues = function () {
  76517. if (!this._shadowMap) {
  76518. return;
  76519. }
  76520. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  76521. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  76522. }
  76523. else {
  76524. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76525. }
  76526. };
  76527. /**
  76528. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76529. * @param onCompiled Callback triggered at the and of the effects compilation
  76530. * @param options Sets of optional options forcing the compilation with different modes
  76531. */
  76532. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  76533. var _this = this;
  76534. var localOptions = __assign({ useInstances: false }, options);
  76535. var shadowMap = this.getShadowMap();
  76536. if (!shadowMap) {
  76537. if (onCompiled) {
  76538. onCompiled(this);
  76539. }
  76540. return;
  76541. }
  76542. var renderList = shadowMap.renderList;
  76543. if (!renderList) {
  76544. if (onCompiled) {
  76545. onCompiled(this);
  76546. }
  76547. return;
  76548. }
  76549. var subMeshes = new Array();
  76550. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  76551. var mesh = renderList_1[_i];
  76552. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  76553. }
  76554. if (subMeshes.length === 0) {
  76555. if (onCompiled) {
  76556. onCompiled(this);
  76557. }
  76558. return;
  76559. }
  76560. var currentIndex = 0;
  76561. var checkReady = function () {
  76562. if (!_this._scene || !_this._scene.getEngine()) {
  76563. return;
  76564. }
  76565. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  76566. currentIndex++;
  76567. if (currentIndex >= subMeshes.length) {
  76568. if (onCompiled) {
  76569. onCompiled(_this);
  76570. }
  76571. return;
  76572. }
  76573. }
  76574. setTimeout(checkReady, 16);
  76575. };
  76576. checkReady();
  76577. };
  76578. /**
  76579. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76580. * @param options Sets of optional options forcing the compilation with different modes
  76581. * @returns A promise that resolves when the compilation completes
  76582. */
  76583. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  76584. var _this = this;
  76585. return new Promise(function (resolve) {
  76586. _this.forceCompilation(function () {
  76587. resolve();
  76588. }, options);
  76589. });
  76590. };
  76591. /**
  76592. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  76593. * @param subMesh The submesh we want to render in the shadow map
  76594. * @param useInstances Defines wether will draw in the map using instances
  76595. * @returns true if ready otherwise, false
  76596. */
  76597. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  76598. var defines = [];
  76599. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76600. defines.push("#define FLOAT");
  76601. }
  76602. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76603. defines.push("#define ESM");
  76604. }
  76605. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  76606. defines.push("#define DEPTHTEXTURE");
  76607. }
  76608. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76609. var mesh = subMesh.getMesh();
  76610. var material = subMesh.getMaterial();
  76611. // Normal bias.
  76612. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76613. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76614. defines.push("#define NORMAL");
  76615. if (mesh.nonUniformScaling) {
  76616. defines.push("#define NONUNIFORMSCALING");
  76617. }
  76618. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76619. defines.push("#define DIRECTIONINLIGHTDATA");
  76620. }
  76621. }
  76622. // Alpha test
  76623. if (material && material.needAlphaTesting()) {
  76624. var alphaTexture = material.getAlphaTestTexture();
  76625. if (alphaTexture) {
  76626. defines.push("#define ALPHATEST");
  76627. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76628. attribs.push(BABYLON.VertexBuffer.UVKind);
  76629. defines.push("#define UV1");
  76630. }
  76631. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76632. if (alphaTexture.coordinatesIndex === 1) {
  76633. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76634. defines.push("#define UV2");
  76635. }
  76636. }
  76637. }
  76638. }
  76639. // Bones
  76640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76643. if (mesh.numBoneInfluencers > 4) {
  76644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76646. }
  76647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76648. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  76649. }
  76650. else {
  76651. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76652. }
  76653. // Morph targets
  76654. var manager = mesh.morphTargetManager;
  76655. var morphInfluencers = 0;
  76656. if (manager) {
  76657. if (manager.numInfluencers > 0) {
  76658. defines.push("#define MORPHTARGETS");
  76659. morphInfluencers = manager.numInfluencers;
  76660. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  76661. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  76662. }
  76663. }
  76664. // Instances
  76665. if (useInstances) {
  76666. defines.push("#define INSTANCES");
  76667. attribs.push("world0");
  76668. attribs.push("world1");
  76669. attribs.push("world2");
  76670. attribs.push("world3");
  76671. }
  76672. // Get correct effect
  76673. var join = defines.join("\n");
  76674. if (this._cachedDefines !== join) {
  76675. this._cachedDefines = join;
  76676. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  76677. }
  76678. if (!this._effect.isReady()) {
  76679. return false;
  76680. }
  76681. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76682. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  76683. this._initializeBlurRTTAndPostProcesses();
  76684. }
  76685. }
  76686. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  76687. return false;
  76688. }
  76689. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  76690. return false;
  76691. }
  76692. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  76693. return false;
  76694. }
  76695. return true;
  76696. };
  76697. /**
  76698. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  76699. * @param defines Defines of the material we want to update
  76700. * @param lightIndex Index of the light in the enabled light list of the material
  76701. */
  76702. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  76703. var scene = this._scene;
  76704. var light = this._light;
  76705. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76706. return;
  76707. }
  76708. defines["SHADOW" + lightIndex] = true;
  76709. if (this.useContactHardeningShadow) {
  76710. defines["SHADOWPCSS" + lightIndex] = true;
  76711. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76712. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76713. }
  76714. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76715. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76716. }
  76717. // else default to high.
  76718. }
  76719. if (this.usePercentageCloserFiltering) {
  76720. defines["SHADOWPCF" + lightIndex] = true;
  76721. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76722. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76723. }
  76724. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76725. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76726. }
  76727. // else default to high.
  76728. }
  76729. else if (this.usePoissonSampling) {
  76730. defines["SHADOWPOISSON" + lightIndex] = true;
  76731. }
  76732. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76733. defines["SHADOWESM" + lightIndex] = true;
  76734. }
  76735. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76736. defines["SHADOWCLOSEESM" + lightIndex] = true;
  76737. }
  76738. if (light.needCube()) {
  76739. defines["SHADOWCUBE" + lightIndex] = true;
  76740. }
  76741. };
  76742. /**
  76743. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  76744. * defined in the generator but impacting the effect).
  76745. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  76746. * @param effect The effect we are binfing the information for
  76747. */
  76748. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  76749. var light = this._light;
  76750. var scene = this._scene;
  76751. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76752. return;
  76753. }
  76754. var camera = scene.activeCamera;
  76755. if (!camera) {
  76756. return;
  76757. }
  76758. var shadowMap = this.getShadowMap();
  76759. if (!shadowMap) {
  76760. return;
  76761. }
  76762. if (!light.needCube()) {
  76763. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  76764. }
  76765. // Only PCF uses depth stencil texture.
  76766. if (this._filter === ShadowGenerator.FILTER_PCF) {
  76767. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76768. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76769. }
  76770. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  76771. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76772. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  76773. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76774. }
  76775. else {
  76776. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76777. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  76778. }
  76779. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  76780. };
  76781. /**
  76782. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  76783. * (eq to shadow prjection matrix * light transform matrix)
  76784. * @returns The transform matrix used to create the shadow map
  76785. */
  76786. ShadowGenerator.prototype.getTransformMatrix = function () {
  76787. var scene = this._scene;
  76788. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  76789. return this._transformMatrix;
  76790. }
  76791. this._currentRenderID = scene.getRenderId();
  76792. this._currentFaceIndexCache = this._currentFaceIndex;
  76793. var lightPosition = this._light.position;
  76794. if (this._light.computeTransformedInformation()) {
  76795. lightPosition = this._light.transformedPosition;
  76796. }
  76797. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  76798. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  76799. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  76800. }
  76801. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  76802. this._cachedPosition.copyFrom(lightPosition);
  76803. this._cachedDirection.copyFrom(this._lightDirection);
  76804. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  76805. var shadowMap = this.getShadowMap();
  76806. if (shadowMap) {
  76807. var renderList = shadowMap.renderList;
  76808. if (renderList) {
  76809. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  76810. }
  76811. }
  76812. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  76813. }
  76814. return this._transformMatrix;
  76815. };
  76816. /**
  76817. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  76818. * Cube and 2D textures for instance.
  76819. */
  76820. ShadowGenerator.prototype.recreateShadowMap = function () {
  76821. var shadowMap = this._shadowMap;
  76822. if (!shadowMap) {
  76823. return;
  76824. }
  76825. // Track render list.
  76826. var renderList = shadowMap.renderList;
  76827. // Clean up existing data.
  76828. this._disposeRTTandPostProcesses();
  76829. // Reinitializes.
  76830. this._initializeGenerator();
  76831. // Reaffect the filter to ensure a correct fallback if necessary.
  76832. this.filter = this.filter;
  76833. // Reaffect the filter.
  76834. this._applyFilterValues();
  76835. // Reaffect Render List.
  76836. this._shadowMap.renderList = renderList;
  76837. };
  76838. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  76839. if (this._shadowMap2) {
  76840. this._shadowMap2.dispose();
  76841. this._shadowMap2 = null;
  76842. }
  76843. if (this._boxBlurPostprocess) {
  76844. this._boxBlurPostprocess.dispose();
  76845. this._boxBlurPostprocess = null;
  76846. }
  76847. if (this._kernelBlurXPostprocess) {
  76848. this._kernelBlurXPostprocess.dispose();
  76849. this._kernelBlurXPostprocess = null;
  76850. }
  76851. if (this._kernelBlurYPostprocess) {
  76852. this._kernelBlurYPostprocess.dispose();
  76853. this._kernelBlurYPostprocess = null;
  76854. }
  76855. this._blurPostProcesses = [];
  76856. };
  76857. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  76858. if (this._shadowMap) {
  76859. this._shadowMap.dispose();
  76860. this._shadowMap = null;
  76861. }
  76862. this._disposeBlurPostProcesses();
  76863. };
  76864. /**
  76865. * Disposes the ShadowGenerator.
  76866. * Returns nothing.
  76867. */
  76868. ShadowGenerator.prototype.dispose = function () {
  76869. this._disposeRTTandPostProcesses();
  76870. if (this._light) {
  76871. this._light._shadowGenerator = null;
  76872. this._light._markMeshesAsLightDirty();
  76873. }
  76874. };
  76875. /**
  76876. * Serializes the shadow generator setup to a json object.
  76877. * @returns The serialized JSON object
  76878. */
  76879. ShadowGenerator.prototype.serialize = function () {
  76880. var serializationObject = {};
  76881. var shadowMap = this.getShadowMap();
  76882. if (!shadowMap) {
  76883. return serializationObject;
  76884. }
  76885. serializationObject.lightId = this._light.id;
  76886. serializationObject.mapSize = shadowMap.getRenderSize();
  76887. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  76888. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  76889. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76890. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76891. serializationObject.usePoissonSampling = this.usePoissonSampling;
  76892. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  76893. serializationObject.depthScale = this.depthScale;
  76894. serializationObject.darkness = this.getDarkness();
  76895. serializationObject.blurBoxOffset = this.blurBoxOffset;
  76896. serializationObject.blurKernel = this.blurKernel;
  76897. serializationObject.blurScale = this.blurScale;
  76898. serializationObject.useKernelBlur = this.useKernelBlur;
  76899. serializationObject.transparencyShadow = this._transparencyShadow;
  76900. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  76901. serializationObject.bias = this.bias;
  76902. serializationObject.normalBias = this.normalBias;
  76903. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  76904. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  76905. serializationObject.filteringQuality = this.filteringQuality;
  76906. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  76907. serializationObject.renderList = [];
  76908. if (shadowMap.renderList) {
  76909. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  76910. var mesh = shadowMap.renderList[meshIndex];
  76911. serializationObject.renderList.push(mesh.id);
  76912. }
  76913. }
  76914. return serializationObject;
  76915. };
  76916. /**
  76917. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  76918. * @param parsedShadowGenerator The JSON object to parse
  76919. * @param scene The scene to create the shadow map for
  76920. * @returns The parsed shadow generator
  76921. */
  76922. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  76923. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  76924. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  76925. var shadowMap = shadowGenerator.getShadowMap();
  76926. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  76927. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  76928. meshes.forEach(function (mesh) {
  76929. if (!shadowMap) {
  76930. return;
  76931. }
  76932. if (!shadowMap.renderList) {
  76933. shadowMap.renderList = [];
  76934. }
  76935. shadowMap.renderList.push(mesh);
  76936. });
  76937. }
  76938. if (parsedShadowGenerator.usePoissonSampling) {
  76939. shadowGenerator.usePoissonSampling = true;
  76940. }
  76941. else if (parsedShadowGenerator.useExponentialShadowMap) {
  76942. shadowGenerator.useExponentialShadowMap = true;
  76943. }
  76944. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  76945. shadowGenerator.useBlurExponentialShadowMap = true;
  76946. }
  76947. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  76948. shadowGenerator.useCloseExponentialShadowMap = true;
  76949. }
  76950. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  76951. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  76952. }
  76953. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  76954. shadowGenerator.usePercentageCloserFiltering = true;
  76955. }
  76956. else if (parsedShadowGenerator.useContactHardeningShadow) {
  76957. shadowGenerator.useContactHardeningShadow = true;
  76958. }
  76959. if (parsedShadowGenerator.filteringQuality) {
  76960. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  76961. }
  76962. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  76963. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  76964. }
  76965. // Backward compat
  76966. else if (parsedShadowGenerator.useVarianceShadowMap) {
  76967. shadowGenerator.useExponentialShadowMap = true;
  76968. }
  76969. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  76970. shadowGenerator.useBlurExponentialShadowMap = true;
  76971. }
  76972. if (parsedShadowGenerator.depthScale) {
  76973. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  76974. }
  76975. if (parsedShadowGenerator.blurScale) {
  76976. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  76977. }
  76978. if (parsedShadowGenerator.blurBoxOffset) {
  76979. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  76980. }
  76981. if (parsedShadowGenerator.useKernelBlur) {
  76982. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  76983. }
  76984. if (parsedShadowGenerator.blurKernel) {
  76985. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  76986. }
  76987. if (parsedShadowGenerator.bias !== undefined) {
  76988. shadowGenerator.bias = parsedShadowGenerator.bias;
  76989. }
  76990. if (parsedShadowGenerator.normalBias !== undefined) {
  76991. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  76992. }
  76993. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  76994. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  76995. }
  76996. if (parsedShadowGenerator.darkness) {
  76997. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  76998. }
  76999. if (parsedShadowGenerator.transparencyShadow) {
  77000. shadowGenerator.setTransparencyShadow(true);
  77001. }
  77002. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  77003. return shadowGenerator;
  77004. };
  77005. /**
  77006. * Shadow generator mode None: no filtering applied.
  77007. */
  77008. ShadowGenerator.FILTER_NONE = 0;
  77009. /**
  77010. * Shadow generator mode ESM: Exponential Shadow Mapping.
  77011. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77012. */
  77013. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  77014. /**
  77015. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  77016. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  77017. */
  77018. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  77019. /**
  77020. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  77021. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77022. */
  77023. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77024. /**
  77025. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77026. * edge artifacts on steep falloff.
  77027. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77028. */
  77029. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77030. /**
  77031. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77032. * edge artifacts on steep falloff.
  77033. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77034. */
  77035. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77036. /**
  77037. * Shadow generator mode PCF: Percentage Closer Filtering
  77038. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77039. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77040. */
  77041. ShadowGenerator.FILTER_PCF = 6;
  77042. /**
  77043. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77044. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77045. * Contact Hardening
  77046. */
  77047. ShadowGenerator.FILTER_PCSS = 7;
  77048. /**
  77049. * Reserved for PCF and PCSS
  77050. * Highest Quality.
  77051. *
  77052. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77053. *
  77054. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77055. */
  77056. ShadowGenerator.QUALITY_HIGH = 0;
  77057. /**
  77058. * Reserved for PCF and PCSS
  77059. * Good tradeoff for quality/perf cross devices
  77060. *
  77061. * Execute PCF on a 3*3 kernel.
  77062. *
  77063. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77064. */
  77065. ShadowGenerator.QUALITY_MEDIUM = 1;
  77066. /**
  77067. * Reserved for PCF and PCSS
  77068. * The lowest quality but the fastest.
  77069. *
  77070. * Execute PCF on a 1*1 kernel.
  77071. *
  77072. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77073. */
  77074. ShadowGenerator.QUALITY_LOW = 2;
  77075. return ShadowGenerator;
  77076. }());
  77077. BABYLON.ShadowGenerator = ShadowGenerator;
  77078. })(BABYLON || (BABYLON = {}));
  77079. //# sourceMappingURL=babylon.shadowGenerator.js.map
  77080. var BABYLON;
  77081. (function (BABYLON) {
  77082. // Adds the parser to the scene parsers.
  77083. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77084. // Shadows
  77085. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77086. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77087. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77088. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77089. // SG would be available on their associated lights
  77090. }
  77091. }
  77092. });
  77093. /**
  77094. * Defines the shadow generator component responsible to manage any shadow generators
  77095. * in a given scene.
  77096. */
  77097. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77098. /**
  77099. * Creates a new instance of the component for the given scene
  77100. * @param scene Defines the scene to register the component in
  77101. */
  77102. function ShadowGeneratorSceneComponent(scene) {
  77103. /**
  77104. * The component name helpfull to identify the component in the list of scene components.
  77105. */
  77106. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77107. this.scene = scene;
  77108. }
  77109. /**
  77110. * Registers the component in a given scene
  77111. */
  77112. ShadowGeneratorSceneComponent.prototype.register = function () {
  77113. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77114. };
  77115. /**
  77116. * Rebuilds the elements related to this component in case of
  77117. * context lost for instance.
  77118. */
  77119. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77120. // Nothing To Do Here.
  77121. };
  77122. /**
  77123. * Serializes the component data to the specified json object
  77124. * @param serializationObject The object to serialize to
  77125. */
  77126. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77127. // Shadows
  77128. serializationObject.shadowGenerators = [];
  77129. var lights = this.scene.lights;
  77130. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77131. var light = lights_1[_i];
  77132. var shadowGenerator = light.getShadowGenerator();
  77133. if (shadowGenerator) {
  77134. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77135. }
  77136. }
  77137. };
  77138. /**
  77139. * Adds all the element from the container to the scene
  77140. * @param container the container holding the elements
  77141. */
  77142. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77143. // Nothing To Do Here. (directly attached to a light)
  77144. };
  77145. /**
  77146. * Removes all the elements in the container from the scene
  77147. * @param container contains the elements to remove
  77148. */
  77149. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77150. // Nothing To Do Here. (directly attached to a light)
  77151. };
  77152. /**
  77153. * Rebuilds the elements related to this component in case of
  77154. * context lost for instance.
  77155. */
  77156. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77157. // Nothing To Do Here.
  77158. };
  77159. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77160. // Shadows
  77161. var scene = this.scene;
  77162. if (this.scene.shadowsEnabled) {
  77163. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77164. var light = scene.lights[lightIndex];
  77165. var shadowGenerator = light.getShadowGenerator();
  77166. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77167. var shadowMap = (shadowGenerator.getShadowMap());
  77168. if (scene.textures.indexOf(shadowMap) !== -1) {
  77169. renderTargets.push(shadowMap);
  77170. }
  77171. }
  77172. }
  77173. }
  77174. };
  77175. return ShadowGeneratorSceneComponent;
  77176. }());
  77177. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77178. })(BABYLON || (BABYLON = {}));
  77179. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  77180. var BABYLON;
  77181. (function (BABYLON) {
  77182. /**
  77183. * Class used for the default loading screen
  77184. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77185. */
  77186. var DefaultLoadingScreen = /** @class */ (function () {
  77187. /**
  77188. * Creates a new default loading screen
  77189. * @param _renderingCanvas defines the canvas used to render the scene
  77190. * @param _loadingText defines the default text to display
  77191. * @param _loadingDivBackgroundColor defines the default background color
  77192. */
  77193. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77194. if (_loadingText === void 0) { _loadingText = ""; }
  77195. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77196. var _this = this;
  77197. this._renderingCanvas = _renderingCanvas;
  77198. this._loadingText = _loadingText;
  77199. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77200. // Resize
  77201. this._resizeLoadingUI = function () {
  77202. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77203. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77204. if (!_this._loadingDiv) {
  77205. return;
  77206. }
  77207. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77208. _this._loadingDiv.style.left = canvasRect.left + "px";
  77209. _this._loadingDiv.style.top = canvasRect.top + "px";
  77210. _this._loadingDiv.style.width = canvasRect.width + "px";
  77211. _this._loadingDiv.style.height = canvasRect.height + "px";
  77212. };
  77213. }
  77214. /**
  77215. * Function called to display the loading screen
  77216. */
  77217. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77218. if (this._loadingDiv) {
  77219. // Do not add a loading screen if there is already one
  77220. return;
  77221. }
  77222. this._loadingDiv = document.createElement("div");
  77223. this._loadingDiv.id = "babylonjsLoadingDiv";
  77224. this._loadingDiv.style.opacity = "0";
  77225. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77226. this._loadingDiv.style.pointerEvents = "none";
  77227. // Loading text
  77228. this._loadingTextDiv = document.createElement("div");
  77229. this._loadingTextDiv.style.position = "absolute";
  77230. this._loadingTextDiv.style.left = "0";
  77231. this._loadingTextDiv.style.top = "50%";
  77232. this._loadingTextDiv.style.marginTop = "80px";
  77233. this._loadingTextDiv.style.width = "100%";
  77234. this._loadingTextDiv.style.height = "20px";
  77235. this._loadingTextDiv.style.fontFamily = "Arial";
  77236. this._loadingTextDiv.style.fontSize = "14px";
  77237. this._loadingTextDiv.style.color = "white";
  77238. this._loadingTextDiv.style.textAlign = "center";
  77239. this._loadingTextDiv.innerHTML = "Loading";
  77240. this._loadingDiv.appendChild(this._loadingTextDiv);
  77241. //set the predefined text
  77242. this._loadingTextDiv.innerHTML = this._loadingText;
  77243. // Generating keyframes
  77244. var style = document.createElement('style');
  77245. style.type = 'text/css';
  77246. 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 }";
  77247. style.innerHTML = keyFrames;
  77248. document.getElementsByTagName('head')[0].appendChild(style);
  77249. // Loading img
  77250. var imgBack = new Image();
  77251. 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";
  77252. imgBack.style.position = "absolute";
  77253. imgBack.style.left = "50%";
  77254. imgBack.style.top = "50%";
  77255. imgBack.style.marginLeft = "-60px";
  77256. imgBack.style.marginTop = "-60px";
  77257. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77258. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77259. imgBack.style.transformOrigin = "50% 50%";
  77260. imgBack.style.webkitTransformOrigin = "50% 50%";
  77261. this._loadingDiv.appendChild(imgBack);
  77262. this._resizeLoadingUI();
  77263. window.addEventListener("resize", this._resizeLoadingUI);
  77264. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77265. document.body.appendChild(this._loadingDiv);
  77266. this._loadingDiv.style.opacity = "1";
  77267. };
  77268. /**
  77269. * Function called to hide the loading screen
  77270. */
  77271. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77272. var _this = this;
  77273. if (!this._loadingDiv) {
  77274. return;
  77275. }
  77276. var onTransitionEnd = function () {
  77277. if (!_this._loadingDiv) {
  77278. return;
  77279. }
  77280. document.body.removeChild(_this._loadingDiv);
  77281. window.removeEventListener("resize", _this._resizeLoadingUI);
  77282. _this._loadingDiv = null;
  77283. };
  77284. this._loadingDiv.style.opacity = "0";
  77285. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77286. };
  77287. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77288. get: function () {
  77289. return this._loadingText;
  77290. },
  77291. /**
  77292. * Gets or sets the text to display while loading
  77293. */
  77294. set: function (text) {
  77295. this._loadingText = text;
  77296. if (this._loadingTextDiv) {
  77297. this._loadingTextDiv.innerHTML = this._loadingText;
  77298. }
  77299. },
  77300. enumerable: true,
  77301. configurable: true
  77302. });
  77303. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77304. /**
  77305. * Gets or sets the color to use for the background
  77306. */
  77307. get: function () {
  77308. return this._loadingDivBackgroundColor;
  77309. },
  77310. set: function (color) {
  77311. this._loadingDivBackgroundColor = color;
  77312. if (!this._loadingDiv) {
  77313. return;
  77314. }
  77315. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77316. },
  77317. enumerable: true,
  77318. configurable: true
  77319. });
  77320. return DefaultLoadingScreen;
  77321. }());
  77322. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77323. })(BABYLON || (BABYLON = {}));
  77324. //# sourceMappingURL=babylon.loadingScreen.js.map
  77325. var BABYLON;
  77326. (function (BABYLON) {
  77327. /**
  77328. * Class used to represent data loading progression
  77329. */
  77330. var SceneLoaderProgressEvent = /** @class */ (function () {
  77331. /**
  77332. * Create a new progress event
  77333. * @param lengthComputable defines if data length to load can be evaluated
  77334. * @param loaded defines the loaded data length
  77335. * @param total defines the data length to load
  77336. */
  77337. function SceneLoaderProgressEvent(
  77338. /** defines if data length to load can be evaluated */
  77339. lengthComputable,
  77340. /** defines the loaded data length */
  77341. loaded,
  77342. /** defines the data length to load */
  77343. total) {
  77344. this.lengthComputable = lengthComputable;
  77345. this.loaded = loaded;
  77346. this.total = total;
  77347. }
  77348. /**
  77349. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77350. * @param event defines the source event
  77351. * @returns a new SceneLoaderProgressEvent
  77352. */
  77353. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77354. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77355. };
  77356. return SceneLoaderProgressEvent;
  77357. }());
  77358. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77359. /**
  77360. * Class used to load scene from various file formats using registered plugins
  77361. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77362. */
  77363. var SceneLoader = /** @class */ (function () {
  77364. function SceneLoader() {
  77365. }
  77366. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77367. /**
  77368. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77369. */
  77370. get: function () {
  77371. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77372. },
  77373. set: function (value) {
  77374. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77375. },
  77376. enumerable: true,
  77377. configurable: true
  77378. });
  77379. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77380. /**
  77381. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77382. */
  77383. get: function () {
  77384. return SceneLoader._ShowLoadingScreen;
  77385. },
  77386. set: function (value) {
  77387. SceneLoader._ShowLoadingScreen = value;
  77388. },
  77389. enumerable: true,
  77390. configurable: true
  77391. });
  77392. Object.defineProperty(SceneLoader, "loggingLevel", {
  77393. /**
  77394. * Defines the current logging level (while loading the scene)
  77395. * @ignorenaming
  77396. */
  77397. get: function () {
  77398. return SceneLoader._loggingLevel;
  77399. },
  77400. set: function (value) {
  77401. SceneLoader._loggingLevel = value;
  77402. },
  77403. enumerable: true,
  77404. configurable: true
  77405. });
  77406. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77407. /**
  77408. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77409. */
  77410. get: function () {
  77411. return SceneLoader._CleanBoneMatrixWeights;
  77412. },
  77413. set: function (value) {
  77414. SceneLoader._CleanBoneMatrixWeights = value;
  77415. },
  77416. enumerable: true,
  77417. configurable: true
  77418. });
  77419. SceneLoader._getDefaultPlugin = function () {
  77420. return SceneLoader._registeredPlugins[".babylon"];
  77421. };
  77422. SceneLoader._getPluginForExtension = function (extension) {
  77423. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77424. if (registeredPlugin) {
  77425. return registeredPlugin;
  77426. }
  77427. 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");
  77428. return SceneLoader._getDefaultPlugin();
  77429. };
  77430. SceneLoader._getPluginForDirectLoad = function (data) {
  77431. for (var extension in SceneLoader._registeredPlugins) {
  77432. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  77433. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  77434. return SceneLoader._registeredPlugins[extension];
  77435. }
  77436. }
  77437. return SceneLoader._getDefaultPlugin();
  77438. };
  77439. SceneLoader._getPluginForFilename = function (sceneFilename) {
  77440. var queryStringPosition = sceneFilename.indexOf("?");
  77441. if (queryStringPosition !== -1) {
  77442. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  77443. }
  77444. var dotPosition = sceneFilename.lastIndexOf(".");
  77445. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  77446. return SceneLoader._getPluginForExtension(extension);
  77447. };
  77448. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  77449. SceneLoader._getDirectLoad = function (sceneFilename) {
  77450. if (sceneFilename.substr(0, 5) === "data:") {
  77451. return sceneFilename.substr(5);
  77452. }
  77453. return null;
  77454. };
  77455. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  77456. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  77457. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  77458. var plugin;
  77459. if (registeredPlugin.plugin.createPlugin) {
  77460. plugin = registeredPlugin.plugin.createPlugin();
  77461. }
  77462. else {
  77463. plugin = registeredPlugin.plugin;
  77464. }
  77465. var useArrayBuffer = registeredPlugin.isBinary;
  77466. var offlineProvider;
  77467. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  77468. var dataCallback = function (data, responseURL) {
  77469. if (scene.isDisposed) {
  77470. onError("Scene has been disposed");
  77471. return;
  77472. }
  77473. scene.offlineProvider = offlineProvider;
  77474. onSuccess(plugin, data, responseURL);
  77475. };
  77476. var request = null;
  77477. var pluginDisposed = false;
  77478. var onDisposeObservable = plugin.onDisposeObservable;
  77479. if (onDisposeObservable) {
  77480. onDisposeObservable.add(function () {
  77481. pluginDisposed = true;
  77482. if (request) {
  77483. request.abort();
  77484. request = null;
  77485. }
  77486. onDispose();
  77487. });
  77488. }
  77489. var manifestChecked = function () {
  77490. if (pluginDisposed) {
  77491. return;
  77492. }
  77493. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  77494. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  77495. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  77496. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  77497. });
  77498. };
  77499. if (directLoad) {
  77500. dataCallback(directLoad);
  77501. return plugin;
  77502. }
  77503. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  77504. var engine = scene.getEngine();
  77505. var canUseOfflineSupport = engine.enableOfflineSupport;
  77506. if (canUseOfflineSupport) {
  77507. // Also check for exceptions
  77508. var exceptionFound = false;
  77509. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  77510. var regex = _a[_i];
  77511. if (regex.test(fileInfo.url)) {
  77512. exceptionFound = true;
  77513. break;
  77514. }
  77515. }
  77516. canUseOfflineSupport = !exceptionFound;
  77517. }
  77518. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  77519. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  77520. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  77521. }
  77522. else {
  77523. manifestChecked();
  77524. }
  77525. }
  77526. // Loading file from disk via input file or drag'n'drop
  77527. else {
  77528. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  77529. if (file) {
  77530. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  77531. }
  77532. else {
  77533. onError("Unable to find file named " + fileInfo.name);
  77534. }
  77535. }
  77536. return plugin;
  77537. };
  77538. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  77539. var url;
  77540. var name;
  77541. if (!sceneFilename) {
  77542. url = rootUrl;
  77543. name = BABYLON.Tools.GetFilename(rootUrl);
  77544. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  77545. }
  77546. else {
  77547. if (sceneFilename.substr(0, 1) === "/") {
  77548. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  77549. return null;
  77550. }
  77551. url = rootUrl + sceneFilename;
  77552. name = sceneFilename;
  77553. }
  77554. return {
  77555. url: url,
  77556. rootUrl: rootUrl,
  77557. name: name
  77558. };
  77559. };
  77560. // Public functions
  77561. /**
  77562. * Gets a plugin that can load the given extension
  77563. * @param extension defines the extension to load
  77564. * @returns a plugin or null if none works
  77565. */
  77566. SceneLoader.GetPluginForExtension = function (extension) {
  77567. return SceneLoader._getPluginForExtension(extension).plugin;
  77568. };
  77569. /**
  77570. * Gets a boolean indicating that the given extension can be loaded
  77571. * @param extension defines the extension to load
  77572. * @returns true if the extension is supported
  77573. */
  77574. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  77575. return !!SceneLoader._registeredPlugins[extension];
  77576. };
  77577. /**
  77578. * Adds a new plugin to the list of registered plugins
  77579. * @param plugin defines the plugin to add
  77580. */
  77581. SceneLoader.RegisterPlugin = function (plugin) {
  77582. if (typeof plugin.extensions === "string") {
  77583. var extension = plugin.extensions;
  77584. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77585. plugin: plugin,
  77586. isBinary: false
  77587. };
  77588. }
  77589. else {
  77590. var extensions = plugin.extensions;
  77591. Object.keys(extensions).forEach(function (extension) {
  77592. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77593. plugin: plugin,
  77594. isBinary: extensions[extension].isBinary
  77595. };
  77596. });
  77597. }
  77598. };
  77599. /**
  77600. * Import meshes into a scene
  77601. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77602. * @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)
  77603. * @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)
  77604. * @param scene the instance of BABYLON.Scene to append to
  77605. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  77606. * @param onProgress a callback with a progress event for each file being loaded
  77607. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77608. * @param pluginExtension the extension used to determine the plugin
  77609. * @returns The loaded plugin
  77610. */
  77611. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77612. if (sceneFilename === void 0) { sceneFilename = ""; }
  77613. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77614. if (onSuccess === void 0) { onSuccess = null; }
  77615. if (onProgress === void 0) { onProgress = null; }
  77616. if (onError === void 0) { onError = null; }
  77617. if (pluginExtension === void 0) { pluginExtension = null; }
  77618. if (!scene) {
  77619. BABYLON.Tools.Error("No scene available to import mesh to");
  77620. return null;
  77621. }
  77622. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77623. if (!fileInfo) {
  77624. return null;
  77625. }
  77626. var loadingToken = {};
  77627. scene._addPendingData(loadingToken);
  77628. var disposeHandler = function () {
  77629. scene._removePendingData(loadingToken);
  77630. };
  77631. var errorHandler = function (message, exception) {
  77632. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  77633. if (onError) {
  77634. onError(scene, errorMessage, exception);
  77635. }
  77636. else {
  77637. BABYLON.Tools.Error(errorMessage);
  77638. // should the exception be thrown?
  77639. }
  77640. disposeHandler();
  77641. };
  77642. var progressHandler = onProgress ? function (event) {
  77643. try {
  77644. onProgress(event);
  77645. }
  77646. catch (e) {
  77647. errorHandler("Error in onProgress callback", e);
  77648. }
  77649. } : undefined;
  77650. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  77651. scene.importedMeshesFiles.push(fileInfo.url);
  77652. if (onSuccess) {
  77653. try {
  77654. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  77655. }
  77656. catch (e) {
  77657. errorHandler("Error in onSuccess callback", e);
  77658. }
  77659. }
  77660. scene._removePendingData(loadingToken);
  77661. };
  77662. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77663. if (plugin.rewriteRootURL) {
  77664. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  77665. }
  77666. if (plugin.importMesh) {
  77667. var syncedPlugin = plugin;
  77668. var meshes = new Array();
  77669. var particleSystems = new Array();
  77670. var skeletons = new Array();
  77671. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  77672. return;
  77673. }
  77674. scene.loadingPluginName = plugin.name;
  77675. successHandler(meshes, particleSystems, skeletons, []);
  77676. }
  77677. else {
  77678. var asyncedPlugin = plugin;
  77679. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  77680. scene.loadingPluginName = plugin.name;
  77681. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  77682. }).catch(function (error) {
  77683. errorHandler(error.message, error);
  77684. });
  77685. }
  77686. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77687. };
  77688. /**
  77689. * Import meshes into a scene
  77690. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77691. * @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)
  77692. * @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)
  77693. * @param scene the instance of BABYLON.Scene to append to
  77694. * @param onProgress a callback with a progress event for each file being loaded
  77695. * @param pluginExtension the extension used to determine the plugin
  77696. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  77697. */
  77698. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77699. if (sceneFilename === void 0) { sceneFilename = ""; }
  77700. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77701. if (onProgress === void 0) { onProgress = null; }
  77702. if (pluginExtension === void 0) { pluginExtension = null; }
  77703. return new Promise(function (resolve, reject) {
  77704. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  77705. resolve({
  77706. meshes: meshes,
  77707. particleSystems: particleSystems,
  77708. skeletons: skeletons,
  77709. animationGroups: animationGroups
  77710. });
  77711. }, onProgress, function (scene, message, exception) {
  77712. reject(exception || new Error(message));
  77713. }, pluginExtension);
  77714. });
  77715. };
  77716. /**
  77717. * Load a scene
  77718. * @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)
  77719. * @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)
  77720. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77721. * @param onSuccess a callback with the scene when import succeeds
  77722. * @param onProgress a callback with a progress event for each file being loaded
  77723. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77724. * @param pluginExtension the extension used to determine the plugin
  77725. * @returns The loaded plugin
  77726. */
  77727. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  77728. if (onSuccess === void 0) { onSuccess = null; }
  77729. if (onProgress === void 0) { onProgress = null; }
  77730. if (onError === void 0) { onError = null; }
  77731. if (pluginExtension === void 0) { pluginExtension = null; }
  77732. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  77733. };
  77734. /**
  77735. * Load a scene
  77736. * @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)
  77737. * @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)
  77738. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77739. * @param onProgress a callback with a progress event for each file being loaded
  77740. * @param pluginExtension the extension used to determine the plugin
  77741. * @returns The loaded scene
  77742. */
  77743. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  77744. if (onProgress === void 0) { onProgress = null; }
  77745. if (pluginExtension === void 0) { pluginExtension = null; }
  77746. return new Promise(function (resolve, reject) {
  77747. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  77748. resolve(scene);
  77749. }, onProgress, function (scene, message, exception) {
  77750. reject(exception || new Error(message));
  77751. }, pluginExtension);
  77752. });
  77753. };
  77754. /**
  77755. * Append a scene
  77756. * @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)
  77757. * @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)
  77758. * @param scene is the instance of BABYLON.Scene to append to
  77759. * @param onSuccess a callback with the scene when import succeeds
  77760. * @param onProgress a callback with a progress event for each file being loaded
  77761. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77762. * @param pluginExtension the extension used to determine the plugin
  77763. * @returns The loaded plugin
  77764. */
  77765. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77766. if (sceneFilename === void 0) { sceneFilename = ""; }
  77767. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77768. if (onSuccess === void 0) { onSuccess = null; }
  77769. if (onProgress === void 0) { onProgress = null; }
  77770. if (onError === void 0) { onError = null; }
  77771. if (pluginExtension === void 0) { pluginExtension = null; }
  77772. if (!scene) {
  77773. BABYLON.Tools.Error("No scene available to append to");
  77774. return null;
  77775. }
  77776. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77777. if (!fileInfo) {
  77778. return null;
  77779. }
  77780. if (SceneLoader.ShowLoadingScreen) {
  77781. scene.getEngine().displayLoadingUI();
  77782. }
  77783. var loadingToken = {};
  77784. scene._addPendingData(loadingToken);
  77785. var disposeHandler = function () {
  77786. scene._removePendingData(loadingToken);
  77787. scene.getEngine().hideLoadingUI();
  77788. };
  77789. var errorHandler = function (message, exception) {
  77790. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  77791. if (onError) {
  77792. onError(scene, errorMessage, exception);
  77793. }
  77794. else {
  77795. BABYLON.Tools.Error(errorMessage);
  77796. // should the exception be thrown?
  77797. }
  77798. disposeHandler();
  77799. };
  77800. var progressHandler = onProgress ? function (event) {
  77801. try {
  77802. onProgress(event);
  77803. }
  77804. catch (e) {
  77805. errorHandler("Error in onProgress callback", e);
  77806. }
  77807. } : undefined;
  77808. var successHandler = function () {
  77809. if (onSuccess) {
  77810. try {
  77811. onSuccess(scene);
  77812. }
  77813. catch (e) {
  77814. errorHandler("Error in onSuccess callback", e);
  77815. }
  77816. }
  77817. scene._removePendingData(loadingToken);
  77818. };
  77819. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77820. if (plugin.load) {
  77821. var syncedPlugin = plugin;
  77822. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  77823. return;
  77824. }
  77825. scene.loadingPluginName = plugin.name;
  77826. successHandler();
  77827. }
  77828. else {
  77829. var asyncedPlugin = plugin;
  77830. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  77831. scene.loadingPluginName = plugin.name;
  77832. successHandler();
  77833. }).catch(function (error) {
  77834. errorHandler(error.message, error);
  77835. });
  77836. }
  77837. if (SceneLoader.ShowLoadingScreen) {
  77838. scene.executeWhenReady(function () {
  77839. scene.getEngine().hideLoadingUI();
  77840. });
  77841. }
  77842. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77843. };
  77844. /**
  77845. * Append a scene
  77846. * @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)
  77847. * @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)
  77848. * @param scene is the instance of BABYLON.Scene to append to
  77849. * @param onProgress a callback with a progress event for each file being loaded
  77850. * @param pluginExtension the extension used to determine the plugin
  77851. * @returns The given scene
  77852. */
  77853. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77854. if (sceneFilename === void 0) { sceneFilename = ""; }
  77855. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77856. if (onProgress === void 0) { onProgress = null; }
  77857. if (pluginExtension === void 0) { pluginExtension = null; }
  77858. return new Promise(function (resolve, reject) {
  77859. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  77860. resolve(scene);
  77861. }, onProgress, function (scene, message, exception) {
  77862. reject(exception || new Error(message));
  77863. }, pluginExtension);
  77864. });
  77865. };
  77866. /**
  77867. * Load a scene into an asset container
  77868. * @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)
  77869. * @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)
  77870. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  77871. * @param onSuccess a callback with the scene when import succeeds
  77872. * @param onProgress a callback with a progress event for each file being loaded
  77873. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77874. * @param pluginExtension the extension used to determine the plugin
  77875. * @returns The loaded plugin
  77876. */
  77877. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77878. if (sceneFilename === void 0) { sceneFilename = ""; }
  77879. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77880. if (onSuccess === void 0) { onSuccess = null; }
  77881. if (onProgress === void 0) { onProgress = null; }
  77882. if (onError === void 0) { onError = null; }
  77883. if (pluginExtension === void 0) { pluginExtension = null; }
  77884. if (!scene) {
  77885. BABYLON.Tools.Error("No scene available to load asset container to");
  77886. return null;
  77887. }
  77888. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77889. if (!fileInfo) {
  77890. return null;
  77891. }
  77892. var loadingToken = {};
  77893. scene._addPendingData(loadingToken);
  77894. var disposeHandler = function () {
  77895. scene._removePendingData(loadingToken);
  77896. };
  77897. var errorHandler = function (message, exception) {
  77898. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  77899. if (onError) {
  77900. onError(scene, errorMessage, exception);
  77901. }
  77902. else {
  77903. BABYLON.Tools.Error(errorMessage);
  77904. // should the exception be thrown?
  77905. }
  77906. disposeHandler();
  77907. };
  77908. var progressHandler = onProgress ? function (event) {
  77909. try {
  77910. onProgress(event);
  77911. }
  77912. catch (e) {
  77913. errorHandler("Error in onProgress callback", e);
  77914. }
  77915. } : undefined;
  77916. var successHandler = function (assets) {
  77917. if (onSuccess) {
  77918. try {
  77919. onSuccess(assets);
  77920. }
  77921. catch (e) {
  77922. errorHandler("Error in onSuccess callback", e);
  77923. }
  77924. }
  77925. scene._removePendingData(loadingToken);
  77926. };
  77927. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77928. if (plugin.loadAssetContainer) {
  77929. var syncedPlugin = plugin;
  77930. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  77931. if (!assetContainer) {
  77932. return;
  77933. }
  77934. scene.loadingPluginName = plugin.name;
  77935. successHandler(assetContainer);
  77936. }
  77937. else if (plugin.loadAssetContainerAsync) {
  77938. var asyncedPlugin = plugin;
  77939. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  77940. scene.loadingPluginName = plugin.name;
  77941. successHandler(assetContainer);
  77942. }).catch(function (error) {
  77943. errorHandler(error.message, error);
  77944. });
  77945. }
  77946. else {
  77947. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  77948. }
  77949. if (SceneLoader.ShowLoadingScreen) {
  77950. scene.executeWhenReady(function () {
  77951. scene.getEngine().hideLoadingUI();
  77952. });
  77953. }
  77954. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77955. };
  77956. /**
  77957. * Load a scene into an asset container
  77958. * @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)
  77959. * @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)
  77960. * @param scene is the instance of BABYLON.Scene to append to
  77961. * @param onProgress a callback with a progress event for each file being loaded
  77962. * @param pluginExtension the extension used to determine the plugin
  77963. * @returns The loaded asset container
  77964. */
  77965. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77966. if (sceneFilename === void 0) { sceneFilename = ""; }
  77967. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77968. if (onProgress === void 0) { onProgress = null; }
  77969. if (pluginExtension === void 0) { pluginExtension = null; }
  77970. return new Promise(function (resolve, reject) {
  77971. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  77972. resolve(assetContainer);
  77973. }, onProgress, function (scene, message, exception) {
  77974. reject(exception || new Error(message));
  77975. }, pluginExtension);
  77976. });
  77977. };
  77978. // Flags
  77979. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  77980. SceneLoader._ShowLoadingScreen = true;
  77981. SceneLoader._CleanBoneMatrixWeights = false;
  77982. /**
  77983. * No logging while loading
  77984. */
  77985. SceneLoader.NO_LOGGING = 0;
  77986. /**
  77987. * Minimal logging while loading
  77988. */
  77989. SceneLoader.MINIMAL_LOGGING = 1;
  77990. /**
  77991. * Summary logging while loading
  77992. */
  77993. SceneLoader.SUMMARY_LOGGING = 2;
  77994. /**
  77995. * Detailled logging while loading
  77996. */
  77997. SceneLoader.DETAILED_LOGGING = 3;
  77998. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  77999. // Members
  78000. /**
  78001. * Event raised when a plugin is used to load a scene
  78002. */
  78003. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  78004. SceneLoader._registeredPlugins = {};
  78005. return SceneLoader;
  78006. }());
  78007. BABYLON.SceneLoader = SceneLoader;
  78008. })(BABYLON || (BABYLON = {}));
  78009. //# sourceMappingURL=babylon.sceneLoader.js.map
  78010. var BABYLON;
  78011. (function (BABYLON) {
  78012. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  78013. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78014. var parsedMaterial = parsedData.materials[index];
  78015. if (parsedMaterial.id === id) {
  78016. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78017. }
  78018. }
  78019. return null;
  78020. };
  78021. var isDescendantOf = function (mesh, names, hierarchyIds) {
  78022. for (var i in names) {
  78023. if (mesh.name === names[i]) {
  78024. hierarchyIds.push(mesh.id);
  78025. return true;
  78026. }
  78027. }
  78028. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78029. hierarchyIds.push(mesh.id);
  78030. return true;
  78031. }
  78032. return false;
  78033. };
  78034. var logOperation = function (operation, producer) {
  78035. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78036. };
  78037. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78038. if (addToScene === void 0) { addToScene = false; }
  78039. var container = new BABYLON.AssetContainer(scene);
  78040. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78041. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78042. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78043. // and avoid problems with multiple concurrent .babylon loads.
  78044. var log = "importScene has failed JSON parse";
  78045. try {
  78046. var parsedData = JSON.parse(data);
  78047. log = "";
  78048. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78049. var index;
  78050. var cache;
  78051. // Lights
  78052. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78053. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78054. var parsedLight = parsedData.lights[index];
  78055. var light = BABYLON.Light.Parse(parsedLight, scene);
  78056. if (light) {
  78057. container.lights.push(light);
  78058. log += (index === 0 ? "\n\tLights:" : "");
  78059. log += "\n\t\t" + light.toString(fullDetails);
  78060. }
  78061. }
  78062. }
  78063. // Animations
  78064. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78065. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78066. var parsedAnimation = parsedData.animations[index];
  78067. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78068. scene.animations.push(animation);
  78069. container.animations.push(animation);
  78070. log += (index === 0 ? "\n\tAnimations:" : "");
  78071. log += "\n\t\t" + animation.toString(fullDetails);
  78072. }
  78073. }
  78074. // Materials
  78075. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78076. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78077. var parsedMaterial = parsedData.materials[index];
  78078. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78079. container.materials.push(mat);
  78080. log += (index === 0 ? "\n\tMaterials:" : "");
  78081. log += "\n\t\t" + mat.toString(fullDetails);
  78082. }
  78083. }
  78084. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78085. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78086. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78087. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78088. container.multiMaterials.push(mmat);
  78089. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78090. log += "\n\t\t" + mmat.toString(fullDetails);
  78091. }
  78092. }
  78093. // Morph targets
  78094. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78095. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78096. var managerData = _a[_i];
  78097. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78098. }
  78099. }
  78100. // Skeletons
  78101. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78102. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78103. var parsedSkeleton = parsedData.skeletons[index];
  78104. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78105. container.skeletons.push(skeleton);
  78106. log += (index === 0 ? "\n\tSkeletons:" : "");
  78107. log += "\n\t\t" + skeleton.toString(fullDetails);
  78108. }
  78109. }
  78110. // Geometries
  78111. var geometries = parsedData.geometries;
  78112. if (geometries !== undefined && geometries !== null) {
  78113. var addedGeometry = new Array();
  78114. // Boxes
  78115. var boxes = geometries.boxes;
  78116. if (boxes !== undefined && boxes !== null) {
  78117. for (index = 0, cache = boxes.length; index < cache; index++) {
  78118. var parsedBox = boxes[index];
  78119. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78120. }
  78121. }
  78122. // Spheres
  78123. var spheres = geometries.spheres;
  78124. if (spheres !== undefined && spheres !== null) {
  78125. for (index = 0, cache = spheres.length; index < cache; index++) {
  78126. var parsedSphere = spheres[index];
  78127. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78128. }
  78129. }
  78130. // Cylinders
  78131. var cylinders = geometries.cylinders;
  78132. if (cylinders !== undefined && cylinders !== null) {
  78133. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78134. var parsedCylinder = cylinders[index];
  78135. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78136. }
  78137. }
  78138. // Toruses
  78139. var toruses = geometries.toruses;
  78140. if (toruses !== undefined && toruses !== null) {
  78141. for (index = 0, cache = toruses.length; index < cache; index++) {
  78142. var parsedTorus = toruses[index];
  78143. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78144. }
  78145. }
  78146. // Grounds
  78147. var grounds = geometries.grounds;
  78148. if (grounds !== undefined && grounds !== null) {
  78149. for (index = 0, cache = grounds.length; index < cache; index++) {
  78150. var parsedGround = grounds[index];
  78151. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78152. }
  78153. }
  78154. // Planes
  78155. var planes = geometries.planes;
  78156. if (planes !== undefined && planes !== null) {
  78157. for (index = 0, cache = planes.length; index < cache; index++) {
  78158. var parsedPlane = planes[index];
  78159. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78160. }
  78161. }
  78162. // TorusKnots
  78163. var torusKnots = geometries.torusKnots;
  78164. if (torusKnots !== undefined && torusKnots !== null) {
  78165. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78166. var parsedTorusKnot = torusKnots[index];
  78167. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78168. }
  78169. }
  78170. // VertexData
  78171. var vertexData = geometries.vertexData;
  78172. if (vertexData !== undefined && vertexData !== null) {
  78173. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78174. var parsedVertexData = vertexData[index];
  78175. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78176. }
  78177. }
  78178. addedGeometry.forEach(function (g) {
  78179. if (g) {
  78180. container.geometries.push(g);
  78181. }
  78182. });
  78183. }
  78184. // Transform nodes
  78185. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78186. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78187. var parsedTransformNode = parsedData.transformNodes[index];
  78188. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78189. container.transformNodes.push(node);
  78190. }
  78191. }
  78192. // Meshes
  78193. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78194. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78195. var parsedMesh = parsedData.meshes[index];
  78196. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78197. container.meshes.push(mesh);
  78198. log += (index === 0 ? "\n\tMeshes:" : "");
  78199. log += "\n\t\t" + mesh.toString(fullDetails);
  78200. }
  78201. }
  78202. // Cameras
  78203. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78204. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78205. var parsedCamera = parsedData.cameras[index];
  78206. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78207. container.cameras.push(camera);
  78208. log += (index === 0 ? "\n\tCameras:" : "");
  78209. log += "\n\t\t" + camera.toString(fullDetails);
  78210. }
  78211. }
  78212. // Animation Groups
  78213. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78214. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78215. var parsedAnimationGroup = parsedData.animationGroups[index];
  78216. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78217. container.animationGroups.push(animationGroup);
  78218. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78219. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78220. }
  78221. }
  78222. // Browsing all the graph to connect the dots
  78223. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78224. var camera = scene.cameras[index];
  78225. if (camera._waitingParentId) {
  78226. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78227. camera._waitingParentId = null;
  78228. }
  78229. }
  78230. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78231. var light_1 = scene.lights[index];
  78232. if (light_1 && light_1._waitingParentId) {
  78233. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78234. light_1._waitingParentId = null;
  78235. }
  78236. }
  78237. // Connect parents & children and parse actions
  78238. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78239. var transformNode = scene.transformNodes[index];
  78240. if (transformNode._waitingParentId) {
  78241. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78242. transformNode._waitingParentId = null;
  78243. }
  78244. }
  78245. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78246. var mesh = scene.meshes[index];
  78247. if (mesh._waitingParentId) {
  78248. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78249. mesh._waitingParentId = null;
  78250. }
  78251. }
  78252. // freeze world matrix application
  78253. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78254. var currentMesh = scene.meshes[index];
  78255. if (currentMesh._waitingFreezeWorldMatrix) {
  78256. currentMesh.freezeWorldMatrix();
  78257. currentMesh._waitingFreezeWorldMatrix = null;
  78258. }
  78259. else {
  78260. currentMesh.computeWorldMatrix(true);
  78261. }
  78262. }
  78263. // Lights exclusions / inclusions
  78264. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78265. var light_2 = scene.lights[index];
  78266. // Excluded check
  78267. if (light_2._excludedMeshesIds.length > 0) {
  78268. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78269. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78270. if (excludedMesh) {
  78271. light_2.excludedMeshes.push(excludedMesh);
  78272. }
  78273. }
  78274. light_2._excludedMeshesIds = [];
  78275. }
  78276. // Included check
  78277. if (light_2._includedOnlyMeshesIds.length > 0) {
  78278. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78279. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78280. if (includedOnlyMesh) {
  78281. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78282. }
  78283. }
  78284. light_2._includedOnlyMeshesIds = [];
  78285. }
  78286. }
  78287. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78288. // Actions (scene) Done last as it can access other objects.
  78289. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78290. var mesh = scene.meshes[index];
  78291. if (mesh._waitingActions) {
  78292. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78293. mesh._waitingActions = null;
  78294. }
  78295. }
  78296. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78297. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78298. }
  78299. if (!addToScene) {
  78300. container.removeAllFromScene();
  78301. }
  78302. }
  78303. catch (err) {
  78304. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78305. if (onError) {
  78306. onError(msg, err);
  78307. }
  78308. else {
  78309. BABYLON.Tools.Log(msg);
  78310. throw err;
  78311. }
  78312. }
  78313. finally {
  78314. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78315. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78316. }
  78317. }
  78318. return container;
  78319. };
  78320. BABYLON.SceneLoader.RegisterPlugin({
  78321. name: "babylon.js",
  78322. extensions: ".babylon",
  78323. canDirectLoad: function (data) {
  78324. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78325. return true;
  78326. }
  78327. return false;
  78328. },
  78329. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78330. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78331. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78332. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78333. // and avoid problems with multiple concurrent .babylon loads.
  78334. var log = "importMesh has failed JSON parse";
  78335. try {
  78336. var parsedData = JSON.parse(data);
  78337. log = "";
  78338. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78339. if (!meshesNames) {
  78340. meshesNames = null;
  78341. }
  78342. else if (!Array.isArray(meshesNames)) {
  78343. meshesNames = [meshesNames];
  78344. }
  78345. var hierarchyIds = new Array();
  78346. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78347. var loadedSkeletonsIds = [];
  78348. var loadedMaterialsIds = [];
  78349. var index;
  78350. var cache;
  78351. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78352. var parsedMesh = parsedData.meshes[index];
  78353. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78354. if (meshesNames !== null) {
  78355. // Remove found mesh name from list.
  78356. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78357. }
  78358. //Geometry?
  78359. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78360. //does the file contain geometries?
  78361. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78362. //find the correct geometry and add it to the scene
  78363. var found = false;
  78364. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78365. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78366. return;
  78367. }
  78368. else {
  78369. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78370. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78371. switch (geometryType) {
  78372. case "boxes":
  78373. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78374. break;
  78375. case "spheres":
  78376. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78377. break;
  78378. case "cylinders":
  78379. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78380. break;
  78381. case "toruses":
  78382. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78383. break;
  78384. case "grounds":
  78385. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78386. break;
  78387. case "planes":
  78388. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78389. break;
  78390. case "torusKnots":
  78391. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78392. break;
  78393. case "vertexData":
  78394. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78395. break;
  78396. }
  78397. found = true;
  78398. }
  78399. });
  78400. }
  78401. });
  78402. if (found === false) {
  78403. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78404. }
  78405. }
  78406. }
  78407. // Material ?
  78408. if (parsedMesh.materialId) {
  78409. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78410. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78411. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78412. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78413. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78414. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78415. var subMatId = parsedMultiMaterial.materials[matIndex];
  78416. loadedMaterialsIds.push(subMatId);
  78417. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78418. if (mat) {
  78419. log += "\n\tMaterial " + mat.toString(fullDetails);
  78420. }
  78421. }
  78422. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78423. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78424. if (mmat) {
  78425. materialFound = true;
  78426. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78427. }
  78428. break;
  78429. }
  78430. }
  78431. }
  78432. if (materialFound === false) {
  78433. loadedMaterialsIds.push(parsedMesh.materialId);
  78434. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  78435. if (!mat) {
  78436. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  78437. }
  78438. else {
  78439. log += "\n\tMaterial " + mat.toString(fullDetails);
  78440. }
  78441. }
  78442. }
  78443. // Skeleton ?
  78444. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78445. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  78446. if (skeletonAlreadyLoaded === false) {
  78447. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  78448. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  78449. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  78450. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78451. skeletons.push(skeleton);
  78452. loadedSkeletonsIds.push(parsedSkeleton.id);
  78453. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  78454. }
  78455. }
  78456. }
  78457. }
  78458. // Morph targets ?
  78459. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78460. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78461. var managerData = _a[_i];
  78462. BABYLON.MorphTargetManager.Parse(managerData, scene);
  78463. }
  78464. }
  78465. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78466. meshes.push(mesh);
  78467. log += "\n\tMesh " + mesh.toString(fullDetails);
  78468. }
  78469. }
  78470. // Connecting parents
  78471. var currentMesh;
  78472. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78473. currentMesh = scene.meshes[index];
  78474. if (currentMesh._waitingParentId) {
  78475. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  78476. currentMesh._waitingParentId = null;
  78477. }
  78478. }
  78479. // freeze and compute world matrix application
  78480. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78481. currentMesh = scene.meshes[index];
  78482. if (currentMesh._waitingFreezeWorldMatrix) {
  78483. currentMesh.freezeWorldMatrix();
  78484. currentMesh._waitingFreezeWorldMatrix = null;
  78485. }
  78486. else {
  78487. currentMesh.computeWorldMatrix(true);
  78488. }
  78489. }
  78490. }
  78491. // Particles
  78492. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  78493. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  78494. if (parser) {
  78495. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  78496. var parsedParticleSystem = parsedData.particleSystems[index];
  78497. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  78498. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  78499. }
  78500. }
  78501. }
  78502. }
  78503. return true;
  78504. }
  78505. catch (err) {
  78506. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  78507. if (onError) {
  78508. onError(msg, err);
  78509. }
  78510. else {
  78511. BABYLON.Tools.Log(msg);
  78512. throw err;
  78513. }
  78514. }
  78515. finally {
  78516. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78517. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78518. }
  78519. }
  78520. return false;
  78521. },
  78522. load: function (scene, data, rootUrl, onError) {
  78523. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78524. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78525. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78526. // and avoid problems with multiple concurrent .babylon loads.
  78527. var log = "importScene has failed JSON parse";
  78528. try {
  78529. var parsedData = JSON.parse(data);
  78530. log = "";
  78531. // Scene
  78532. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  78533. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  78534. }
  78535. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  78536. scene.autoClear = parsedData.autoClear;
  78537. }
  78538. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  78539. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  78540. }
  78541. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  78542. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  78543. }
  78544. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  78545. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  78546. }
  78547. // Fog
  78548. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  78549. scene.fogMode = parsedData.fogMode;
  78550. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  78551. scene.fogStart = parsedData.fogStart;
  78552. scene.fogEnd = parsedData.fogEnd;
  78553. scene.fogDensity = parsedData.fogDensity;
  78554. log += "\tFog mode for scene: ";
  78555. switch (scene.fogMode) {
  78556. // getters not compiling, so using hardcoded
  78557. case 1:
  78558. log += "exp\n";
  78559. break;
  78560. case 2:
  78561. log += "exp2\n";
  78562. break;
  78563. case 3:
  78564. log += "linear\n";
  78565. break;
  78566. }
  78567. }
  78568. //Physics
  78569. if (parsedData.physicsEnabled) {
  78570. var physicsPlugin;
  78571. if (parsedData.physicsEngine === "cannon") {
  78572. physicsPlugin = new BABYLON.CannonJSPlugin();
  78573. }
  78574. else if (parsedData.physicsEngine === "oimo") {
  78575. physicsPlugin = new BABYLON.OimoJSPlugin();
  78576. }
  78577. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  78578. //else - default engine, which is currently oimo
  78579. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  78580. scene.enablePhysics(physicsGravity, physicsPlugin);
  78581. }
  78582. // Metadata
  78583. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  78584. scene.metadata = parsedData.metadata;
  78585. }
  78586. //collisions, if defined. otherwise, default is true
  78587. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  78588. scene.collisionsEnabled = parsedData.collisionsEnabled;
  78589. }
  78590. scene.workerCollisions = !!parsedData.workerCollisions;
  78591. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  78592. if (!container) {
  78593. return false;
  78594. }
  78595. if (parsedData.autoAnimate) {
  78596. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  78597. }
  78598. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  78599. scene.setActiveCameraByID(parsedData.activeCameraID);
  78600. }
  78601. // Environment texture
  78602. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  78603. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  78604. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  78605. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  78606. if (parsedData.environmentTextureRotationY) {
  78607. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  78608. }
  78609. scene.environmentTexture = hdrTexture;
  78610. }
  78611. else {
  78612. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  78613. if (parsedData.environmentTextureRotationY) {
  78614. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  78615. }
  78616. scene.environmentTexture = cubeTexture;
  78617. }
  78618. if (parsedData.createDefaultSkybox === true) {
  78619. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  78620. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  78621. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  78622. }
  78623. }
  78624. // Finish
  78625. return true;
  78626. }
  78627. catch (err) {
  78628. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  78629. if (onError) {
  78630. onError(msg, err);
  78631. }
  78632. else {
  78633. BABYLON.Tools.Log(msg);
  78634. throw err;
  78635. }
  78636. }
  78637. finally {
  78638. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78639. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78640. }
  78641. }
  78642. return false;
  78643. },
  78644. loadAssetContainer: function (scene, data, rootUrl, onError) {
  78645. var container = loadAssetContainer(scene, data, rootUrl, onError);
  78646. return container;
  78647. }
  78648. });
  78649. })(BABYLON || (BABYLON = {}));
  78650. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  78651. var BABYLON;
  78652. (function (BABYLON) {
  78653. /**
  78654. * Class used to help managing file picking and drag'n'drop
  78655. */
  78656. var FilesInput = /** @class */ (function () {
  78657. /**
  78658. * Creates a new FilesInput
  78659. * @param engine defines the rendering engine
  78660. * @param scene defines the hosting scene
  78661. * @param sceneLoadedCallback callback called when scene is loaded
  78662. * @param progressCallback callback called to track progress
  78663. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  78664. * @param textureLoadingCallback callback called when a texture is loading
  78665. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  78666. * @param onReloadCallback callback called when a reload is requested
  78667. * @param errorCallback callback call if an error occurs
  78668. */
  78669. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  78670. /**
  78671. * Callback called when a file is processed
  78672. */
  78673. this.onProcessFileCallback = function () { return true; };
  78674. this._engine = engine;
  78675. this._currentScene = scene;
  78676. this._sceneLoadedCallback = sceneLoadedCallback;
  78677. this._progressCallback = progressCallback;
  78678. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  78679. this._textureLoadingCallback = textureLoadingCallback;
  78680. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  78681. this._onReloadCallback = onReloadCallback;
  78682. this._errorCallback = errorCallback;
  78683. }
  78684. /**
  78685. * Calls this function to listen to drag'n'drop events on a specific DOM element
  78686. * @param elementToMonitor defines the DOM element to track
  78687. */
  78688. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  78689. var _this = this;
  78690. if (elementToMonitor) {
  78691. this._elementToMonitor = elementToMonitor;
  78692. this._dragEnterHandler = function (e) { _this.drag(e); };
  78693. this._dragOverHandler = function (e) { _this.drag(e); };
  78694. this._dropHandler = function (e) { _this.drop(e); };
  78695. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  78696. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78697. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  78698. }
  78699. };
  78700. /**
  78701. * Release all associated resources
  78702. */
  78703. FilesInput.prototype.dispose = function () {
  78704. if (!this._elementToMonitor) {
  78705. return;
  78706. }
  78707. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  78708. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  78709. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  78710. };
  78711. FilesInput.prototype.renderFunction = function () {
  78712. if (this._additionalRenderLoopLogicCallback) {
  78713. this._additionalRenderLoopLogicCallback();
  78714. }
  78715. if (this._currentScene) {
  78716. if (this._textureLoadingCallback) {
  78717. var remaining = this._currentScene.getWaitingItemsCount();
  78718. if (remaining > 0) {
  78719. this._textureLoadingCallback(remaining);
  78720. }
  78721. }
  78722. this._currentScene.render();
  78723. }
  78724. };
  78725. FilesInput.prototype.drag = function (e) {
  78726. e.stopPropagation();
  78727. e.preventDefault();
  78728. };
  78729. FilesInput.prototype.drop = function (eventDrop) {
  78730. eventDrop.stopPropagation();
  78731. eventDrop.preventDefault();
  78732. this.loadFiles(eventDrop);
  78733. };
  78734. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  78735. var _this = this;
  78736. var reader = folder.createReader();
  78737. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  78738. reader.readEntries(function (entries) {
  78739. remaining.count += entries.length;
  78740. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  78741. var entry = entries_1[_i];
  78742. if (entry.isFile) {
  78743. entry.file(function (file) {
  78744. file.correctName = relativePath + file.name;
  78745. files.push(file);
  78746. if (--remaining.count === 0) {
  78747. callback();
  78748. }
  78749. });
  78750. }
  78751. else if (entry.isDirectory) {
  78752. _this._traverseFolder(entry, files, remaining, callback);
  78753. }
  78754. }
  78755. if (--remaining.count) {
  78756. callback();
  78757. }
  78758. });
  78759. };
  78760. FilesInput.prototype._processFiles = function (files) {
  78761. for (var i = 0; i < files.length; i++) {
  78762. var name = files[i].correctName.toLowerCase();
  78763. var extension = name.split('.').pop();
  78764. if (!this.onProcessFileCallback(files[i], name, extension)) {
  78765. continue;
  78766. }
  78767. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  78768. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  78769. this._sceneFileToLoad = files[i];
  78770. }
  78771. FilesInput.FilesToLoad[name] = files[i];
  78772. }
  78773. };
  78774. /**
  78775. * Load files from a drop event
  78776. * @param event defines the drop event to use as source
  78777. */
  78778. FilesInput.prototype.loadFiles = function (event) {
  78779. var _this = this;
  78780. // Handling data transfer via drag'n'drop
  78781. if (event && event.dataTransfer && event.dataTransfer.files) {
  78782. this._filesToLoad = event.dataTransfer.files;
  78783. }
  78784. // Handling files from input files
  78785. if (event && event.target && event.target.files) {
  78786. this._filesToLoad = event.target.files;
  78787. }
  78788. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  78789. return;
  78790. }
  78791. if (this._startingProcessingFilesCallback) {
  78792. this._startingProcessingFilesCallback(this._filesToLoad);
  78793. }
  78794. if (this._filesToLoad && this._filesToLoad.length > 0) {
  78795. var files_1 = new Array();
  78796. var folders = [];
  78797. var items = event.dataTransfer ? event.dataTransfer.items : null;
  78798. for (var i = 0; i < this._filesToLoad.length; i++) {
  78799. var fileToLoad = this._filesToLoad[i];
  78800. var name_1 = fileToLoad.name.toLowerCase();
  78801. var entry = void 0;
  78802. fileToLoad.correctName = name_1;
  78803. if (items) {
  78804. var item = items[i];
  78805. if (item.getAsEntry) {
  78806. entry = item.getAsEntry();
  78807. }
  78808. else if (item.webkitGetAsEntry) {
  78809. entry = item.webkitGetAsEntry();
  78810. }
  78811. }
  78812. if (!entry) {
  78813. files_1.push(fileToLoad);
  78814. }
  78815. else {
  78816. if (entry.isDirectory) {
  78817. folders.push(entry);
  78818. }
  78819. else {
  78820. files_1.push(fileToLoad);
  78821. }
  78822. }
  78823. }
  78824. if (folders.length === 0) {
  78825. this._processFiles(files_1);
  78826. this._processReload();
  78827. }
  78828. else {
  78829. var remaining = { count: folders.length };
  78830. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  78831. var folder = folders_1[_i];
  78832. this._traverseFolder(folder, files_1, remaining, function () {
  78833. _this._processFiles(files_1);
  78834. if (remaining.count === 0) {
  78835. _this._processReload();
  78836. }
  78837. });
  78838. }
  78839. }
  78840. }
  78841. };
  78842. FilesInput.prototype._processReload = function () {
  78843. if (this._onReloadCallback) {
  78844. this._onReloadCallback(this._sceneFileToLoad);
  78845. }
  78846. else {
  78847. this.reload();
  78848. }
  78849. };
  78850. /**
  78851. * Reload the current scene from the loaded files
  78852. */
  78853. FilesInput.prototype.reload = function () {
  78854. var _this = this;
  78855. // If a scene file has been provided
  78856. if (this._sceneFileToLoad) {
  78857. if (this._currentScene) {
  78858. if (BABYLON.Tools.errorsCount > 0) {
  78859. BABYLON.Tools.ClearLogCache();
  78860. }
  78861. this._engine.stopRenderLoop();
  78862. }
  78863. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  78864. if (_this._progressCallback) {
  78865. _this._progressCallback(progress);
  78866. }
  78867. }).then(function (scene) {
  78868. if (_this._currentScene) {
  78869. _this._currentScene.dispose();
  78870. }
  78871. _this._currentScene = scene;
  78872. if (_this._sceneLoadedCallback) {
  78873. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  78874. }
  78875. // Wait for textures and shaders to be ready
  78876. _this._currentScene.executeWhenReady(function () {
  78877. _this._engine.runRenderLoop(function () {
  78878. _this.renderFunction();
  78879. });
  78880. });
  78881. }).catch(function (error) {
  78882. if (_this._errorCallback) {
  78883. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  78884. }
  78885. });
  78886. }
  78887. else {
  78888. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  78889. }
  78890. };
  78891. /**
  78892. * List of files ready to be loaded
  78893. */
  78894. FilesInput.FilesToLoad = {};
  78895. return FilesInput;
  78896. }());
  78897. BABYLON.FilesInput = FilesInput;
  78898. })(BABYLON || (BABYLON = {}));
  78899. //# sourceMappingURL=babylon.filesInput.js.map
  78900. var BABYLON;
  78901. (function (BABYLON) {
  78902. /**
  78903. * Class used to store custom tags
  78904. */
  78905. var Tags = /** @class */ (function () {
  78906. function Tags() {
  78907. }
  78908. /**
  78909. * Adds support for tags on the given object
  78910. * @param obj defines the object to use
  78911. */
  78912. Tags.EnableFor = function (obj) {
  78913. obj._tags = obj._tags || {};
  78914. obj.hasTags = function () {
  78915. return Tags.HasTags(obj);
  78916. };
  78917. obj.addTags = function (tagsString) {
  78918. return Tags.AddTagsTo(obj, tagsString);
  78919. };
  78920. obj.removeTags = function (tagsString) {
  78921. return Tags.RemoveTagsFrom(obj, tagsString);
  78922. };
  78923. obj.matchesTagsQuery = function (tagsQuery) {
  78924. return Tags.MatchesQuery(obj, tagsQuery);
  78925. };
  78926. };
  78927. /**
  78928. * Removes tags support
  78929. * @param obj defines the object to use
  78930. */
  78931. Tags.DisableFor = function (obj) {
  78932. delete obj._tags;
  78933. delete obj.hasTags;
  78934. delete obj.addTags;
  78935. delete obj.removeTags;
  78936. delete obj.matchesTagsQuery;
  78937. };
  78938. /**
  78939. * Gets a boolean indicating if the given object has tags
  78940. * @param obj defines the object to use
  78941. * @returns a boolean
  78942. */
  78943. Tags.HasTags = function (obj) {
  78944. if (!obj._tags) {
  78945. return false;
  78946. }
  78947. return !BABYLON.Tools.IsEmpty(obj._tags);
  78948. };
  78949. /**
  78950. * Gets the tags available on a given object
  78951. * @param obj defines the object to use
  78952. * @param asString defines if the tags must be returned as a string instead of an array of strings
  78953. * @returns the tags
  78954. */
  78955. Tags.GetTags = function (obj, asString) {
  78956. if (asString === void 0) { asString = true; }
  78957. if (!obj._tags) {
  78958. return null;
  78959. }
  78960. if (asString) {
  78961. var tagsArray = [];
  78962. for (var tag in obj._tags) {
  78963. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  78964. tagsArray.push(tag);
  78965. }
  78966. }
  78967. return tagsArray.join(" ");
  78968. }
  78969. else {
  78970. return obj._tags;
  78971. }
  78972. };
  78973. /**
  78974. * Adds tags to an object
  78975. * @param obj defines the object to use
  78976. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  78977. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  78978. */
  78979. Tags.AddTagsTo = function (obj, tagsString) {
  78980. if (!tagsString) {
  78981. return;
  78982. }
  78983. if (typeof tagsString !== "string") {
  78984. return;
  78985. }
  78986. var tags = tagsString.split(" ");
  78987. tags.forEach(function (tag, index, array) {
  78988. Tags._AddTagTo(obj, tag);
  78989. });
  78990. };
  78991. /**
  78992. * @hidden
  78993. */
  78994. Tags._AddTagTo = function (obj, tag) {
  78995. tag = tag.trim();
  78996. if (tag === "" || tag === "true" || tag === "false") {
  78997. return;
  78998. }
  78999. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  79000. return;
  79001. }
  79002. Tags.EnableFor(obj);
  79003. obj._tags[tag] = true;
  79004. };
  79005. /**
  79006. * Removes specific tags from a specific object
  79007. * @param obj defines the object to use
  79008. * @param tagsString defines the tags to remove
  79009. */
  79010. Tags.RemoveTagsFrom = function (obj, tagsString) {
  79011. if (!Tags.HasTags(obj)) {
  79012. return;
  79013. }
  79014. var tags = tagsString.split(" ");
  79015. for (var t in tags) {
  79016. Tags._RemoveTagFrom(obj, tags[t]);
  79017. }
  79018. };
  79019. /**
  79020. * @hidden
  79021. */
  79022. Tags._RemoveTagFrom = function (obj, tag) {
  79023. delete obj._tags[tag];
  79024. };
  79025. /**
  79026. * Defines if tags hosted on an object match a given query
  79027. * @param obj defines the object to use
  79028. * @param tagsQuery defines the tag query
  79029. * @returns a boolean
  79030. */
  79031. Tags.MatchesQuery = function (obj, tagsQuery) {
  79032. if (tagsQuery === undefined) {
  79033. return true;
  79034. }
  79035. if (tagsQuery === "") {
  79036. return Tags.HasTags(obj);
  79037. }
  79038. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79039. };
  79040. return Tags;
  79041. }());
  79042. BABYLON.Tags = Tags;
  79043. })(BABYLON || (BABYLON = {}));
  79044. //# sourceMappingURL=babylon.tags.js.map
  79045. var BABYLON;
  79046. (function (BABYLON) {
  79047. /**
  79048. * Class used to evalaute queries containing `and` and `or` operators
  79049. */
  79050. var AndOrNotEvaluator = /** @class */ (function () {
  79051. function AndOrNotEvaluator() {
  79052. }
  79053. /**
  79054. * Evaluate a query
  79055. * @param query defines the query to evaluate
  79056. * @param evaluateCallback defines the callback used to filter result
  79057. * @returns true if the query matches
  79058. */
  79059. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79060. if (!query.match(/\([^\(\)]*\)/g)) {
  79061. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79062. }
  79063. else {
  79064. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79065. // remove parenthesis
  79066. r = r.slice(1, r.length - 1);
  79067. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79068. });
  79069. }
  79070. if (query === "true") {
  79071. return true;
  79072. }
  79073. if (query === "false") {
  79074. return false;
  79075. }
  79076. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79077. };
  79078. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79079. evaluateCallback = evaluateCallback || (function (r) {
  79080. return r === "true" ? true : false;
  79081. });
  79082. var result;
  79083. var or = parenthesisContent.split("||");
  79084. for (var i in or) {
  79085. if (or.hasOwnProperty(i)) {
  79086. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79087. var and = ori.split("&&");
  79088. if (and.length > 1) {
  79089. for (var j = 0; j < and.length; ++j) {
  79090. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79091. if (andj !== "true" && andj !== "false") {
  79092. if (andj[0] === "!") {
  79093. result = !evaluateCallback(andj.substring(1));
  79094. }
  79095. else {
  79096. result = evaluateCallback(andj);
  79097. }
  79098. }
  79099. else {
  79100. result = andj === "true" ? true : false;
  79101. }
  79102. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79103. ori = "false";
  79104. break;
  79105. }
  79106. }
  79107. }
  79108. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79109. result = true;
  79110. break;
  79111. }
  79112. // result equals false (or undefined)
  79113. if (ori !== "true" && ori !== "false") {
  79114. if (ori[0] === "!") {
  79115. result = !evaluateCallback(ori.substring(1));
  79116. }
  79117. else {
  79118. result = evaluateCallback(ori);
  79119. }
  79120. }
  79121. else {
  79122. result = ori === "true" ? true : false;
  79123. }
  79124. }
  79125. }
  79126. // the whole parenthesis scope is replaced by 'true' or 'false'
  79127. return result ? "true" : "false";
  79128. };
  79129. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79130. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79131. // remove whitespaces
  79132. r = r.replace(/[\s]/g, function () { return ""; });
  79133. return r.length % 2 ? "!" : "";
  79134. });
  79135. booleanString = booleanString.trim();
  79136. if (booleanString === "!true") {
  79137. booleanString = "false";
  79138. }
  79139. else if (booleanString === "!false") {
  79140. booleanString = "true";
  79141. }
  79142. return booleanString;
  79143. };
  79144. return AndOrNotEvaluator;
  79145. }());
  79146. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79147. })(BABYLON || (BABYLON = {}));
  79148. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  79149. var BABYLON;
  79150. (function (BABYLON) {
  79151. // Sets the default offline provider to Babylon.js
  79152. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79153. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79154. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79155. };
  79156. /**
  79157. * Class used to enable access to IndexedDB
  79158. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79159. */
  79160. var Database = /** @class */ (function () {
  79161. /**
  79162. * Creates a new Database
  79163. * @param urlToScene defines the url to load the scene
  79164. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79165. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79166. */
  79167. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79168. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79169. var _this = this;
  79170. // Handling various flavors of prefixed version of IndexedDB
  79171. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79172. this._callbackManifestChecked = callbackManifestChecked;
  79173. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79174. this._db = null;
  79175. this._enableSceneOffline = false;
  79176. this._enableTexturesOffline = false;
  79177. this._manifestVersionFound = 0;
  79178. this._mustUpdateRessources = false;
  79179. this._hasReachedQuota = false;
  79180. if (!Database.IDBStorageEnabled) {
  79181. this._callbackManifestChecked(true);
  79182. }
  79183. else {
  79184. if (disableManifestCheck) {
  79185. this._enableSceneOffline = true;
  79186. this._enableTexturesOffline = true;
  79187. this._manifestVersionFound = 1;
  79188. BABYLON.Tools.SetImmediate(function () {
  79189. _this._callbackManifestChecked(true);
  79190. });
  79191. }
  79192. else {
  79193. this._checkManifestFile();
  79194. }
  79195. }
  79196. }
  79197. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79198. /**
  79199. * Gets a boolean indicating if scene must be saved in the database
  79200. */
  79201. get: function () {
  79202. return this._enableSceneOffline;
  79203. },
  79204. enumerable: true,
  79205. configurable: true
  79206. });
  79207. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79208. /**
  79209. * Gets a boolean indicating if textures must be saved in the database
  79210. */
  79211. get: function () {
  79212. return this._enableTexturesOffline;
  79213. },
  79214. enumerable: true,
  79215. configurable: true
  79216. });
  79217. Database.prototype._checkManifestFile = function () {
  79218. var _this = this;
  79219. var noManifestFile = function () {
  79220. _this._enableSceneOffline = false;
  79221. _this._enableTexturesOffline = false;
  79222. _this._callbackManifestChecked(false);
  79223. };
  79224. var timeStampUsed = false;
  79225. var manifestURL = this._currentSceneUrl + ".manifest";
  79226. var xhr = new XMLHttpRequest();
  79227. if (navigator.onLine) {
  79228. // Adding a timestamp to by-pass browsers' cache
  79229. timeStampUsed = true;
  79230. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79231. }
  79232. xhr.open("GET", manifestURL, true);
  79233. xhr.addEventListener("load", function () {
  79234. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79235. try {
  79236. var manifestFile = JSON.parse(xhr.response);
  79237. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79238. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79239. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79240. _this._manifestVersionFound = manifestFile.version;
  79241. }
  79242. if (_this._callbackManifestChecked) {
  79243. _this._callbackManifestChecked(true);
  79244. }
  79245. }
  79246. catch (ex) {
  79247. noManifestFile();
  79248. }
  79249. }
  79250. else {
  79251. noManifestFile();
  79252. }
  79253. }, false);
  79254. xhr.addEventListener("error", function (event) {
  79255. if (timeStampUsed) {
  79256. timeStampUsed = false;
  79257. // Let's retry without the timeStamp
  79258. // It could fail when coupled with HTML5 Offline API
  79259. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79260. xhr.open("GET", retryManifestURL, true);
  79261. xhr.send();
  79262. }
  79263. else {
  79264. noManifestFile();
  79265. }
  79266. }, false);
  79267. try {
  79268. xhr.send();
  79269. }
  79270. catch (ex) {
  79271. BABYLON.Tools.Error("Error on XHR send request.");
  79272. this._callbackManifestChecked(false);
  79273. }
  79274. };
  79275. /**
  79276. * Open the database and make it available
  79277. * @param successCallback defines the callback to call on success
  79278. * @param errorCallback defines the callback to call on error
  79279. */
  79280. Database.prototype.open = function (successCallback, errorCallback) {
  79281. var _this = this;
  79282. var handleError = function () {
  79283. _this._isSupported = false;
  79284. if (errorCallback) {
  79285. errorCallback();
  79286. }
  79287. };
  79288. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79289. // Your browser doesn't support IndexedDB
  79290. this._isSupported = false;
  79291. if (errorCallback) {
  79292. errorCallback();
  79293. }
  79294. }
  79295. else {
  79296. // If the DB hasn't been opened or created yet
  79297. if (!this._db) {
  79298. this._hasReachedQuota = false;
  79299. this._isSupported = true;
  79300. var request = this._idbFactory.open("babylonjs", 1);
  79301. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79302. request.onerror = function (event) {
  79303. handleError();
  79304. };
  79305. // executes when a version change transaction cannot complete due to other active transactions
  79306. request.onblocked = function (event) {
  79307. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79308. handleError();
  79309. };
  79310. // DB has been opened successfully
  79311. request.onsuccess = function (event) {
  79312. _this._db = request.result;
  79313. successCallback();
  79314. };
  79315. // Initialization of the DB. Creating Scenes & Textures stores
  79316. request.onupgradeneeded = function (event) {
  79317. _this._db = (event.target).result;
  79318. if (_this._db) {
  79319. try {
  79320. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79321. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79322. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79323. }
  79324. catch (ex) {
  79325. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79326. handleError();
  79327. }
  79328. }
  79329. };
  79330. }
  79331. // DB has already been created and opened
  79332. else {
  79333. if (successCallback) {
  79334. successCallback();
  79335. }
  79336. }
  79337. }
  79338. };
  79339. /**
  79340. * Loads an image from the database
  79341. * @param url defines the url to load from
  79342. * @param image defines the target DOM image
  79343. */
  79344. Database.prototype.loadImage = function (url, image) {
  79345. var _this = this;
  79346. var completeURL = Database._ReturnFullUrlLocation(url);
  79347. var saveAndLoadImage = function () {
  79348. if (!_this._hasReachedQuota && _this._db !== null) {
  79349. // the texture is not yet in the DB, let's try to save it
  79350. _this._saveImageIntoDBAsync(completeURL, image);
  79351. }
  79352. // If the texture is not in the DB and we've reached the DB quota limit
  79353. // let's load it directly from the web
  79354. else {
  79355. image.src = url;
  79356. }
  79357. };
  79358. if (!this._mustUpdateRessources) {
  79359. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79360. }
  79361. // First time we're download the images or update requested in the manifest file by a version change
  79362. else {
  79363. saveAndLoadImage();
  79364. }
  79365. };
  79366. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79367. if (this._isSupported && this._db !== null) {
  79368. var texture;
  79369. var transaction = this._db.transaction(["textures"]);
  79370. transaction.onabort = function (event) {
  79371. image.src = url;
  79372. };
  79373. transaction.oncomplete = function (event) {
  79374. var blobTextureURL;
  79375. if (texture) {
  79376. var URL = window.URL || window.webkitURL;
  79377. blobTextureURL = URL.createObjectURL(texture.data);
  79378. image.onerror = function () {
  79379. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79380. image.src = url;
  79381. };
  79382. image.src = blobTextureURL;
  79383. }
  79384. else {
  79385. notInDBCallback();
  79386. }
  79387. };
  79388. var getRequest = transaction.objectStore("textures").get(url);
  79389. getRequest.onsuccess = function (event) {
  79390. texture = (event.target).result;
  79391. };
  79392. getRequest.onerror = function (event) {
  79393. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79394. image.src = url;
  79395. };
  79396. }
  79397. else {
  79398. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79399. image.src = url;
  79400. }
  79401. };
  79402. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79403. var _this = this;
  79404. if (this._isSupported) {
  79405. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79406. var generateBlobUrl = function () {
  79407. var blobTextureURL;
  79408. if (blob) {
  79409. var URL = window.URL || window.webkitURL;
  79410. try {
  79411. blobTextureURL = URL.createObjectURL(blob);
  79412. }
  79413. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79414. catch (ex) {
  79415. blobTextureURL = URL.createObjectURL(blob);
  79416. }
  79417. }
  79418. if (blobTextureURL) {
  79419. image.src = blobTextureURL;
  79420. }
  79421. };
  79422. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79423. var xhr = new XMLHttpRequest(), blob;
  79424. xhr.open("GET", url, true);
  79425. xhr.responseType = "blob";
  79426. xhr.addEventListener("load", function () {
  79427. if (xhr.status === 200 && _this._db) {
  79428. // Blob as response (XHR2)
  79429. blob = xhr.response;
  79430. var transaction = _this._db.transaction(["textures"], "readwrite");
  79431. // the transaction could abort because of a QuotaExceededError error
  79432. transaction.onabort = function (event) {
  79433. try {
  79434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79435. var srcElement = (event.srcElement || event.target);
  79436. var error = srcElement.error;
  79437. if (error && error.name === "QuotaExceededError") {
  79438. _this._hasReachedQuota = true;
  79439. }
  79440. }
  79441. catch (ex) { }
  79442. generateBlobUrl();
  79443. };
  79444. transaction.oncomplete = function (event) {
  79445. generateBlobUrl();
  79446. };
  79447. var newTexture = { textureUrl: url, data: blob };
  79448. try {
  79449. // Put the blob into the dabase
  79450. var addRequest = transaction.objectStore("textures").put(newTexture);
  79451. addRequest.onsuccess = function (event) {
  79452. };
  79453. addRequest.onerror = function (event) {
  79454. generateBlobUrl();
  79455. };
  79456. }
  79457. catch (ex) {
  79458. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  79459. if (ex.code === 25) {
  79460. Database.IsUASupportingBlobStorage = false;
  79461. _this._enableTexturesOffline = false;
  79462. }
  79463. image.src = url;
  79464. }
  79465. }
  79466. else {
  79467. image.src = url;
  79468. }
  79469. }, false);
  79470. xhr.addEventListener("error", function (event) {
  79471. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  79472. image.src = url;
  79473. }, false);
  79474. xhr.send();
  79475. }
  79476. else {
  79477. image.src = url;
  79478. }
  79479. }
  79480. else {
  79481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79482. image.src = url;
  79483. }
  79484. };
  79485. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  79486. var _this = this;
  79487. var updateVersion = function () {
  79488. // the version is not yet in the DB or we need to update it
  79489. _this._saveVersionIntoDBAsync(url, versionLoaded);
  79490. };
  79491. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  79492. };
  79493. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  79494. var _this = this;
  79495. if (this._isSupported && this._db) {
  79496. var version;
  79497. try {
  79498. var transaction = this._db.transaction(["versions"]);
  79499. transaction.oncomplete = function (event) {
  79500. if (version) {
  79501. // If the version in the JSON file is different from the version in DB
  79502. if (_this._manifestVersionFound !== version.data) {
  79503. _this._mustUpdateRessources = true;
  79504. updateInDBCallback();
  79505. }
  79506. else {
  79507. callback(version.data);
  79508. }
  79509. }
  79510. // version was not found in DB
  79511. else {
  79512. _this._mustUpdateRessources = true;
  79513. updateInDBCallback();
  79514. }
  79515. };
  79516. transaction.onabort = function (event) {
  79517. callback(-1);
  79518. };
  79519. var getRequest = transaction.objectStore("versions").get(url);
  79520. getRequest.onsuccess = function (event) {
  79521. version = (event.target).result;
  79522. };
  79523. getRequest.onerror = function (event) {
  79524. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  79525. callback(-1);
  79526. };
  79527. }
  79528. catch (ex) {
  79529. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  79530. callback(-1);
  79531. }
  79532. }
  79533. else {
  79534. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79535. callback(-1);
  79536. }
  79537. };
  79538. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  79539. var _this = this;
  79540. if (this._isSupported && !this._hasReachedQuota && this._db) {
  79541. try {
  79542. // Open a transaction to the database
  79543. var transaction = this._db.transaction(["versions"], "readwrite");
  79544. // the transaction could abort because of a QuotaExceededError error
  79545. transaction.onabort = function (event) {
  79546. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79547. var error = event.srcElement['error'];
  79548. if (error && error.name === "QuotaExceededError") {
  79549. _this._hasReachedQuota = true;
  79550. }
  79551. }
  79552. catch (ex) { }
  79553. callback(-1);
  79554. };
  79555. transaction.oncomplete = function (event) {
  79556. callback(_this._manifestVersionFound);
  79557. };
  79558. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  79559. // Put the scene into the database
  79560. var addRequest = transaction.objectStore("versions").put(newVersion);
  79561. addRequest.onsuccess = function (event) {
  79562. };
  79563. addRequest.onerror = function (event) {
  79564. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  79565. };
  79566. }
  79567. catch (ex) {
  79568. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  79569. callback(-1);
  79570. }
  79571. }
  79572. else {
  79573. callback(-1);
  79574. }
  79575. };
  79576. /**
  79577. * Loads a file from database
  79578. * @param url defines the URL to load from
  79579. * @param sceneLoaded defines a callback to call on success
  79580. * @param progressCallBack defines a callback to call when progress changed
  79581. * @param errorCallback defines a callback to call on error
  79582. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  79583. */
  79584. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  79585. var _this = this;
  79586. var completeUrl = Database._ReturnFullUrlLocation(url);
  79587. var saveAndLoadFile = function () {
  79588. // the scene is not yet in the DB, let's try to save it
  79589. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79590. };
  79591. this._checkVersionFromDB(completeUrl, function (version) {
  79592. if (version !== -1) {
  79593. if (!_this._mustUpdateRessources) {
  79594. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  79595. }
  79596. else {
  79597. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79598. }
  79599. }
  79600. else {
  79601. if (errorCallback) {
  79602. errorCallback();
  79603. }
  79604. }
  79605. });
  79606. };
  79607. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  79608. if (this._isSupported && this._db) {
  79609. var targetStore;
  79610. if (url.indexOf(".babylon") !== -1) {
  79611. targetStore = "scenes";
  79612. }
  79613. else {
  79614. targetStore = "textures";
  79615. }
  79616. var file;
  79617. var transaction = this._db.transaction([targetStore]);
  79618. transaction.oncomplete = function (event) {
  79619. if (file) {
  79620. callback(file.data);
  79621. }
  79622. // file was not found in DB
  79623. else {
  79624. notInDBCallback();
  79625. }
  79626. };
  79627. transaction.onabort = function (event) {
  79628. notInDBCallback();
  79629. };
  79630. var getRequest = transaction.objectStore(targetStore).get(url);
  79631. getRequest.onsuccess = function (event) {
  79632. file = (event.target).result;
  79633. };
  79634. getRequest.onerror = function (event) {
  79635. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  79636. notInDBCallback();
  79637. };
  79638. }
  79639. else {
  79640. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79641. callback();
  79642. }
  79643. };
  79644. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  79645. var _this = this;
  79646. if (this._isSupported) {
  79647. var targetStore;
  79648. if (url.indexOf(".babylon") !== -1) {
  79649. targetStore = "scenes";
  79650. }
  79651. else {
  79652. targetStore = "textures";
  79653. }
  79654. // Create XHR
  79655. var xhr = new XMLHttpRequest();
  79656. var fileData;
  79657. xhr.open("GET", url + "?" + Date.now(), true);
  79658. if (useArrayBuffer) {
  79659. xhr.responseType = "arraybuffer";
  79660. }
  79661. if (progressCallback) {
  79662. xhr.onprogress = progressCallback;
  79663. }
  79664. xhr.addEventListener("load", function () {
  79665. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  79666. // Blob as response (XHR2)
  79667. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  79668. if (!_this._hasReachedQuota && _this._db) {
  79669. // Open a transaction to the database
  79670. var transaction = _this._db.transaction([targetStore], "readwrite");
  79671. // the transaction could abort because of a QuotaExceededError error
  79672. transaction.onabort = function (event) {
  79673. try {
  79674. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79675. var error = event.srcElement['error'];
  79676. if (error && error.name === "QuotaExceededError") {
  79677. _this._hasReachedQuota = true;
  79678. }
  79679. }
  79680. catch (ex) { }
  79681. callback(fileData);
  79682. };
  79683. transaction.oncomplete = function (event) {
  79684. callback(fileData);
  79685. };
  79686. var newFile;
  79687. if (targetStore === "scenes") {
  79688. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  79689. }
  79690. else {
  79691. newFile = { textureUrl: url, data: fileData };
  79692. }
  79693. try {
  79694. // Put the scene into the database
  79695. var addRequest = transaction.objectStore(targetStore).put(newFile);
  79696. addRequest.onsuccess = function (event) {
  79697. };
  79698. addRequest.onerror = function (event) {
  79699. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  79700. };
  79701. }
  79702. catch (ex) {
  79703. callback(fileData);
  79704. }
  79705. }
  79706. else {
  79707. callback(fileData);
  79708. }
  79709. }
  79710. else {
  79711. if (xhr.status >= 400 && errorCallback) {
  79712. errorCallback(xhr);
  79713. }
  79714. else {
  79715. callback();
  79716. }
  79717. }
  79718. }, false);
  79719. xhr.addEventListener("error", function (event) {
  79720. BABYLON.Tools.Error("error on XHR request.");
  79721. callback();
  79722. }, false);
  79723. xhr.send();
  79724. }
  79725. else {
  79726. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  79727. callback();
  79728. }
  79729. };
  79730. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  79731. Database.IsUASupportingBlobStorage = true;
  79732. /**
  79733. * Gets a boolean indicating if Database storate is enabled (off by default)
  79734. */
  79735. Database.IDBStorageEnabled = false;
  79736. Database._ParseURL = function (url) {
  79737. var a = document.createElement('a');
  79738. a.href = url;
  79739. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  79740. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  79741. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  79742. return absLocation;
  79743. };
  79744. Database._ReturnFullUrlLocation = function (url) {
  79745. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  79746. return (Database._ParseURL(window.location.href) + url);
  79747. }
  79748. else {
  79749. return url;
  79750. }
  79751. };
  79752. return Database;
  79753. }());
  79754. BABYLON.Database = Database;
  79755. })(BABYLON || (BABYLON = {}));
  79756. //# sourceMappingURL=babylon.database.js.map
  79757. var BABYLON;
  79758. (function (BABYLON) {
  79759. /**
  79760. * This represents all the required information to add a fresnel effect on a material:
  79761. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  79762. */
  79763. var FresnelParameters = /** @class */ (function () {
  79764. function FresnelParameters() {
  79765. this._isEnabled = true;
  79766. /**
  79767. * Define the color used on edges (grazing angle)
  79768. */
  79769. this.leftColor = BABYLON.Color3.White();
  79770. /**
  79771. * Define the color used on center
  79772. */
  79773. this.rightColor = BABYLON.Color3.Black();
  79774. /**
  79775. * Define bias applied to computed fresnel term
  79776. */
  79777. this.bias = 0;
  79778. /**
  79779. * Defined the power exponent applied to fresnel term
  79780. */
  79781. this.power = 1;
  79782. }
  79783. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  79784. /**
  79785. * Define if the fresnel effect is enable or not.
  79786. */
  79787. get: function () {
  79788. return this._isEnabled;
  79789. },
  79790. set: function (value) {
  79791. if (this._isEnabled === value) {
  79792. return;
  79793. }
  79794. this._isEnabled = value;
  79795. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  79796. },
  79797. enumerable: true,
  79798. configurable: true
  79799. });
  79800. /**
  79801. * Clones the current fresnel and its valuues
  79802. * @returns a clone fresnel configuration
  79803. */
  79804. FresnelParameters.prototype.clone = function () {
  79805. var newFresnelParameters = new FresnelParameters();
  79806. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  79807. return newFresnelParameters;
  79808. };
  79809. /**
  79810. * Serializes the current fresnel parameters to a JSON representation.
  79811. * @return the JSON serialization
  79812. */
  79813. FresnelParameters.prototype.serialize = function () {
  79814. var serializationObject = {};
  79815. serializationObject.isEnabled = this.isEnabled;
  79816. serializationObject.leftColor = this.leftColor.asArray();
  79817. serializationObject.rightColor = this.rightColor.asArray();
  79818. serializationObject.bias = this.bias;
  79819. serializationObject.power = this.power;
  79820. return serializationObject;
  79821. };
  79822. /**
  79823. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  79824. * @param parsedFresnelParameters Define the JSON representation
  79825. * @returns the parsed parameters
  79826. */
  79827. FresnelParameters.Parse = function (parsedFresnelParameters) {
  79828. var fresnelParameters = new FresnelParameters();
  79829. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  79830. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  79831. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  79832. fresnelParameters.bias = parsedFresnelParameters.bias;
  79833. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  79834. return fresnelParameters;
  79835. };
  79836. return FresnelParameters;
  79837. }());
  79838. BABYLON.FresnelParameters = FresnelParameters;
  79839. })(BABYLON || (BABYLON = {}));
  79840. //# sourceMappingURL=babylon.fresnelParameters.js.map
  79841. var BABYLON;
  79842. (function (BABYLON) {
  79843. /**
  79844. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79845. * separate meshes. This can be use to improve performances.
  79846. * @see http://doc.babylonjs.com/how_to/multi_materials
  79847. */
  79848. var MultiMaterial = /** @class */ (function (_super) {
  79849. __extends(MultiMaterial, _super);
  79850. /**
  79851. * Instantiates a new Multi Material
  79852. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79853. * separate meshes. This can be use to improve performances.
  79854. * @see http://doc.babylonjs.com/how_to/multi_materials
  79855. * @param name Define the name in the scene
  79856. * @param scene Define the scene the material belongs to
  79857. */
  79858. function MultiMaterial(name, scene) {
  79859. var _this = _super.call(this, name, scene, true) || this;
  79860. scene.multiMaterials.push(_this);
  79861. _this.subMaterials = new Array();
  79862. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  79863. return _this;
  79864. }
  79865. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  79866. /**
  79867. * Gets or Sets the list of Materials used within the multi material.
  79868. * They need to be ordered according to the submeshes order in the associated mesh
  79869. */
  79870. get: function () {
  79871. return this._subMaterials;
  79872. },
  79873. set: function (value) {
  79874. this._subMaterials = value;
  79875. this._hookArray(value);
  79876. },
  79877. enumerable: true,
  79878. configurable: true
  79879. });
  79880. MultiMaterial.prototype._hookArray = function (array) {
  79881. var _this = this;
  79882. var oldPush = array.push;
  79883. array.push = function () {
  79884. var items = [];
  79885. for (var _i = 0; _i < arguments.length; _i++) {
  79886. items[_i] = arguments[_i];
  79887. }
  79888. var result = oldPush.apply(array, items);
  79889. _this._markAllSubMeshesAsTexturesDirty();
  79890. return result;
  79891. };
  79892. var oldSplice = array.splice;
  79893. array.splice = function (index, deleteCount) {
  79894. var deleted = oldSplice.apply(array, [index, deleteCount]);
  79895. _this._markAllSubMeshesAsTexturesDirty();
  79896. return deleted;
  79897. };
  79898. };
  79899. /**
  79900. * Get one of the submaterial by its index in the submaterials array
  79901. * @param index The index to look the sub material at
  79902. * @returns The Material if the index has been defined
  79903. */
  79904. MultiMaterial.prototype.getSubMaterial = function (index) {
  79905. if (index < 0 || index >= this.subMaterials.length) {
  79906. return this.getScene().defaultMaterial;
  79907. }
  79908. return this.subMaterials[index];
  79909. };
  79910. /**
  79911. * Get the list of active textures for the whole sub materials list.
  79912. * @returns All the textures that will be used during the rendering
  79913. */
  79914. MultiMaterial.prototype.getActiveTextures = function () {
  79915. var _a;
  79916. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  79917. if (subMaterial) {
  79918. return subMaterial.getActiveTextures();
  79919. }
  79920. else {
  79921. return [];
  79922. }
  79923. }));
  79924. };
  79925. /**
  79926. * Gets the current class name of the material e.g. "MultiMaterial"
  79927. * Mainly use in serialization.
  79928. * @returns the class name
  79929. */
  79930. MultiMaterial.prototype.getClassName = function () {
  79931. return "MultiMaterial";
  79932. };
  79933. /**
  79934. * Checks if the material is ready to render the requested sub mesh
  79935. * @param mesh Define the mesh the submesh belongs to
  79936. * @param subMesh Define the sub mesh to look readyness for
  79937. * @param useInstances Define whether or not the material is used with instances
  79938. * @returns true if ready, otherwise false
  79939. */
  79940. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79941. for (var index = 0; index < this.subMaterials.length; index++) {
  79942. var subMaterial = this.subMaterials[index];
  79943. if (subMaterial) {
  79944. if (subMaterial._storeEffectOnSubMeshes) {
  79945. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  79946. return false;
  79947. }
  79948. continue;
  79949. }
  79950. if (!subMaterial.isReady(mesh)) {
  79951. return false;
  79952. }
  79953. }
  79954. }
  79955. return true;
  79956. };
  79957. /**
  79958. * Clones the current material and its related sub materials
  79959. * @param name Define the name of the newly cloned material
  79960. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  79961. * @returns the cloned material
  79962. */
  79963. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  79964. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  79965. for (var index = 0; index < this.subMaterials.length; index++) {
  79966. var subMaterial = null;
  79967. var current = this.subMaterials[index];
  79968. if (cloneChildren && current) {
  79969. subMaterial = current.clone(name + "-" + current.name);
  79970. }
  79971. else {
  79972. subMaterial = this.subMaterials[index];
  79973. }
  79974. newMultiMaterial.subMaterials.push(subMaterial);
  79975. }
  79976. return newMultiMaterial;
  79977. };
  79978. /**
  79979. * Serializes the materials into a JSON representation.
  79980. * @returns the JSON representation
  79981. */
  79982. MultiMaterial.prototype.serialize = function () {
  79983. var serializationObject = {};
  79984. serializationObject.name = this.name;
  79985. serializationObject.id = this.id;
  79986. if (BABYLON.Tags) {
  79987. serializationObject.tags = BABYLON.Tags.GetTags(this);
  79988. }
  79989. serializationObject.materials = [];
  79990. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  79991. var subMat = this.subMaterials[matIndex];
  79992. if (subMat) {
  79993. serializationObject.materials.push(subMat.id);
  79994. }
  79995. else {
  79996. serializationObject.materials.push(null);
  79997. }
  79998. }
  79999. return serializationObject;
  80000. };
  80001. /**
  80002. * Dispose the material and release its associated resources
  80003. * @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)
  80004. * @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)
  80005. */
  80006. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80007. var scene = this.getScene();
  80008. if (!scene) {
  80009. return;
  80010. }
  80011. var index = scene.multiMaterials.indexOf(this);
  80012. if (index >= 0) {
  80013. scene.multiMaterials.splice(index, 1);
  80014. }
  80015. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  80016. };
  80017. return MultiMaterial;
  80018. }(BABYLON.Material));
  80019. BABYLON.MultiMaterial = MultiMaterial;
  80020. })(BABYLON || (BABYLON = {}));
  80021. //# sourceMappingURL=babylon.multiMaterial.js.map
  80022. var BABYLON;
  80023. (function (BABYLON) {
  80024. /**
  80025. * Manage the touch inputs to control the movement of a free camera.
  80026. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80027. */
  80028. var FreeCameraTouchInput = /** @class */ (function () {
  80029. function FreeCameraTouchInput() {
  80030. /**
  80031. * Defines the touch sensibility for rotation.
  80032. * The higher the faster.
  80033. */
  80034. this.touchAngularSensibility = 200000.0;
  80035. /**
  80036. * Defines the touch sensibility for move.
  80037. * The higher the faster.
  80038. */
  80039. this.touchMoveSensibility = 250.0;
  80040. this._offsetX = null;
  80041. this._offsetY = null;
  80042. this._pointerPressed = new Array();
  80043. }
  80044. /**
  80045. * Attach the input controls to a specific dom element to get the input from.
  80046. * @param element Defines the element the controls should be listened from
  80047. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80048. */
  80049. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80050. var _this = this;
  80051. var previousPosition = null;
  80052. if (this._pointerInput === undefined) {
  80053. this._onLostFocus = function (evt) {
  80054. _this._offsetX = null;
  80055. _this._offsetY = null;
  80056. };
  80057. this._pointerInput = function (p, s) {
  80058. var evt = p.event;
  80059. if (evt.pointerType === "mouse") {
  80060. return;
  80061. }
  80062. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80063. if (!noPreventDefault) {
  80064. evt.preventDefault();
  80065. }
  80066. _this._pointerPressed.push(evt.pointerId);
  80067. if (_this._pointerPressed.length !== 1) {
  80068. return;
  80069. }
  80070. previousPosition = {
  80071. x: evt.clientX,
  80072. y: evt.clientY
  80073. };
  80074. }
  80075. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80076. if (!noPreventDefault) {
  80077. evt.preventDefault();
  80078. }
  80079. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80080. if (index === -1) {
  80081. return;
  80082. }
  80083. _this._pointerPressed.splice(index, 1);
  80084. if (index != 0) {
  80085. return;
  80086. }
  80087. previousPosition = null;
  80088. _this._offsetX = null;
  80089. _this._offsetY = null;
  80090. }
  80091. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80092. if (!noPreventDefault) {
  80093. evt.preventDefault();
  80094. }
  80095. if (!previousPosition) {
  80096. return;
  80097. }
  80098. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80099. if (index != 0) {
  80100. return;
  80101. }
  80102. _this._offsetX = evt.clientX - previousPosition.x;
  80103. _this._offsetY = -(evt.clientY - previousPosition.y);
  80104. }
  80105. };
  80106. }
  80107. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80108. if (this._onLostFocus) {
  80109. element.addEventListener("blur", this._onLostFocus);
  80110. }
  80111. };
  80112. /**
  80113. * Detach the current controls from the specified dom element.
  80114. * @param element Defines the element to stop listening the inputs from
  80115. */
  80116. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80117. if (this._pointerInput && element) {
  80118. if (this._observer) {
  80119. this.camera.getScene().onPointerObservable.remove(this._observer);
  80120. this._observer = null;
  80121. }
  80122. if (this._onLostFocus) {
  80123. element.removeEventListener("blur", this._onLostFocus);
  80124. this._onLostFocus = null;
  80125. }
  80126. this._pointerPressed = [];
  80127. this._offsetX = null;
  80128. this._offsetY = null;
  80129. }
  80130. };
  80131. /**
  80132. * Update the current camera state depending on the inputs that have been used this frame.
  80133. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80134. */
  80135. FreeCameraTouchInput.prototype.checkInputs = function () {
  80136. if (this._offsetX && this._offsetY) {
  80137. var camera = this.camera;
  80138. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80139. if (this._pointerPressed.length > 1) {
  80140. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80141. }
  80142. else {
  80143. var speed = camera._computeLocalCameraSpeed();
  80144. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80145. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80146. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80147. }
  80148. }
  80149. };
  80150. /**
  80151. * Gets the class name of the current intput.
  80152. * @returns the class name
  80153. */
  80154. FreeCameraTouchInput.prototype.getClassName = function () {
  80155. return "FreeCameraTouchInput";
  80156. };
  80157. /**
  80158. * Get the friendly name associated with the input class.
  80159. * @returns the input friendly name
  80160. */
  80161. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80162. return "touch";
  80163. };
  80164. __decorate([
  80165. BABYLON.serialize()
  80166. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80167. __decorate([
  80168. BABYLON.serialize()
  80169. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80170. return FreeCameraTouchInput;
  80171. }());
  80172. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80173. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80174. })(BABYLON || (BABYLON = {}));
  80175. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  80176. var BABYLON;
  80177. (function (BABYLON) {
  80178. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80179. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80180. });
  80181. /**
  80182. * This represents a FPS type of camera controlled by touch.
  80183. * This is like a universal camera minus the Gamepad controls.
  80184. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80185. */
  80186. var TouchCamera = /** @class */ (function (_super) {
  80187. __extends(TouchCamera, _super);
  80188. /**
  80189. * Instantiates a new touch camera.
  80190. * This represents a FPS type of camera controlled by touch.
  80191. * This is like a universal camera minus the Gamepad controls.
  80192. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80193. * @param name Define the name of the camera in the scene
  80194. * @param position Define the start position of the camera in the scene
  80195. * @param scene Define the scene the camera belongs to
  80196. */
  80197. function TouchCamera(name, position, scene) {
  80198. var _this = _super.call(this, name, position, scene) || this;
  80199. _this.inputs.addTouch();
  80200. _this._setupInputs();
  80201. return _this;
  80202. }
  80203. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80204. /**
  80205. * Defines the touch sensibility for rotation.
  80206. * The higher the faster.
  80207. */
  80208. get: function () {
  80209. var touch = this.inputs.attached["touch"];
  80210. if (touch) {
  80211. return touch.touchAngularSensibility;
  80212. }
  80213. return 0;
  80214. },
  80215. set: function (value) {
  80216. var touch = this.inputs.attached["touch"];
  80217. if (touch) {
  80218. touch.touchAngularSensibility = value;
  80219. }
  80220. },
  80221. enumerable: true,
  80222. configurable: true
  80223. });
  80224. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80225. /**
  80226. * Defines the touch sensibility for move.
  80227. * The higher the faster.
  80228. */
  80229. get: function () {
  80230. var touch = this.inputs.attached["touch"];
  80231. if (touch) {
  80232. return touch.touchMoveSensibility;
  80233. }
  80234. return 0;
  80235. },
  80236. set: function (value) {
  80237. var touch = this.inputs.attached["touch"];
  80238. if (touch) {
  80239. touch.touchMoveSensibility = value;
  80240. }
  80241. },
  80242. enumerable: true,
  80243. configurable: true
  80244. });
  80245. /**
  80246. * Gets the current object class name.
  80247. * @return the class name
  80248. */
  80249. TouchCamera.prototype.getClassName = function () {
  80250. return "TouchCamera";
  80251. };
  80252. /** @hidden */
  80253. TouchCamera.prototype._setupInputs = function () {
  80254. var mouse = this.inputs.attached["mouse"];
  80255. if (mouse) {
  80256. mouse.touchEnabled = false;
  80257. }
  80258. };
  80259. return TouchCamera;
  80260. }(BABYLON.FreeCamera));
  80261. BABYLON.TouchCamera = TouchCamera;
  80262. })(BABYLON || (BABYLON = {}));
  80263. //# sourceMappingURL=babylon.touchCamera.js.map
  80264. var BABYLON;
  80265. (function (BABYLON) {
  80266. /**
  80267. * 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.
  80268. * This is the base class of any Procedural texture and contains most of the shareable code.
  80269. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80270. */
  80271. var ProceduralTexture = /** @class */ (function (_super) {
  80272. __extends(ProceduralTexture, _super);
  80273. /**
  80274. * Instantiates a new procedural texture.
  80275. * 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.
  80276. * This is the base class of any Procedural texture and contains most of the shareable code.
  80277. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80278. * @param name Define the name of the texture
  80279. * @param size Define the size of the texture to create
  80280. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80281. * @param scene Define the scene the texture belongs to
  80282. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80283. * @param generateMipMaps Define if the texture should creates mip maps or not
  80284. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80285. */
  80286. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80287. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80288. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80289. if (isCube === void 0) { isCube = false; }
  80290. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80291. _this.isCube = isCube;
  80292. /**
  80293. * Define if the texture is enabled or not (disabled texture will not render)
  80294. */
  80295. _this.isEnabled = true;
  80296. /**
  80297. * Define if the texture must be cleared before rendering (default is true)
  80298. */
  80299. _this.autoClear = true;
  80300. /**
  80301. * Event raised when the texture is generated
  80302. */
  80303. _this.onGeneratedObservable = new BABYLON.Observable();
  80304. /** @hidden */
  80305. _this._textures = {};
  80306. _this._currentRefreshId = -1;
  80307. _this._refreshRate = 1;
  80308. _this._vertexBuffers = {};
  80309. _this._uniforms = new Array();
  80310. _this._samplers = new Array();
  80311. _this._floats = {};
  80312. _this._ints = {};
  80313. _this._floatsArrays = {};
  80314. _this._colors3 = {};
  80315. _this._colors4 = {};
  80316. _this._vectors2 = {};
  80317. _this._vectors3 = {};
  80318. _this._matrices = {};
  80319. _this._fallbackTextureUsed = false;
  80320. _this._cachedDefines = "";
  80321. _this._contentUpdateId = -1;
  80322. scene = _this.getScene();
  80323. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80324. if (!component) {
  80325. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80326. scene._addComponent(component);
  80327. }
  80328. scene.proceduralTextures.push(_this);
  80329. _this._engine = scene.getEngine();
  80330. _this.name = name;
  80331. _this.isRenderTarget = true;
  80332. _this._size = size;
  80333. _this._generateMipMaps = generateMipMaps;
  80334. _this.setFragment(fragment);
  80335. _this._fallbackTexture = fallbackTexture;
  80336. if (isCube) {
  80337. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80338. _this.setFloat("face", 0);
  80339. }
  80340. else {
  80341. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80342. }
  80343. // VBO
  80344. var vertices = [];
  80345. vertices.push(1, 1);
  80346. vertices.push(-1, 1);
  80347. vertices.push(-1, -1);
  80348. vertices.push(1, -1);
  80349. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80350. _this._createIndexBuffer();
  80351. return _this;
  80352. }
  80353. /**
  80354. * The effect that is created when initializing the post process.
  80355. * @returns The created effect corrisponding the the postprocess.
  80356. */
  80357. ProceduralTexture.prototype.getEffect = function () {
  80358. return this._effect;
  80359. };
  80360. /**
  80361. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80362. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80363. */
  80364. ProceduralTexture.prototype.getContent = function () {
  80365. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80366. return this._contentData;
  80367. }
  80368. this._contentData = this.readPixels(0, 0, this._contentData);
  80369. this._contentUpdateId = this._currentRefreshId;
  80370. return this._contentData;
  80371. };
  80372. ProceduralTexture.prototype._createIndexBuffer = function () {
  80373. var engine = this._engine;
  80374. // Indices
  80375. var indices = [];
  80376. indices.push(0);
  80377. indices.push(1);
  80378. indices.push(2);
  80379. indices.push(0);
  80380. indices.push(2);
  80381. indices.push(3);
  80382. this._indexBuffer = engine.createIndexBuffer(indices);
  80383. };
  80384. /** @hidden */
  80385. ProceduralTexture.prototype._rebuild = function () {
  80386. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80387. if (vb) {
  80388. vb._rebuild();
  80389. }
  80390. this._createIndexBuffer();
  80391. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80392. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80393. }
  80394. };
  80395. /**
  80396. * Resets the texture in order to recreate its associated resources.
  80397. * This can be called in case of context loss
  80398. */
  80399. ProceduralTexture.prototype.reset = function () {
  80400. if (this._effect === undefined) {
  80401. return;
  80402. }
  80403. var engine = this._engine;
  80404. engine._releaseEffect(this._effect);
  80405. };
  80406. ProceduralTexture.prototype._getDefines = function () {
  80407. return "";
  80408. };
  80409. /**
  80410. * Is the texture ready to be used ? (rendered at least once)
  80411. * @returns true if ready, otherwise, false.
  80412. */
  80413. ProceduralTexture.prototype.isReady = function () {
  80414. var _this = this;
  80415. var engine = this._engine;
  80416. var shaders;
  80417. if (!this._fragment) {
  80418. return false;
  80419. }
  80420. if (this._fallbackTextureUsed) {
  80421. return true;
  80422. }
  80423. var defines = this._getDefines();
  80424. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80425. return true;
  80426. }
  80427. if (this._fragment.fragmentElement !== undefined) {
  80428. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  80429. }
  80430. else {
  80431. shaders = { vertex: "procedural", fragment: this._fragment };
  80432. }
  80433. this._cachedDefines = defines;
  80434. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  80435. _this.releaseInternalTexture();
  80436. if (_this._fallbackTexture) {
  80437. _this._texture = _this._fallbackTexture._texture;
  80438. if (_this._texture) {
  80439. _this._texture.incrementReferences();
  80440. }
  80441. }
  80442. _this._fallbackTextureUsed = true;
  80443. });
  80444. return this._effect.isReady();
  80445. };
  80446. /**
  80447. * Resets the refresh counter of the texture and start bak from scratch.
  80448. * Could be usefull to regenerate the texture if it is setup to render only once.
  80449. */
  80450. ProceduralTexture.prototype.resetRefreshCounter = function () {
  80451. this._currentRefreshId = -1;
  80452. };
  80453. /**
  80454. * Set the fragment shader to use in order to render the texture.
  80455. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  80456. */
  80457. ProceduralTexture.prototype.setFragment = function (fragment) {
  80458. this._fragment = fragment;
  80459. };
  80460. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  80461. /**
  80462. * Define the refresh rate of the texture or the rendering frequency.
  80463. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  80464. */
  80465. get: function () {
  80466. return this._refreshRate;
  80467. },
  80468. set: function (value) {
  80469. this._refreshRate = value;
  80470. this.resetRefreshCounter();
  80471. },
  80472. enumerable: true,
  80473. configurable: true
  80474. });
  80475. /** @hidden */
  80476. ProceduralTexture.prototype._shouldRender = function () {
  80477. if (!this.isEnabled || !this.isReady() || !this._texture) {
  80478. if (this._texture) {
  80479. this._texture.isReady = false;
  80480. }
  80481. return false;
  80482. }
  80483. if (this._fallbackTextureUsed) {
  80484. return false;
  80485. }
  80486. if (this._currentRefreshId === -1) { // At least render once
  80487. this._currentRefreshId = 1;
  80488. return true;
  80489. }
  80490. if (this.refreshRate === this._currentRefreshId) {
  80491. this._currentRefreshId = 1;
  80492. return true;
  80493. }
  80494. this._currentRefreshId++;
  80495. return false;
  80496. };
  80497. /**
  80498. * Get the size the texture is rendering at.
  80499. * @returns the size (texture is always squared)
  80500. */
  80501. ProceduralTexture.prototype.getRenderSize = function () {
  80502. return this._size;
  80503. };
  80504. /**
  80505. * Resize the texture to new value.
  80506. * @param size Define the new size the texture should have
  80507. * @param generateMipMaps Define whether the new texture should create mip maps
  80508. */
  80509. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  80510. if (this._fallbackTextureUsed) {
  80511. return;
  80512. }
  80513. this.releaseInternalTexture();
  80514. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  80515. // Update properties
  80516. this._size = size;
  80517. this._generateMipMaps = generateMipMaps;
  80518. };
  80519. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  80520. if (this._uniforms.indexOf(uniformName) === -1) {
  80521. this._uniforms.push(uniformName);
  80522. }
  80523. };
  80524. /**
  80525. * Set a texture in the shader program used to render.
  80526. * @param name Define the name of the uniform samplers as defined in the shader
  80527. * @param texture Define the texture to bind to this sampler
  80528. * @return the texture itself allowing "fluent" like uniform updates
  80529. */
  80530. ProceduralTexture.prototype.setTexture = function (name, texture) {
  80531. if (this._samplers.indexOf(name) === -1) {
  80532. this._samplers.push(name);
  80533. }
  80534. this._textures[name] = texture;
  80535. return this;
  80536. };
  80537. /**
  80538. * Set a float in the shader.
  80539. * @param name Define the name of the uniform as defined in the shader
  80540. * @param value Define the value to give to the uniform
  80541. * @return the texture itself allowing "fluent" like uniform updates
  80542. */
  80543. ProceduralTexture.prototype.setFloat = function (name, value) {
  80544. this._checkUniform(name);
  80545. this._floats[name] = value;
  80546. return this;
  80547. };
  80548. /**
  80549. * Set a int in the shader.
  80550. * @param name Define the name of the uniform as defined in the shader
  80551. * @param value Define the value to give to the uniform
  80552. * @return the texture itself allowing "fluent" like uniform updates
  80553. */
  80554. ProceduralTexture.prototype.setInt = function (name, value) {
  80555. this._checkUniform(name);
  80556. this._ints[name] = value;
  80557. return this;
  80558. };
  80559. /**
  80560. * Set an array of floats in the shader.
  80561. * @param name Define the name of the uniform as defined in the shader
  80562. * @param value Define the value to give to the uniform
  80563. * @return the texture itself allowing "fluent" like uniform updates
  80564. */
  80565. ProceduralTexture.prototype.setFloats = function (name, value) {
  80566. this._checkUniform(name);
  80567. this._floatsArrays[name] = value;
  80568. return this;
  80569. };
  80570. /**
  80571. * Set a vec3 in the shader from a Color3.
  80572. * @param name Define the name of the uniform as defined in the shader
  80573. * @param value Define the value to give to the uniform
  80574. * @return the texture itself allowing "fluent" like uniform updates
  80575. */
  80576. ProceduralTexture.prototype.setColor3 = function (name, value) {
  80577. this._checkUniform(name);
  80578. this._colors3[name] = value;
  80579. return this;
  80580. };
  80581. /**
  80582. * Set a vec4 in the shader from a Color4.
  80583. * @param name Define the name of the uniform as defined in the shader
  80584. * @param value Define the value to give to the uniform
  80585. * @return the texture itself allowing "fluent" like uniform updates
  80586. */
  80587. ProceduralTexture.prototype.setColor4 = function (name, value) {
  80588. this._checkUniform(name);
  80589. this._colors4[name] = value;
  80590. return this;
  80591. };
  80592. /**
  80593. * Set a vec2 in the shader from a Vector2.
  80594. * @param name Define the name of the uniform as defined in the shader
  80595. * @param value Define the value to give to the uniform
  80596. * @return the texture itself allowing "fluent" like uniform updates
  80597. */
  80598. ProceduralTexture.prototype.setVector2 = function (name, value) {
  80599. this._checkUniform(name);
  80600. this._vectors2[name] = value;
  80601. return this;
  80602. };
  80603. /**
  80604. * Set a vec3 in the shader from a Vector3.
  80605. * @param name Define the name of the uniform as defined in the shader
  80606. * @param value Define the value to give to the uniform
  80607. * @return the texture itself allowing "fluent" like uniform updates
  80608. */
  80609. ProceduralTexture.prototype.setVector3 = function (name, value) {
  80610. this._checkUniform(name);
  80611. this._vectors3[name] = value;
  80612. return this;
  80613. };
  80614. /**
  80615. * Set a mat4 in the shader from a MAtrix.
  80616. * @param name Define the name of the uniform as defined in the shader
  80617. * @param value Define the value to give to the uniform
  80618. * @return the texture itself allowing "fluent" like uniform updates
  80619. */
  80620. ProceduralTexture.prototype.setMatrix = function (name, value) {
  80621. this._checkUniform(name);
  80622. this._matrices[name] = value;
  80623. return this;
  80624. };
  80625. /**
  80626. * Render the texture to its associated render target.
  80627. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80628. */
  80629. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80630. var scene = this.getScene();
  80631. if (!scene) {
  80632. return;
  80633. }
  80634. var engine = this._engine;
  80635. // Render
  80636. engine.enableEffect(this._effect);
  80637. engine.setState(false);
  80638. // Texture
  80639. for (var name in this._textures) {
  80640. this._effect.setTexture(name, this._textures[name]);
  80641. }
  80642. // Float
  80643. for (name in this._ints) {
  80644. this._effect.setInt(name, this._ints[name]);
  80645. }
  80646. // Float
  80647. for (name in this._floats) {
  80648. this._effect.setFloat(name, this._floats[name]);
  80649. }
  80650. // Floats
  80651. for (name in this._floatsArrays) {
  80652. this._effect.setArray(name, this._floatsArrays[name]);
  80653. }
  80654. // Color3
  80655. for (name in this._colors3) {
  80656. this._effect.setColor3(name, this._colors3[name]);
  80657. }
  80658. // Color4
  80659. for (name in this._colors4) {
  80660. var color = this._colors4[name];
  80661. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  80662. }
  80663. // Vector2
  80664. for (name in this._vectors2) {
  80665. this._effect.setVector2(name, this._vectors2[name]);
  80666. }
  80667. // Vector3
  80668. for (name in this._vectors3) {
  80669. this._effect.setVector3(name, this._vectors3[name]);
  80670. }
  80671. // Matrix
  80672. for (name in this._matrices) {
  80673. this._effect.setMatrix(name, this._matrices[name]);
  80674. }
  80675. if (!this._texture) {
  80676. return;
  80677. }
  80678. if (this.isCube) {
  80679. for (var face = 0; face < 6; face++) {
  80680. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  80681. // VBOs
  80682. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80683. this._effect.setFloat("face", face);
  80684. // Clear
  80685. if (this.autoClear) {
  80686. engine.clear(scene.clearColor, true, false, false);
  80687. }
  80688. // Draw order
  80689. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80690. // Mipmaps
  80691. if (face === 5) {
  80692. engine.generateMipMapsForCubemap(this._texture);
  80693. }
  80694. }
  80695. }
  80696. else {
  80697. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  80698. // VBOs
  80699. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80700. // Clear
  80701. if (this.autoClear) {
  80702. engine.clear(scene.clearColor, true, false, false);
  80703. }
  80704. // Draw order
  80705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80706. }
  80707. // Unbind
  80708. engine.unBindFramebuffer(this._texture, this.isCube);
  80709. if (this.onGenerated) {
  80710. this.onGenerated();
  80711. }
  80712. this.onGeneratedObservable.notifyObservers(this);
  80713. };
  80714. /**
  80715. * Clone the texture.
  80716. * @returns the cloned texture
  80717. */
  80718. ProceduralTexture.prototype.clone = function () {
  80719. var textureSize = this.getSize();
  80720. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  80721. // Base texture
  80722. newTexture.hasAlpha = this.hasAlpha;
  80723. newTexture.level = this.level;
  80724. // RenderTarget Texture
  80725. newTexture.coordinatesMode = this.coordinatesMode;
  80726. return newTexture;
  80727. };
  80728. /**
  80729. * Dispose the texture and release its asoociated resources.
  80730. */
  80731. ProceduralTexture.prototype.dispose = function () {
  80732. var scene = this.getScene();
  80733. if (!scene) {
  80734. return;
  80735. }
  80736. var index = scene.proceduralTextures.indexOf(this);
  80737. if (index >= 0) {
  80738. scene.proceduralTextures.splice(index, 1);
  80739. }
  80740. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80741. if (vertexBuffer) {
  80742. vertexBuffer.dispose();
  80743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80744. }
  80745. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  80746. this._indexBuffer = null;
  80747. }
  80748. _super.prototype.dispose.call(this);
  80749. };
  80750. __decorate([
  80751. BABYLON.serialize()
  80752. ], ProceduralTexture.prototype, "isEnabled", void 0);
  80753. __decorate([
  80754. BABYLON.serialize()
  80755. ], ProceduralTexture.prototype, "autoClear", void 0);
  80756. __decorate([
  80757. BABYLON.serialize()
  80758. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  80759. __decorate([
  80760. BABYLON.serialize()
  80761. ], ProceduralTexture.prototype, "_size", void 0);
  80762. __decorate([
  80763. BABYLON.serialize()
  80764. ], ProceduralTexture.prototype, "refreshRate", null);
  80765. return ProceduralTexture;
  80766. }(BABYLON.Texture));
  80767. BABYLON.ProceduralTexture = ProceduralTexture;
  80768. })(BABYLON || (BABYLON = {}));
  80769. //# sourceMappingURL=babylon.proceduralTexture.js.map
  80770. var BABYLON;
  80771. (function (BABYLON) {
  80772. /**
  80773. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  80774. * in a given scene.
  80775. */
  80776. var ProceduralTextureSceneComponent = /** @class */ (function () {
  80777. /**
  80778. * Creates a new instance of the component for the given scene
  80779. * @param scene Defines the scene to register the component in
  80780. */
  80781. function ProceduralTextureSceneComponent(scene) {
  80782. /**
  80783. * The component name helpfull to identify the component in the list of scene components.
  80784. */
  80785. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  80786. this.scene = scene;
  80787. this.scene.proceduralTextures = new Array();
  80788. scene.layers = new Array();
  80789. }
  80790. /**
  80791. * Registers the component in a given scene
  80792. */
  80793. ProceduralTextureSceneComponent.prototype.register = function () {
  80794. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  80795. };
  80796. /**
  80797. * Rebuilds the elements related to this component in case of
  80798. * context lost for instance.
  80799. */
  80800. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  80801. // Nothing to do here.
  80802. };
  80803. /**
  80804. * Disposes the component and the associated ressources.
  80805. */
  80806. ProceduralTextureSceneComponent.prototype.dispose = function () {
  80807. // Nothing to do here.
  80808. };
  80809. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  80810. if (this.scene.proceduralTexturesEnabled) {
  80811. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80812. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  80813. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  80814. if (proceduralTexture._shouldRender()) {
  80815. proceduralTexture.render();
  80816. }
  80817. }
  80818. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80819. }
  80820. };
  80821. return ProceduralTextureSceneComponent;
  80822. }());
  80823. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  80824. })(BABYLON || (BABYLON = {}));
  80825. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  80826. var BABYLON;
  80827. (function (BABYLON) {
  80828. /**
  80829. * 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.
  80830. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80831. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80832. */
  80833. var CustomProceduralTexture = /** @class */ (function (_super) {
  80834. __extends(CustomProceduralTexture, _super);
  80835. /**
  80836. * Instantiates a new Custom Procedural Texture.
  80837. * 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.
  80838. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80839. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80840. * @param name Define the name of the texture
  80841. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  80842. * @param size Define the size of the texture to create
  80843. * @param scene Define the scene the texture belongs to
  80844. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80845. * @param generateMipMaps Define if the texture should creates mip maps or not
  80846. */
  80847. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  80848. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  80849. _this._animate = true;
  80850. _this._time = 0;
  80851. _this._texturePath = texturePath;
  80852. //Try to load json
  80853. _this._loadJson(texturePath);
  80854. _this.refreshRate = 1;
  80855. return _this;
  80856. }
  80857. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  80858. var _this = this;
  80859. var noConfigFile = function () {
  80860. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  80861. try {
  80862. _this.setFragment(_this._texturePath);
  80863. }
  80864. catch (ex) {
  80865. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  80866. }
  80867. };
  80868. var configFileUrl = jsonUrl + "/config.json";
  80869. var xhr = new XMLHttpRequest();
  80870. xhr.open("GET", configFileUrl, true);
  80871. xhr.addEventListener("load", function () {
  80872. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  80873. try {
  80874. _this._config = JSON.parse(xhr.response);
  80875. _this.updateShaderUniforms();
  80876. _this.updateTextures();
  80877. _this.setFragment(_this._texturePath + "/custom");
  80878. _this._animate = _this._config.animate;
  80879. _this.refreshRate = _this._config.refreshrate;
  80880. }
  80881. catch (ex) {
  80882. noConfigFile();
  80883. }
  80884. }
  80885. else {
  80886. noConfigFile();
  80887. }
  80888. }, false);
  80889. xhr.addEventListener("error", function () {
  80890. noConfigFile();
  80891. }, false);
  80892. try {
  80893. xhr.send();
  80894. }
  80895. catch (ex) {
  80896. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  80897. }
  80898. };
  80899. /**
  80900. * Is the texture ready to be used ? (rendered at least once)
  80901. * @returns true if ready, otherwise, false.
  80902. */
  80903. CustomProceduralTexture.prototype.isReady = function () {
  80904. if (!_super.prototype.isReady.call(this)) {
  80905. return false;
  80906. }
  80907. for (var name in this._textures) {
  80908. var texture = this._textures[name];
  80909. if (!texture.isReady()) {
  80910. return false;
  80911. }
  80912. }
  80913. return true;
  80914. };
  80915. /**
  80916. * Render the texture to its associated render target.
  80917. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80918. */
  80919. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80920. var scene = this.getScene();
  80921. if (this._animate && scene) {
  80922. this._time += scene.getAnimationRatio() * 0.03;
  80923. this.updateShaderUniforms();
  80924. }
  80925. _super.prototype.render.call(this, useCameraPostProcess);
  80926. };
  80927. /**
  80928. * Update the list of dependant textures samplers in the shader.
  80929. */
  80930. CustomProceduralTexture.prototype.updateTextures = function () {
  80931. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  80932. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  80933. }
  80934. };
  80935. /**
  80936. * Update the uniform values of the procedural texture in the shader.
  80937. */
  80938. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  80939. if (this._config) {
  80940. for (var j = 0; j < this._config.uniforms.length; j++) {
  80941. var uniform = this._config.uniforms[j];
  80942. switch (uniform.type) {
  80943. case "float":
  80944. this.setFloat(uniform.name, uniform.value);
  80945. break;
  80946. case "color3":
  80947. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  80948. break;
  80949. case "color4":
  80950. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  80951. break;
  80952. case "vector2":
  80953. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  80954. break;
  80955. case "vector3":
  80956. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  80957. break;
  80958. }
  80959. }
  80960. }
  80961. this.setFloat("time", this._time);
  80962. };
  80963. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  80964. /**
  80965. * Define if the texture animates or not.
  80966. */
  80967. get: function () {
  80968. return this._animate;
  80969. },
  80970. set: function (value) {
  80971. this._animate = value;
  80972. },
  80973. enumerable: true,
  80974. configurable: true
  80975. });
  80976. return CustomProceduralTexture;
  80977. }(BABYLON.ProceduralTexture));
  80978. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  80979. })(BABYLON || (BABYLON = {}));
  80980. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  80981. var BABYLON;
  80982. (function (BABYLON) {
  80983. /**
  80984. * Manage the gamepad inputs to control a free camera.
  80985. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80986. */
  80987. var FreeCameraGamepadInput = /** @class */ (function () {
  80988. function FreeCameraGamepadInput() {
  80989. /**
  80990. * Defines the gamepad rotation sensiblity.
  80991. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80992. */
  80993. this.gamepadAngularSensibility = 200;
  80994. /**
  80995. * Defines the gamepad move sensiblity.
  80996. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80997. */
  80998. this.gamepadMoveSensibility = 40;
  80999. this._cameraTransform = BABYLON.Matrix.Identity();
  81000. this._deltaTransform = BABYLON.Vector3.Zero();
  81001. this._vector3 = BABYLON.Vector3.Zero();
  81002. this._vector2 = BABYLON.Vector2.Zero();
  81003. }
  81004. /**
  81005. * Attach the input controls to a specific dom element to get the input from.
  81006. * @param element Defines the element the controls should be listened from
  81007. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81008. */
  81009. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81010. var _this = this;
  81011. var manager = this.camera.getScene().gamepadManager;
  81012. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81013. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81014. // prioritize XBOX gamepads.
  81015. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81016. _this.gamepad = gamepad;
  81017. }
  81018. }
  81019. });
  81020. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81021. if (_this.gamepad === gamepad) {
  81022. _this.gamepad = null;
  81023. }
  81024. });
  81025. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81026. };
  81027. /**
  81028. * Detach the current controls from the specified dom element.
  81029. * @param element Defines the element to stop listening the inputs from
  81030. */
  81031. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81032. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81033. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81034. this.gamepad = null;
  81035. };
  81036. /**
  81037. * Update the current camera state depending on the inputs that have been used this frame.
  81038. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81039. */
  81040. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81041. if (this.gamepad && this.gamepad.leftStick) {
  81042. var camera = this.camera;
  81043. var LSValues = this.gamepad.leftStick;
  81044. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81045. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81046. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81047. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81048. var RSValues = this.gamepad.rightStick;
  81049. if (RSValues) {
  81050. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81051. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81052. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81053. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81054. }
  81055. else {
  81056. RSValues = { x: 0, y: 0 };
  81057. }
  81058. if (!camera.rotationQuaternion) {
  81059. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81060. }
  81061. else {
  81062. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81063. }
  81064. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81065. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81066. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81067. camera.cameraDirection.addInPlace(this._deltaTransform);
  81068. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81069. camera.cameraRotation.addInPlace(this._vector2);
  81070. }
  81071. };
  81072. /**
  81073. * Gets the class name of the current intput.
  81074. * @returns the class name
  81075. */
  81076. FreeCameraGamepadInput.prototype.getClassName = function () {
  81077. return "FreeCameraGamepadInput";
  81078. };
  81079. /**
  81080. * Get the friendly name associated with the input class.
  81081. * @returns the input friendly name
  81082. */
  81083. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81084. return "gamepad";
  81085. };
  81086. __decorate([
  81087. BABYLON.serialize()
  81088. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81089. __decorate([
  81090. BABYLON.serialize()
  81091. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81092. return FreeCameraGamepadInput;
  81093. }());
  81094. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81095. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81096. })(BABYLON || (BABYLON = {}));
  81097. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  81098. var BABYLON;
  81099. (function (BABYLON) {
  81100. /**
  81101. * Manage the gamepad inputs to control an arc rotate camera.
  81102. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81103. */
  81104. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81105. function ArcRotateCameraGamepadInput() {
  81106. /**
  81107. * Defines the gamepad rotation sensiblity.
  81108. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81109. */
  81110. this.gamepadRotationSensibility = 80;
  81111. /**
  81112. * Defines the gamepad move sensiblity.
  81113. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81114. */
  81115. this.gamepadMoveSensibility = 40;
  81116. }
  81117. /**
  81118. * Attach the input controls to a specific dom element to get the input from.
  81119. * @param element Defines the element the controls should be listened from
  81120. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81121. */
  81122. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81123. var _this = this;
  81124. var manager = this.camera.getScene().gamepadManager;
  81125. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81126. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81127. // prioritize XBOX gamepads.
  81128. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81129. _this.gamepad = gamepad;
  81130. }
  81131. }
  81132. });
  81133. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81134. if (_this.gamepad === gamepad) {
  81135. _this.gamepad = null;
  81136. }
  81137. });
  81138. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81139. };
  81140. /**
  81141. * Detach the current controls from the specified dom element.
  81142. * @param element Defines the element to stop listening the inputs from
  81143. */
  81144. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81145. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81146. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81147. this.gamepad = null;
  81148. };
  81149. /**
  81150. * Update the current camera state depending on the inputs that have been used this frame.
  81151. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81152. */
  81153. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81154. if (this.gamepad) {
  81155. var camera = this.camera;
  81156. var RSValues = this.gamepad.rightStick;
  81157. if (RSValues) {
  81158. if (RSValues.x != 0) {
  81159. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81160. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81161. camera.inertialAlphaOffset += normalizedRX;
  81162. }
  81163. }
  81164. if (RSValues.y != 0) {
  81165. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81166. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81167. camera.inertialBetaOffset += normalizedRY;
  81168. }
  81169. }
  81170. }
  81171. var LSValues = this.gamepad.leftStick;
  81172. if (LSValues && LSValues.y != 0) {
  81173. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81174. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81175. this.camera.inertialRadiusOffset -= normalizedLY;
  81176. }
  81177. }
  81178. }
  81179. };
  81180. /**
  81181. * Gets the class name of the current intput.
  81182. * @returns the class name
  81183. */
  81184. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81185. return "ArcRotateCameraGamepadInput";
  81186. };
  81187. /**
  81188. * Get the friendly name associated with the input class.
  81189. * @returns the input friendly name
  81190. */
  81191. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81192. return "gamepad";
  81193. };
  81194. __decorate([
  81195. BABYLON.serialize()
  81196. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81197. __decorate([
  81198. BABYLON.serialize()
  81199. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81200. return ArcRotateCameraGamepadInput;
  81201. }());
  81202. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81203. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81204. })(BABYLON || (BABYLON = {}));
  81205. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  81206. var BABYLON;
  81207. (function (BABYLON) {
  81208. /**
  81209. * Manager for handling gamepads
  81210. */
  81211. var GamepadManager = /** @class */ (function () {
  81212. /**
  81213. * Initializes the gamepad manager
  81214. * @param _scene BabylonJS scene
  81215. */
  81216. function GamepadManager(_scene) {
  81217. var _this = this;
  81218. this._scene = _scene;
  81219. this._babylonGamepads = [];
  81220. this._oneGamepadConnected = false;
  81221. /** @hidden */
  81222. this._isMonitoring = false;
  81223. /**
  81224. * observable to be triggered when the gamepad controller has been disconnected
  81225. */
  81226. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81227. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81228. this._gamepadEventSupported = false;
  81229. }
  81230. else {
  81231. this._gamepadEventSupported = 'GamepadEvent' in window;
  81232. this._gamepadSupport = (navigator.getGamepads ||
  81233. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81234. }
  81235. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81236. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81237. for (var i in _this._babylonGamepads) {
  81238. var gamepad = _this._babylonGamepads[i];
  81239. if (gamepad && gamepad._isConnected) {
  81240. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81241. }
  81242. }
  81243. });
  81244. this._onGamepadConnectedEvent = function (evt) {
  81245. var gamepad = evt.gamepad;
  81246. if (gamepad.index in _this._babylonGamepads) {
  81247. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81248. return;
  81249. }
  81250. }
  81251. var newGamepad;
  81252. if (_this._babylonGamepads[gamepad.index]) {
  81253. newGamepad = _this._babylonGamepads[gamepad.index];
  81254. newGamepad.browserGamepad = gamepad;
  81255. newGamepad._isConnected = true;
  81256. }
  81257. else {
  81258. newGamepad = _this._addNewGamepad(gamepad);
  81259. }
  81260. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81261. _this._startMonitoringGamepads();
  81262. };
  81263. this._onGamepadDisconnectedEvent = function (evt) {
  81264. var gamepad = evt.gamepad;
  81265. // Remove the gamepad from the list of gamepads to monitor.
  81266. for (var i in _this._babylonGamepads) {
  81267. if (_this._babylonGamepads[i].index === gamepad.index) {
  81268. var disconnectedGamepad = _this._babylonGamepads[i];
  81269. disconnectedGamepad._isConnected = false;
  81270. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81271. break;
  81272. }
  81273. }
  81274. };
  81275. if (this._gamepadSupport) {
  81276. //first add already-connected gamepads
  81277. this._updateGamepadObjects();
  81278. if (this._babylonGamepads.length) {
  81279. this._startMonitoringGamepads();
  81280. }
  81281. // Checking if the gamepad connected event is supported (like in Firefox)
  81282. if (this._gamepadEventSupported) {
  81283. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81284. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81285. }
  81286. else {
  81287. this._startMonitoringGamepads();
  81288. }
  81289. }
  81290. }
  81291. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81292. /**
  81293. * The gamepads in the game pad manager
  81294. */
  81295. get: function () {
  81296. return this._babylonGamepads;
  81297. },
  81298. enumerable: true,
  81299. configurable: true
  81300. });
  81301. /**
  81302. * Get the gamepad controllers based on type
  81303. * @param type The type of gamepad controller
  81304. * @returns Nullable gamepad
  81305. */
  81306. GamepadManager.prototype.getGamepadByType = function (type) {
  81307. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81308. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81309. var gamepad = _a[_i];
  81310. if (gamepad && gamepad.type === type) {
  81311. return gamepad;
  81312. }
  81313. }
  81314. return null;
  81315. };
  81316. /**
  81317. * Disposes the gamepad manager
  81318. */
  81319. GamepadManager.prototype.dispose = function () {
  81320. if (this._gamepadEventSupported) {
  81321. if (this._onGamepadConnectedEvent) {
  81322. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81323. }
  81324. if (this._onGamepadDisconnectedEvent) {
  81325. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81326. }
  81327. this._onGamepadConnectedEvent = null;
  81328. this._onGamepadDisconnectedEvent = null;
  81329. }
  81330. this._babylonGamepads.forEach(function (gamepad) {
  81331. gamepad.dispose();
  81332. });
  81333. this.onGamepadConnectedObservable.clear();
  81334. this.onGamepadDisconnectedObservable.clear();
  81335. this._oneGamepadConnected = false;
  81336. this._stopMonitoringGamepads();
  81337. this._babylonGamepads = [];
  81338. };
  81339. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81340. if (!this._oneGamepadConnected) {
  81341. this._oneGamepadConnected = true;
  81342. }
  81343. var newGamepad;
  81344. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81345. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81346. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81347. }
  81348. // if pose is supported, use the (WebVR) pose enabled controller
  81349. else if (gamepad.pose) {
  81350. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81351. }
  81352. else {
  81353. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81354. }
  81355. this._babylonGamepads[newGamepad.index] = newGamepad;
  81356. return newGamepad;
  81357. };
  81358. GamepadManager.prototype._startMonitoringGamepads = function () {
  81359. if (!this._isMonitoring) {
  81360. this._isMonitoring = true;
  81361. //back-comp
  81362. if (!this._scene) {
  81363. this._checkGamepadsStatus();
  81364. }
  81365. }
  81366. };
  81367. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81368. this._isMonitoring = false;
  81369. };
  81370. /** @hidden */
  81371. GamepadManager.prototype._checkGamepadsStatus = function () {
  81372. var _this = this;
  81373. // Hack to be compatible Chrome
  81374. this._updateGamepadObjects();
  81375. for (var i in this._babylonGamepads) {
  81376. var gamepad = this._babylonGamepads[i];
  81377. if (!gamepad || !gamepad.isConnected) {
  81378. continue;
  81379. }
  81380. gamepad.update();
  81381. }
  81382. if (this._isMonitoring && !this._scene) {
  81383. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81384. }
  81385. };
  81386. // This function is called only on Chrome, which does not properly support
  81387. // connection/disconnection events and forces you to recopy again the gamepad object
  81388. GamepadManager.prototype._updateGamepadObjects = function () {
  81389. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81390. for (var i = 0; i < gamepads.length; i++) {
  81391. var gamepad = gamepads[i];
  81392. if (gamepad) {
  81393. if (!this._babylonGamepads[gamepad.index]) {
  81394. var newGamepad = this._addNewGamepad(gamepad);
  81395. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81396. }
  81397. else {
  81398. // Forced to copy again this object for Chrome for unknown reason
  81399. this._babylonGamepads[i].browserGamepad = gamepad;
  81400. if (!this._babylonGamepads[i].isConnected) {
  81401. this._babylonGamepads[i]._isConnected = true;
  81402. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81403. }
  81404. }
  81405. }
  81406. }
  81407. };
  81408. return GamepadManager;
  81409. }());
  81410. BABYLON.GamepadManager = GamepadManager;
  81411. })(BABYLON || (BABYLON = {}));
  81412. //# sourceMappingURL=babylon.gamepadManager.js.map
  81413. var BABYLON;
  81414. (function (BABYLON) {
  81415. /**
  81416. * Represents a gamepad control stick position
  81417. */
  81418. var StickValues = /** @class */ (function () {
  81419. /**
  81420. * Initializes the gamepad x and y control stick values
  81421. * @param x The x component of the gamepad control stick value
  81422. * @param y The y component of the gamepad control stick value
  81423. */
  81424. function StickValues(
  81425. /**
  81426. * The x component of the control stick
  81427. */
  81428. x,
  81429. /**
  81430. * The y component of the control stick
  81431. */
  81432. y) {
  81433. this.x = x;
  81434. this.y = y;
  81435. }
  81436. return StickValues;
  81437. }());
  81438. BABYLON.StickValues = StickValues;
  81439. /**
  81440. * Represents a gamepad
  81441. */
  81442. var Gamepad = /** @class */ (function () {
  81443. /**
  81444. * Initializes the gamepad
  81445. * @param id The id of the gamepad
  81446. * @param index The index of the gamepad
  81447. * @param browserGamepad The browser gamepad
  81448. * @param leftStickX The x component of the left joystick
  81449. * @param leftStickY The y component of the left joystick
  81450. * @param rightStickX The x component of the right joystick
  81451. * @param rightStickY The y component of the right joystick
  81452. */
  81453. function Gamepad(
  81454. /**
  81455. * The id of the gamepad
  81456. */
  81457. id,
  81458. /**
  81459. * The index of the gamepad
  81460. */
  81461. index,
  81462. /**
  81463. * The browser gamepad
  81464. */
  81465. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  81466. if (leftStickX === void 0) { leftStickX = 0; }
  81467. if (leftStickY === void 0) { leftStickY = 1; }
  81468. if (rightStickX === void 0) { rightStickX = 2; }
  81469. if (rightStickY === void 0) { rightStickY = 3; }
  81470. this.id = id;
  81471. this.index = index;
  81472. this.browserGamepad = browserGamepad;
  81473. this._leftStick = { x: 0, y: 0 };
  81474. this._rightStick = { x: 0, y: 0 };
  81475. /** @hidden */
  81476. this._isConnected = true;
  81477. /**
  81478. * Specifies whether the left control stick should be Y-inverted
  81479. */
  81480. this._invertLeftStickY = false;
  81481. this.type = Gamepad.GAMEPAD;
  81482. this._leftStickAxisX = leftStickX;
  81483. this._leftStickAxisY = leftStickY;
  81484. this._rightStickAxisX = rightStickX;
  81485. this._rightStickAxisY = rightStickY;
  81486. if (this.browserGamepad.axes.length >= 2) {
  81487. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81488. }
  81489. if (this.browserGamepad.axes.length >= 4) {
  81490. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81491. }
  81492. }
  81493. Object.defineProperty(Gamepad.prototype, "isConnected", {
  81494. /**
  81495. * Specifies if the gamepad has been connected
  81496. */
  81497. get: function () {
  81498. return this._isConnected;
  81499. },
  81500. enumerable: true,
  81501. configurable: true
  81502. });
  81503. /**
  81504. * Callback triggered when the left joystick has changed
  81505. * @param callback
  81506. */
  81507. Gamepad.prototype.onleftstickchanged = function (callback) {
  81508. this._onleftstickchanged = callback;
  81509. };
  81510. /**
  81511. * Callback triggered when the right joystick has changed
  81512. * @param callback
  81513. */
  81514. Gamepad.prototype.onrightstickchanged = function (callback) {
  81515. this._onrightstickchanged = callback;
  81516. };
  81517. Object.defineProperty(Gamepad.prototype, "leftStick", {
  81518. /**
  81519. * Gets the left joystick
  81520. */
  81521. get: function () {
  81522. return this._leftStick;
  81523. },
  81524. /**
  81525. * Sets the left joystick values
  81526. */
  81527. set: function (newValues) {
  81528. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  81529. this._onleftstickchanged(newValues);
  81530. }
  81531. this._leftStick = newValues;
  81532. },
  81533. enumerable: true,
  81534. configurable: true
  81535. });
  81536. Object.defineProperty(Gamepad.prototype, "rightStick", {
  81537. /**
  81538. * Gets the right joystick
  81539. */
  81540. get: function () {
  81541. return this._rightStick;
  81542. },
  81543. /**
  81544. * Sets the right joystick value
  81545. */
  81546. set: function (newValues) {
  81547. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  81548. this._onrightstickchanged(newValues);
  81549. }
  81550. this._rightStick = newValues;
  81551. },
  81552. enumerable: true,
  81553. configurable: true
  81554. });
  81555. /**
  81556. * Updates the gamepad joystick positions
  81557. */
  81558. Gamepad.prototype.update = function () {
  81559. if (this._leftStick) {
  81560. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81561. if (this._invertLeftStickY) {
  81562. this.leftStick.y *= -1;
  81563. }
  81564. }
  81565. if (this._rightStick) {
  81566. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81567. }
  81568. };
  81569. /**
  81570. * Disposes the gamepad
  81571. */
  81572. Gamepad.prototype.dispose = function () {
  81573. };
  81574. /**
  81575. * Represents a gamepad controller
  81576. */
  81577. Gamepad.GAMEPAD = 0;
  81578. /**
  81579. * Represents a generic controller
  81580. */
  81581. Gamepad.GENERIC = 1;
  81582. /**
  81583. * Represents an XBox controller
  81584. */
  81585. Gamepad.XBOX = 2;
  81586. /**
  81587. * Represents a pose-enabled controller
  81588. */
  81589. Gamepad.POSE_ENABLED = 3;
  81590. return Gamepad;
  81591. }());
  81592. BABYLON.Gamepad = Gamepad;
  81593. /**
  81594. * Represents a generic gamepad
  81595. */
  81596. var GenericPad = /** @class */ (function (_super) {
  81597. __extends(GenericPad, _super);
  81598. /**
  81599. * Initializes the generic gamepad
  81600. * @param id The id of the generic gamepad
  81601. * @param index The index of the generic gamepad
  81602. * @param browserGamepad The browser gamepad
  81603. */
  81604. function GenericPad(id, index, browserGamepad) {
  81605. var _this = _super.call(this, id, index, browserGamepad) || this;
  81606. /**
  81607. * Observable triggered when a button has been pressed
  81608. */
  81609. _this.onButtonDownObservable = new BABYLON.Observable();
  81610. /**
  81611. * Observable triggered when a button has been released
  81612. */
  81613. _this.onButtonUpObservable = new BABYLON.Observable();
  81614. _this.type = Gamepad.GENERIC;
  81615. _this._buttons = new Array(browserGamepad.buttons.length);
  81616. return _this;
  81617. }
  81618. /**
  81619. * Callback triggered when a button has been pressed
  81620. * @param callback Called when a button has been pressed
  81621. */
  81622. GenericPad.prototype.onbuttondown = function (callback) {
  81623. this._onbuttondown = callback;
  81624. };
  81625. /**
  81626. * Callback triggered when a button has been released
  81627. * @param callback Called when a button has been released
  81628. */
  81629. GenericPad.prototype.onbuttonup = function (callback) {
  81630. this._onbuttonup = callback;
  81631. };
  81632. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  81633. if (newValue !== currentValue) {
  81634. if (newValue === 1) {
  81635. if (this._onbuttondown) {
  81636. this._onbuttondown(buttonIndex);
  81637. }
  81638. this.onButtonDownObservable.notifyObservers(buttonIndex);
  81639. }
  81640. if (newValue === 0) {
  81641. if (this._onbuttonup) {
  81642. this._onbuttonup(buttonIndex);
  81643. }
  81644. this.onButtonUpObservable.notifyObservers(buttonIndex);
  81645. }
  81646. }
  81647. return newValue;
  81648. };
  81649. /**
  81650. * Updates the generic gamepad
  81651. */
  81652. GenericPad.prototype.update = function () {
  81653. _super.prototype.update.call(this);
  81654. for (var index = 0; index < this._buttons.length; index++) {
  81655. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  81656. }
  81657. };
  81658. /**
  81659. * Disposes the generic gamepad
  81660. */
  81661. GenericPad.prototype.dispose = function () {
  81662. _super.prototype.dispose.call(this);
  81663. this.onButtonDownObservable.clear();
  81664. this.onButtonUpObservable.clear();
  81665. };
  81666. return GenericPad;
  81667. }(Gamepad));
  81668. BABYLON.GenericPad = GenericPad;
  81669. })(BABYLON || (BABYLON = {}));
  81670. //# sourceMappingURL=babylon.gamepad.js.map
  81671. var BABYLON;
  81672. (function (BABYLON) {
  81673. /**
  81674. * Defines supported buttons for XBox360 compatible gamepads
  81675. */
  81676. var Xbox360Button;
  81677. (function (Xbox360Button) {
  81678. /** A */
  81679. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  81680. /** B */
  81681. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  81682. /** X */
  81683. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  81684. /** Y */
  81685. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  81686. /** Start */
  81687. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  81688. /** Back */
  81689. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  81690. /** Left button */
  81691. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  81692. /** Right button */
  81693. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  81694. /** Left stick */
  81695. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  81696. /** Right stick */
  81697. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  81698. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  81699. /** Defines values for XBox360 DPad */
  81700. var Xbox360Dpad;
  81701. (function (Xbox360Dpad) {
  81702. /** Up */
  81703. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  81704. /** Down */
  81705. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  81706. /** Left */
  81707. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  81708. /** Right */
  81709. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  81710. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  81711. /**
  81712. * Defines a XBox360 gamepad
  81713. */
  81714. var Xbox360Pad = /** @class */ (function (_super) {
  81715. __extends(Xbox360Pad, _super);
  81716. /**
  81717. * Creates a new XBox360 gamepad object
  81718. * @param id defines the id of this gamepad
  81719. * @param index defines its index
  81720. * @param gamepad defines the internal HTML gamepad object
  81721. * @param xboxOne defines if it is a XBox One gamepad
  81722. */
  81723. function Xbox360Pad(id, index, gamepad, xboxOne) {
  81724. if (xboxOne === void 0) { xboxOne = false; }
  81725. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  81726. _this._leftTrigger = 0;
  81727. _this._rightTrigger = 0;
  81728. /** Observable raised when a button is pressed */
  81729. _this.onButtonDownObservable = new BABYLON.Observable();
  81730. /** Observable raised when a button is released */
  81731. _this.onButtonUpObservable = new BABYLON.Observable();
  81732. /** Observable raised when a pad is pressed */
  81733. _this.onPadDownObservable = new BABYLON.Observable();
  81734. /** Observable raised when a pad is released */
  81735. _this.onPadUpObservable = new BABYLON.Observable();
  81736. _this._buttonA = 0;
  81737. _this._buttonB = 0;
  81738. _this._buttonX = 0;
  81739. _this._buttonY = 0;
  81740. _this._buttonBack = 0;
  81741. _this._buttonStart = 0;
  81742. _this._buttonLB = 0;
  81743. _this._buttonRB = 0;
  81744. _this._buttonLeftStick = 0;
  81745. _this._buttonRightStick = 0;
  81746. _this._dPadUp = 0;
  81747. _this._dPadDown = 0;
  81748. _this._dPadLeft = 0;
  81749. _this._dPadRight = 0;
  81750. _this._isXboxOnePad = false;
  81751. _this.type = BABYLON.Gamepad.XBOX;
  81752. _this._isXboxOnePad = xboxOne;
  81753. return _this;
  81754. }
  81755. /**
  81756. * Defines the callback to call when left trigger is pressed
  81757. * @param callback defines the callback to use
  81758. */
  81759. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  81760. this._onlefttriggerchanged = callback;
  81761. };
  81762. /**
  81763. * Defines the callback to call when right trigger is pressed
  81764. * @param callback defines the callback to use
  81765. */
  81766. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  81767. this._onrighttriggerchanged = callback;
  81768. };
  81769. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  81770. /**
  81771. * Gets the left trigger value
  81772. */
  81773. get: function () {
  81774. return this._leftTrigger;
  81775. },
  81776. /**
  81777. * Sets the left trigger value
  81778. */
  81779. set: function (newValue) {
  81780. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  81781. this._onlefttriggerchanged(newValue);
  81782. }
  81783. this._leftTrigger = newValue;
  81784. },
  81785. enumerable: true,
  81786. configurable: true
  81787. });
  81788. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  81789. /**
  81790. * Gets the right trigger value
  81791. */
  81792. get: function () {
  81793. return this._rightTrigger;
  81794. },
  81795. /**
  81796. * Sets the right trigger value
  81797. */
  81798. set: function (newValue) {
  81799. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  81800. this._onrighttriggerchanged(newValue);
  81801. }
  81802. this._rightTrigger = newValue;
  81803. },
  81804. enumerable: true,
  81805. configurable: true
  81806. });
  81807. /**
  81808. * Defines the callback to call when a button is pressed
  81809. * @param callback defines the callback to use
  81810. */
  81811. Xbox360Pad.prototype.onbuttondown = function (callback) {
  81812. this._onbuttondown = callback;
  81813. };
  81814. /**
  81815. * Defines the callback to call when a button is released
  81816. * @param callback defines the callback to use
  81817. */
  81818. Xbox360Pad.prototype.onbuttonup = function (callback) {
  81819. this._onbuttonup = callback;
  81820. };
  81821. /**
  81822. * Defines the callback to call when a pad is pressed
  81823. * @param callback defines the callback to use
  81824. */
  81825. Xbox360Pad.prototype.ondpaddown = function (callback) {
  81826. this._ondpaddown = callback;
  81827. };
  81828. /**
  81829. * Defines the callback to call when a pad is released
  81830. * @param callback defines the callback to use
  81831. */
  81832. Xbox360Pad.prototype.ondpadup = function (callback) {
  81833. this._ondpadup = callback;
  81834. };
  81835. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  81836. if (newValue !== currentValue) {
  81837. if (newValue === 1) {
  81838. if (this._onbuttondown) {
  81839. this._onbuttondown(buttonType);
  81840. }
  81841. this.onButtonDownObservable.notifyObservers(buttonType);
  81842. }
  81843. if (newValue === 0) {
  81844. if (this._onbuttonup) {
  81845. this._onbuttonup(buttonType);
  81846. }
  81847. this.onButtonUpObservable.notifyObservers(buttonType);
  81848. }
  81849. }
  81850. return newValue;
  81851. };
  81852. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  81853. if (newValue !== currentValue) {
  81854. if (newValue === 1) {
  81855. if (this._ondpaddown) {
  81856. this._ondpaddown(buttonType);
  81857. }
  81858. this.onPadDownObservable.notifyObservers(buttonType);
  81859. }
  81860. if (newValue === 0) {
  81861. if (this._ondpadup) {
  81862. this._ondpadup(buttonType);
  81863. }
  81864. this.onPadUpObservable.notifyObservers(buttonType);
  81865. }
  81866. }
  81867. return newValue;
  81868. };
  81869. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  81870. /**
  81871. * Gets the value of the `A` button
  81872. */
  81873. get: function () {
  81874. return this._buttonA;
  81875. },
  81876. /**
  81877. * Sets the value of the `A` button
  81878. */
  81879. set: function (value) {
  81880. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  81881. },
  81882. enumerable: true,
  81883. configurable: true
  81884. });
  81885. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  81886. /**
  81887. * Gets the value of the `B` button
  81888. */
  81889. get: function () {
  81890. return this._buttonB;
  81891. },
  81892. /**
  81893. * Sets the value of the `B` button
  81894. */
  81895. set: function (value) {
  81896. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  81897. },
  81898. enumerable: true,
  81899. configurable: true
  81900. });
  81901. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  81902. /**
  81903. * Gets the value of the `X` button
  81904. */
  81905. get: function () {
  81906. return this._buttonX;
  81907. },
  81908. /**
  81909. * Sets the value of the `X` button
  81910. */
  81911. set: function (value) {
  81912. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  81913. },
  81914. enumerable: true,
  81915. configurable: true
  81916. });
  81917. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  81918. /**
  81919. * Gets the value of the `Y` button
  81920. */
  81921. get: function () {
  81922. return this._buttonY;
  81923. },
  81924. /**
  81925. * Sets the value of the `Y` button
  81926. */
  81927. set: function (value) {
  81928. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  81929. },
  81930. enumerable: true,
  81931. configurable: true
  81932. });
  81933. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  81934. /**
  81935. * Gets the value of the `Start` button
  81936. */
  81937. get: function () {
  81938. return this._buttonStart;
  81939. },
  81940. /**
  81941. * Sets the value of the `Start` button
  81942. */
  81943. set: function (value) {
  81944. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  81945. },
  81946. enumerable: true,
  81947. configurable: true
  81948. });
  81949. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  81950. /**
  81951. * Gets the value of the `Back` button
  81952. */
  81953. get: function () {
  81954. return this._buttonBack;
  81955. },
  81956. /**
  81957. * Sets the value of the `Back` button
  81958. */
  81959. set: function (value) {
  81960. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  81966. /**
  81967. * Gets the value of the `Left` button
  81968. */
  81969. get: function () {
  81970. return this._buttonLB;
  81971. },
  81972. /**
  81973. * Sets the value of the `Left` button
  81974. */
  81975. set: function (value) {
  81976. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  81977. },
  81978. enumerable: true,
  81979. configurable: true
  81980. });
  81981. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  81982. /**
  81983. * Gets the value of the `Right` button
  81984. */
  81985. get: function () {
  81986. return this._buttonRB;
  81987. },
  81988. /**
  81989. * Sets the value of the `Right` button
  81990. */
  81991. set: function (value) {
  81992. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  81993. },
  81994. enumerable: true,
  81995. configurable: true
  81996. });
  81997. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  81998. /**
  81999. * Gets the value of the Left joystick
  82000. */
  82001. get: function () {
  82002. return this._buttonLeftStick;
  82003. },
  82004. /**
  82005. * Sets the value of the Left joystick
  82006. */
  82007. set: function (value) {
  82008. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  82009. },
  82010. enumerable: true,
  82011. configurable: true
  82012. });
  82013. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  82014. /**
  82015. * Gets the value of the Right joystick
  82016. */
  82017. get: function () {
  82018. return this._buttonRightStick;
  82019. },
  82020. /**
  82021. * Sets the value of the Right joystick
  82022. */
  82023. set: function (value) {
  82024. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82025. },
  82026. enumerable: true,
  82027. configurable: true
  82028. });
  82029. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82030. /**
  82031. * Gets the value of D-pad up
  82032. */
  82033. get: function () {
  82034. return this._dPadUp;
  82035. },
  82036. /**
  82037. * Sets the value of D-pad up
  82038. */
  82039. set: function (value) {
  82040. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82041. },
  82042. enumerable: true,
  82043. configurable: true
  82044. });
  82045. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82046. /**
  82047. * Gets the value of D-pad down
  82048. */
  82049. get: function () {
  82050. return this._dPadDown;
  82051. },
  82052. /**
  82053. * Sets the value of D-pad down
  82054. */
  82055. set: function (value) {
  82056. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82057. },
  82058. enumerable: true,
  82059. configurable: true
  82060. });
  82061. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82062. /**
  82063. * Gets the value of D-pad left
  82064. */
  82065. get: function () {
  82066. return this._dPadLeft;
  82067. },
  82068. /**
  82069. * Sets the value of D-pad left
  82070. */
  82071. set: function (value) {
  82072. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82073. },
  82074. enumerable: true,
  82075. configurable: true
  82076. });
  82077. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82078. /**
  82079. * Gets the value of D-pad right
  82080. */
  82081. get: function () {
  82082. return this._dPadRight;
  82083. },
  82084. /**
  82085. * Sets the value of D-pad right
  82086. */
  82087. set: function (value) {
  82088. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. /**
  82094. * Force the gamepad to synchronize with device values
  82095. */
  82096. Xbox360Pad.prototype.update = function () {
  82097. _super.prototype.update.call(this);
  82098. if (this._isXboxOnePad) {
  82099. this.buttonA = this.browserGamepad.buttons[0].value;
  82100. this.buttonB = this.browserGamepad.buttons[1].value;
  82101. this.buttonX = this.browserGamepad.buttons[2].value;
  82102. this.buttonY = this.browserGamepad.buttons[3].value;
  82103. this.buttonLB = this.browserGamepad.buttons[4].value;
  82104. this.buttonRB = this.browserGamepad.buttons[5].value;
  82105. this.leftTrigger = this.browserGamepad.axes[2];
  82106. this.rightTrigger = this.browserGamepad.axes[5];
  82107. this.buttonBack = this.browserGamepad.buttons[9].value;
  82108. this.buttonStart = this.browserGamepad.buttons[8].value;
  82109. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82110. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82111. this.dPadUp = this.browserGamepad.buttons[11].value;
  82112. this.dPadDown = this.browserGamepad.buttons[12].value;
  82113. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82114. this.dPadRight = this.browserGamepad.buttons[14].value;
  82115. }
  82116. else {
  82117. this.buttonA = this.browserGamepad.buttons[0].value;
  82118. this.buttonB = this.browserGamepad.buttons[1].value;
  82119. this.buttonX = this.browserGamepad.buttons[2].value;
  82120. this.buttonY = this.browserGamepad.buttons[3].value;
  82121. this.buttonLB = this.browserGamepad.buttons[4].value;
  82122. this.buttonRB = this.browserGamepad.buttons[5].value;
  82123. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82124. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82125. this.buttonBack = this.browserGamepad.buttons[8].value;
  82126. this.buttonStart = this.browserGamepad.buttons[9].value;
  82127. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82128. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82129. this.dPadUp = this.browserGamepad.buttons[12].value;
  82130. this.dPadDown = this.browserGamepad.buttons[13].value;
  82131. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82132. this.dPadRight = this.browserGamepad.buttons[15].value;
  82133. }
  82134. };
  82135. /**
  82136. * Disposes the gamepad
  82137. */
  82138. Xbox360Pad.prototype.dispose = function () {
  82139. _super.prototype.dispose.call(this);
  82140. this.onButtonDownObservable.clear();
  82141. this.onButtonUpObservable.clear();
  82142. this.onPadDownObservable.clear();
  82143. this.onPadUpObservable.clear();
  82144. };
  82145. return Xbox360Pad;
  82146. }(BABYLON.Gamepad));
  82147. BABYLON.Xbox360Pad = Xbox360Pad;
  82148. })(BABYLON || (BABYLON = {}));
  82149. //# sourceMappingURL=babylon.xboxGamepad.js.map
  82150. var BABYLON;
  82151. (function (BABYLON) {
  82152. /**
  82153. * Defines the types of pose enabled controllers that are supported
  82154. */
  82155. var PoseEnabledControllerType;
  82156. (function (PoseEnabledControllerType) {
  82157. /**
  82158. * HTC Vive
  82159. */
  82160. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82161. /**
  82162. * Oculus Rift
  82163. */
  82164. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82165. /**
  82166. * Windows mixed reality
  82167. */
  82168. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82169. /**
  82170. * Samsung gear VR
  82171. */
  82172. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82173. /**
  82174. * Google Daydream
  82175. */
  82176. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82177. /**
  82178. * Generic
  82179. */
  82180. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82181. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82182. /**
  82183. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82184. */
  82185. var PoseEnabledControllerHelper = /** @class */ (function () {
  82186. function PoseEnabledControllerHelper() {
  82187. }
  82188. /**
  82189. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82190. * @param vrGamepad the gamepad to initialized
  82191. * @returns a vr controller of the type the gamepad identified as
  82192. */
  82193. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82194. // Oculus Touch
  82195. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82196. return new BABYLON.OculusTouchController(vrGamepad);
  82197. }
  82198. // Windows Mixed Reality controllers
  82199. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82200. return new BABYLON.WindowsMotionController(vrGamepad);
  82201. }
  82202. // HTC Vive
  82203. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82204. return new BABYLON.ViveController(vrGamepad);
  82205. }
  82206. // Samsung/Oculus Gear VR or Oculus Go
  82207. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82208. return new BABYLON.GearVRController(vrGamepad);
  82209. }
  82210. // Google Daydream
  82211. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82212. return new BABYLON.DaydreamController(vrGamepad);
  82213. }
  82214. // Generic
  82215. else {
  82216. return new BABYLON.GenericController(vrGamepad);
  82217. }
  82218. };
  82219. return PoseEnabledControllerHelper;
  82220. }());
  82221. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82222. /**
  82223. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82224. */
  82225. var PoseEnabledController = /** @class */ (function (_super) {
  82226. __extends(PoseEnabledController, _super);
  82227. /**
  82228. * Creates a new PoseEnabledController from a gamepad
  82229. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82230. */
  82231. function PoseEnabledController(browserGamepad) {
  82232. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82233. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82234. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82235. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82236. /**
  82237. * The device position in babylon space
  82238. */
  82239. _this.devicePosition = BABYLON.Vector3.Zero();
  82240. /**
  82241. * The device rotation in babylon space
  82242. */
  82243. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82244. /**
  82245. * The scale factor of the device in babylon space
  82246. */
  82247. _this.deviceScaleFactor = 1;
  82248. // Used to convert 6dof controllers to 3dof
  82249. _this._trackPosition = true;
  82250. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82251. _this._draggedRoomRotation = 0;
  82252. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82253. /**
  82254. * Internal, matrix used to convert room space to babylon space
  82255. * @hidden
  82256. */
  82257. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82258. /**
  82259. * Node to be used when casting a ray from the controller
  82260. * @hidden
  82261. */
  82262. _this._pointingPoseNode = null;
  82263. _this._workingMatrix = BABYLON.Matrix.Identity();
  82264. /**
  82265. * @hidden
  82266. */
  82267. _this._meshAttachedObservable = new BABYLON.Observable();
  82268. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82269. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82270. _this.position = BABYLON.Vector3.Zero();
  82271. _this.rotationQuaternion = new BABYLON.Quaternion();
  82272. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82273. _this._calculatedRotation = new BABYLON.Quaternion();
  82274. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82275. return _this;
  82276. }
  82277. /**
  82278. * @hidden
  82279. */
  82280. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82281. if (this._trackPosition) {
  82282. this._calculatedPosition.copyFrom(fixedPosition);
  82283. this._trackPosition = false;
  82284. }
  82285. };
  82286. /**
  82287. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82288. */
  82289. PoseEnabledController.prototype.update = function () {
  82290. _super.prototype.update.call(this);
  82291. this._updatePoseAndMesh();
  82292. };
  82293. /**
  82294. * Updates only the pose device and mesh without doing any button event checking
  82295. */
  82296. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82297. var pose = this.browserGamepad.pose;
  82298. this.updateFromDevice(pose);
  82299. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82300. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82301. camera._computeDevicePosition();
  82302. this._deviceToWorld.setTranslation(camera.devicePosition);
  82303. if (camera.deviceRotationQuaternion) {
  82304. var camera = camera;
  82305. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82306. // Find the radian distance away that the headset is from the controllers rotation
  82307. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82308. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82309. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82310. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82311. this._draggedRoomRotation += rotationAmount;
  82312. // Rotate controller around headset
  82313. var sin = Math.sin(-rotationAmount);
  82314. var cos = Math.cos(-rotationAmount);
  82315. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82316. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82317. }
  82318. }
  82319. }
  82320. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82321. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82322. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82323. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82324. if (this._mesh) {
  82325. this._mesh.position.copyFrom(this.devicePosition);
  82326. if (this._mesh.rotationQuaternion) {
  82327. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82328. }
  82329. }
  82330. };
  82331. /**
  82332. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82333. * @param poseData raw pose fromthe device
  82334. */
  82335. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82336. if (poseData) {
  82337. this.rawPose = poseData;
  82338. if (poseData.position) {
  82339. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82340. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82341. this._deviceRoomPosition.z *= -1;
  82342. }
  82343. if (this._trackPosition) {
  82344. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82345. }
  82346. this._calculatedPosition.addInPlace(this.position);
  82347. }
  82348. var pose = this.rawPose;
  82349. if (poseData.orientation && pose.orientation) {
  82350. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82351. if (this._mesh) {
  82352. if (this._mesh.getScene().useRightHandedSystem) {
  82353. this._deviceRoomRotationQuaternion.z *= -1;
  82354. this._deviceRoomRotationQuaternion.w *= -1;
  82355. }
  82356. else {
  82357. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82358. }
  82359. }
  82360. // if the camera is set, rotate to the camera's rotation
  82361. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82362. }
  82363. }
  82364. };
  82365. /**
  82366. * Attaches a mesh to the controller
  82367. * @param mesh the mesh to be attached
  82368. */
  82369. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82370. if (this._mesh) {
  82371. this._mesh.parent = null;
  82372. }
  82373. this._mesh = mesh;
  82374. if (this._poseControlledCamera) {
  82375. this._mesh.parent = this._poseControlledCamera;
  82376. }
  82377. if (!this._mesh.rotationQuaternion) {
  82378. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82379. }
  82380. // 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
  82381. this._updatePoseAndMesh();
  82382. if (this._pointingPoseNode) {
  82383. var parents = [];
  82384. var obj = this._pointingPoseNode;
  82385. while (obj.parent) {
  82386. parents.push(obj.parent);
  82387. obj = obj.parent;
  82388. }
  82389. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82390. }
  82391. this._meshAttachedObservable.notifyObservers(mesh);
  82392. };
  82393. /**
  82394. * Attaches the controllers mesh to a camera
  82395. * @param camera the camera the mesh should be attached to
  82396. */
  82397. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82398. this._poseControlledCamera = camera;
  82399. if (this._mesh) {
  82400. this._mesh.parent = this._poseControlledCamera;
  82401. }
  82402. };
  82403. /**
  82404. * Disposes of the controller
  82405. */
  82406. PoseEnabledController.prototype.dispose = function () {
  82407. if (this._mesh) {
  82408. this._mesh.dispose();
  82409. }
  82410. this._mesh = null;
  82411. _super.prototype.dispose.call(this);
  82412. };
  82413. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82414. /**
  82415. * The mesh that is attached to the controller
  82416. */
  82417. get: function () {
  82418. return this._mesh;
  82419. },
  82420. enumerable: true,
  82421. configurable: true
  82422. });
  82423. /**
  82424. * Gets the ray of the controller in the direction the controller is pointing
  82425. * @param length the length the resulting ray should be
  82426. * @returns a ray in the direction the controller is pointing
  82427. */
  82428. PoseEnabledController.prototype.getForwardRay = function (length) {
  82429. if (length === void 0) { length = 100; }
  82430. if (!this.mesh) {
  82431. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  82432. }
  82433. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  82434. var origin = m.getTranslation();
  82435. var forward = new BABYLON.Vector3(0, 0, -1);
  82436. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82437. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82438. return new BABYLON.Ray(origin, direction, length);
  82439. };
  82440. /**
  82441. * Name of the child mesh that can be used to cast a ray from the controller
  82442. */
  82443. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  82444. return PoseEnabledController;
  82445. }(BABYLON.Gamepad));
  82446. BABYLON.PoseEnabledController = PoseEnabledController;
  82447. })(BABYLON || (BABYLON = {}));
  82448. //# sourceMappingURL=babylon.poseEnabledController.js.map
  82449. var BABYLON;
  82450. (function (BABYLON) {
  82451. /**
  82452. * Defines the WebVRController object that represents controllers tracked in 3D space
  82453. */
  82454. var WebVRController = /** @class */ (function (_super) {
  82455. __extends(WebVRController, _super);
  82456. /**
  82457. * Creates a new WebVRController from a gamepad
  82458. * @param vrGamepad the gamepad that the WebVRController should be created from
  82459. */
  82460. function WebVRController(vrGamepad) {
  82461. var _this = _super.call(this, vrGamepad) || this;
  82462. // Observables
  82463. /**
  82464. * Fired when the trigger state has changed
  82465. */
  82466. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  82467. /**
  82468. * Fired when the main button state has changed
  82469. */
  82470. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  82471. /**
  82472. * Fired when the secondary button state has changed
  82473. */
  82474. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  82475. /**
  82476. * Fired when the pad state has changed
  82477. */
  82478. _this.onPadStateChangedObservable = new BABYLON.Observable();
  82479. /**
  82480. * Fired when controllers stick values have changed
  82481. */
  82482. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  82483. /**
  82484. * X and Y axis corrisponding to the controllers joystick
  82485. */
  82486. _this.pad = { x: 0, y: 0 };
  82487. // avoid GC, store state in a tmp object
  82488. _this._changes = {
  82489. pressChanged: false,
  82490. touchChanged: false,
  82491. valueChanged: false,
  82492. changed: false
  82493. };
  82494. _this._buttons = new Array(vrGamepad.buttons.length);
  82495. _this.hand = vrGamepad.hand;
  82496. return _this;
  82497. }
  82498. /**
  82499. * Fired when a controller button's state has changed
  82500. * @param callback the callback containing the button that was modified
  82501. */
  82502. WebVRController.prototype.onButtonStateChange = function (callback) {
  82503. this._onButtonStateChange = callback;
  82504. };
  82505. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  82506. /**
  82507. * The default controller model for the controller
  82508. */
  82509. get: function () {
  82510. return this._defaultModel;
  82511. },
  82512. enumerable: true,
  82513. configurable: true
  82514. });
  82515. /**
  82516. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  82517. */
  82518. WebVRController.prototype.update = function () {
  82519. _super.prototype.update.call(this);
  82520. for (var index = 0; index < this._buttons.length; index++) {
  82521. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  82522. }
  82523. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  82524. this.pad.x = this.leftStick.x;
  82525. this.pad.y = this.leftStick.y;
  82526. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  82527. }
  82528. };
  82529. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  82530. if (!newState) {
  82531. newState = {
  82532. pressed: false,
  82533. touched: false,
  82534. value: 0
  82535. };
  82536. }
  82537. if (!currentState) {
  82538. this._buttons[buttonIndex] = {
  82539. pressed: newState.pressed,
  82540. touched: newState.touched,
  82541. value: newState.value
  82542. };
  82543. return;
  82544. }
  82545. this._checkChanges(newState, currentState);
  82546. if (this._changes.changed) {
  82547. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  82548. this._handleButtonChange(buttonIndex, newState, this._changes);
  82549. }
  82550. this._buttons[buttonIndex].pressed = newState.pressed;
  82551. this._buttons[buttonIndex].touched = newState.touched;
  82552. // oculus triggers are never 0, thou not touched.
  82553. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  82554. };
  82555. WebVRController.prototype._checkChanges = function (newState, currentState) {
  82556. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  82557. this._changes.touchChanged = newState.touched !== currentState.touched;
  82558. this._changes.valueChanged = newState.value !== currentState.value;
  82559. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  82560. return this._changes;
  82561. };
  82562. /**
  82563. * Disposes of th webVRCOntroller
  82564. */
  82565. WebVRController.prototype.dispose = function () {
  82566. _super.prototype.dispose.call(this);
  82567. this.onTriggerStateChangedObservable.clear();
  82568. this.onMainButtonStateChangedObservable.clear();
  82569. this.onSecondaryButtonStateChangedObservable.clear();
  82570. this.onPadStateChangedObservable.clear();
  82571. this.onPadValuesChangedObservable.clear();
  82572. };
  82573. return WebVRController;
  82574. }(BABYLON.PoseEnabledController));
  82575. BABYLON.WebVRController = WebVRController;
  82576. })(BABYLON || (BABYLON = {}));
  82577. //# sourceMappingURL=babylon.webVRController.js.map
  82578. var BABYLON;
  82579. (function (BABYLON) {
  82580. /**
  82581. * Oculus Touch Controller
  82582. */
  82583. var OculusTouchController = /** @class */ (function (_super) {
  82584. __extends(OculusTouchController, _super);
  82585. /**
  82586. * Creates a new OculusTouchController from a gamepad
  82587. * @param vrGamepad the gamepad that the controller should be created from
  82588. */
  82589. function OculusTouchController(vrGamepad) {
  82590. var _this = _super.call(this, vrGamepad) || this;
  82591. /**
  82592. * Fired when the secondary trigger on this controller is modified
  82593. */
  82594. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  82595. /**
  82596. * Fired when the thumb rest on this controller is modified
  82597. */
  82598. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  82599. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  82600. return _this;
  82601. }
  82602. /**
  82603. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82604. * @param scene scene in which to add meshes
  82605. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82606. */
  82607. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82608. var _this = this;
  82609. var meshName;
  82610. // Hand
  82611. if (this.hand === 'left') {
  82612. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  82613. }
  82614. else { // Right is the default if no hand is specified
  82615. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  82616. }
  82617. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  82618. /*
  82619. Parent Mesh name: oculus_touch_left
  82620. - body
  82621. - trigger
  82622. - thumbstick
  82623. - grip
  82624. - button_y
  82625. - button_x
  82626. - button_enter
  82627. */
  82628. _this._defaultModel = newMeshes[1];
  82629. _this.attachToMesh(_this._defaultModel);
  82630. if (meshLoaded) {
  82631. meshLoaded(_this._defaultModel);
  82632. }
  82633. });
  82634. };
  82635. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  82636. /**
  82637. * Fired when the A button on this controller is modified
  82638. */
  82639. get: function () {
  82640. if (this.hand === 'right') {
  82641. return this.onMainButtonStateChangedObservable;
  82642. }
  82643. else {
  82644. throw new Error('No A button on left hand');
  82645. }
  82646. },
  82647. enumerable: true,
  82648. configurable: true
  82649. });
  82650. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  82651. /**
  82652. * Fired when the B button on this controller is modified
  82653. */
  82654. get: function () {
  82655. if (this.hand === 'right') {
  82656. return this.onSecondaryButtonStateChangedObservable;
  82657. }
  82658. else {
  82659. throw new Error('No B button on left hand');
  82660. }
  82661. },
  82662. enumerable: true,
  82663. configurable: true
  82664. });
  82665. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  82666. /**
  82667. * Fired when the X button on this controller is modified
  82668. */
  82669. get: function () {
  82670. if (this.hand === 'left') {
  82671. return this.onMainButtonStateChangedObservable;
  82672. }
  82673. else {
  82674. throw new Error('No X button on right hand');
  82675. }
  82676. },
  82677. enumerable: true,
  82678. configurable: true
  82679. });
  82680. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  82681. /**
  82682. * Fired when the Y button on this controller is modified
  82683. */
  82684. get: function () {
  82685. if (this.hand === 'left') {
  82686. return this.onSecondaryButtonStateChangedObservable;
  82687. }
  82688. else {
  82689. throw new Error('No Y button on right hand');
  82690. }
  82691. },
  82692. enumerable: true,
  82693. configurable: true
  82694. });
  82695. /**
  82696. * Called once for each button that changed state since the last frame
  82697. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  82698. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  82699. * 2) secondary trigger (same)
  82700. * 3) A (right) X (left), touch, pressed = value
  82701. * 4) B / Y
  82702. * 5) thumb rest
  82703. * @param buttonIdx Which button index changed
  82704. * @param state New state of the button
  82705. * @param changes Which properties on the state changed since last frame
  82706. */
  82707. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82708. var notifyObject = state; //{ state: state, changes: changes };
  82709. var triggerDirection = this.hand === 'right' ? -1 : 1;
  82710. switch (buttonIdx) {
  82711. case 0:
  82712. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82713. return;
  82714. case 1: // index trigger
  82715. if (this._defaultModel) {
  82716. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  82717. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  82718. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  82719. }
  82720. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82721. return;
  82722. case 2: // secondary trigger
  82723. if (this._defaultModel) {
  82724. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  82725. }
  82726. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  82727. return;
  82728. case 3:
  82729. if (this._defaultModel) {
  82730. if (notifyObject.pressed) {
  82731. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  82732. }
  82733. else {
  82734. (this._defaultModel.getChildren()[1]).position.y = 0;
  82735. }
  82736. }
  82737. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82738. return;
  82739. case 4:
  82740. if (this._defaultModel) {
  82741. if (notifyObject.pressed) {
  82742. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82743. }
  82744. else {
  82745. (this._defaultModel.getChildren()[2]).position.y = 0;
  82746. }
  82747. }
  82748. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82749. return;
  82750. case 5:
  82751. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  82752. return;
  82753. }
  82754. };
  82755. /**
  82756. * Base Url for the controller model.
  82757. */
  82758. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  82759. /**
  82760. * File name for the left controller model.
  82761. */
  82762. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  82763. /**
  82764. * File name for the right controller model.
  82765. */
  82766. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  82767. return OculusTouchController;
  82768. }(BABYLON.WebVRController));
  82769. BABYLON.OculusTouchController = OculusTouchController;
  82770. })(BABYLON || (BABYLON = {}));
  82771. //# sourceMappingURL=babylon.oculusTouchController.js.map
  82772. var BABYLON;
  82773. (function (BABYLON) {
  82774. /**
  82775. * Vive Controller
  82776. */
  82777. var ViveController = /** @class */ (function (_super) {
  82778. __extends(ViveController, _super);
  82779. /**
  82780. * Creates a new ViveController from a gamepad
  82781. * @param vrGamepad the gamepad that the controller should be created from
  82782. */
  82783. function ViveController(vrGamepad) {
  82784. var _this = _super.call(this, vrGamepad) || this;
  82785. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  82786. _this._invertLeftStickY = true;
  82787. return _this;
  82788. }
  82789. /**
  82790. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82791. * @param scene scene in which to add meshes
  82792. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82793. */
  82794. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82795. var _this = this;
  82796. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  82797. /*
  82798. Parent Mesh name: ViveWand
  82799. - body
  82800. - r_gripper
  82801. - l_gripper
  82802. - menu_button
  82803. - system_button
  82804. - trackpad
  82805. - trigger
  82806. - LED
  82807. */
  82808. _this._defaultModel = newMeshes[1];
  82809. _this.attachToMesh(_this._defaultModel);
  82810. if (meshLoaded) {
  82811. meshLoaded(_this._defaultModel);
  82812. }
  82813. });
  82814. };
  82815. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  82816. /**
  82817. * Fired when the left button on this controller is modified
  82818. */
  82819. get: function () {
  82820. return this.onMainButtonStateChangedObservable;
  82821. },
  82822. enumerable: true,
  82823. configurable: true
  82824. });
  82825. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  82826. /**
  82827. * Fired when the right button on this controller is modified
  82828. */
  82829. get: function () {
  82830. return this.onMainButtonStateChangedObservable;
  82831. },
  82832. enumerable: true,
  82833. configurable: true
  82834. });
  82835. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  82836. /**
  82837. * Fired when the menu button on this controller is modified
  82838. */
  82839. get: function () {
  82840. return this.onSecondaryButtonStateChangedObservable;
  82841. },
  82842. enumerable: true,
  82843. configurable: true
  82844. });
  82845. /**
  82846. * Called once for each button that changed state since the last frame
  82847. * Vive mapping:
  82848. * 0: touchpad
  82849. * 1: trigger
  82850. * 2: left AND right buttons
  82851. * 3: menu button
  82852. * @param buttonIdx Which button index changed
  82853. * @param state New state of the button
  82854. * @param changes Which properties on the state changed since last frame
  82855. */
  82856. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82857. var notifyObject = state; //{ state: state, changes: changes };
  82858. switch (buttonIdx) {
  82859. case 0:
  82860. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82861. return;
  82862. case 1: // index trigger
  82863. if (this._defaultModel) {
  82864. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  82865. }
  82866. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82867. return;
  82868. case 2: // left AND right button
  82869. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82870. return;
  82871. case 3:
  82872. if (this._defaultModel) {
  82873. if (notifyObject.pressed) {
  82874. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82875. }
  82876. else {
  82877. (this._defaultModel.getChildren()[2]).position.y = 0;
  82878. }
  82879. }
  82880. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82881. return;
  82882. }
  82883. };
  82884. /**
  82885. * Base Url for the controller model.
  82886. */
  82887. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  82888. /**
  82889. * File name for the controller model.
  82890. */
  82891. ViveController.MODEL_FILENAME = 'wand.babylon';
  82892. return ViveController;
  82893. }(BABYLON.WebVRController));
  82894. BABYLON.ViveController = ViveController;
  82895. })(BABYLON || (BABYLON = {}));
  82896. //# sourceMappingURL=babylon.viveController.js.map
  82897. var BABYLON;
  82898. (function (BABYLON) {
  82899. /**
  82900. * Generic Controller
  82901. */
  82902. var GenericController = /** @class */ (function (_super) {
  82903. __extends(GenericController, _super);
  82904. /**
  82905. * Creates a new GenericController from a gamepad
  82906. * @param vrGamepad the gamepad that the controller should be created from
  82907. */
  82908. function GenericController(vrGamepad) {
  82909. return _super.call(this, vrGamepad) || this;
  82910. }
  82911. /**
  82912. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82913. * @param scene scene in which to add meshes
  82914. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82915. */
  82916. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82917. var _this = this;
  82918. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  82919. _this._defaultModel = newMeshes[1];
  82920. _this.attachToMesh(_this._defaultModel);
  82921. if (meshLoaded) {
  82922. meshLoaded(_this._defaultModel);
  82923. }
  82924. });
  82925. };
  82926. /**
  82927. * Called once for each button that changed state since the last frame
  82928. * @param buttonIdx Which button index changed
  82929. * @param state New state of the button
  82930. * @param changes Which properties on the state changed since last frame
  82931. */
  82932. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82933. console.log("Button id: " + buttonIdx + "state: ");
  82934. console.dir(state);
  82935. };
  82936. /**
  82937. * Base Url for the controller model.
  82938. */
  82939. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82940. /**
  82941. * File name for the controller model.
  82942. */
  82943. GenericController.MODEL_FILENAME = 'generic.babylon';
  82944. return GenericController;
  82945. }(BABYLON.WebVRController));
  82946. BABYLON.GenericController = GenericController;
  82947. })(BABYLON || (BABYLON = {}));
  82948. //# sourceMappingURL=babylon.genericController.js.map
  82949. var BABYLON;
  82950. (function (BABYLON) {
  82951. /**
  82952. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  82953. */
  82954. var LoadedMeshInfo = /** @class */ (function () {
  82955. function LoadedMeshInfo() {
  82956. /**
  82957. * Map of the button meshes contained in the controller
  82958. */
  82959. this.buttonMeshes = {};
  82960. /**
  82961. * Map of the axis meshes contained in the controller
  82962. */
  82963. this.axisMeshes = {};
  82964. }
  82965. return LoadedMeshInfo;
  82966. }());
  82967. /**
  82968. * Defines the WindowsMotionController object that the state of the windows motion controller
  82969. */
  82970. var WindowsMotionController = /** @class */ (function (_super) {
  82971. __extends(WindowsMotionController, _super);
  82972. /**
  82973. * Creates a new WindowsMotionController from a gamepad
  82974. * @param vrGamepad the gamepad that the controller should be created from
  82975. */
  82976. function WindowsMotionController(vrGamepad) {
  82977. var _this = _super.call(this, vrGamepad) || this;
  82978. _this._mapping = {
  82979. // Semantic button names
  82980. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  82981. // A mapping of the button name to glTF model node name
  82982. // that should be transformed by button value.
  82983. buttonMeshNames: {
  82984. 'trigger': 'SELECT',
  82985. 'menu': 'MENU',
  82986. 'grip': 'GRASP',
  82987. 'thumbstick': 'THUMBSTICK_PRESS',
  82988. 'trackpad': 'TOUCHPAD_PRESS'
  82989. },
  82990. // This mapping is used to translate from the Motion Controller to Babylon semantics
  82991. buttonObservableNames: {
  82992. 'trigger': 'onTriggerStateChangedObservable',
  82993. 'menu': 'onSecondaryButtonStateChangedObservable',
  82994. 'grip': 'onMainButtonStateChangedObservable',
  82995. 'thumbstick': 'onPadStateChangedObservable',
  82996. 'trackpad': 'onTrackpadChangedObservable'
  82997. },
  82998. // A mapping of the axis name to glTF model node name
  82999. // that should be transformed by axis value.
  83000. // This array mirrors the browserGamepad.axes array, such that
  83001. // the mesh corresponding to axis 0 is in this array index 0.
  83002. axisMeshNames: [
  83003. 'THUMBSTICK_X',
  83004. 'THUMBSTICK_Y',
  83005. 'TOUCHPAD_TOUCH_X',
  83006. 'TOUCHPAD_TOUCH_Y'
  83007. ],
  83008. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  83009. };
  83010. /**
  83011. * Fired when the trackpad on this controller is clicked
  83012. */
  83013. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  83014. /**
  83015. * Fired when the trackpad on this controller is modified
  83016. */
  83017. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  83018. /**
  83019. * The current x and y values of this controller's trackpad
  83020. */
  83021. _this.trackpad = { x: 0, y: 0 };
  83022. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  83023. _this._loadedMeshInfo = null;
  83024. return _this;
  83025. }
  83026. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83027. /**
  83028. * Fired when the trigger on this controller is modified
  83029. */
  83030. get: function () {
  83031. return this.onTriggerStateChangedObservable;
  83032. },
  83033. enumerable: true,
  83034. configurable: true
  83035. });
  83036. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83037. /**
  83038. * Fired when the menu button on this controller is modified
  83039. */
  83040. get: function () {
  83041. return this.onSecondaryButtonStateChangedObservable;
  83042. },
  83043. enumerable: true,
  83044. configurable: true
  83045. });
  83046. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83047. /**
  83048. * Fired when the grip button on this controller is modified
  83049. */
  83050. get: function () {
  83051. return this.onMainButtonStateChangedObservable;
  83052. },
  83053. enumerable: true,
  83054. configurable: true
  83055. });
  83056. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83057. /**
  83058. * Fired when the thumbstick button on this controller is modified
  83059. */
  83060. get: function () {
  83061. return this.onPadStateChangedObservable;
  83062. },
  83063. enumerable: true,
  83064. configurable: true
  83065. });
  83066. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83067. /**
  83068. * Fired when the touchpad button on this controller is modified
  83069. */
  83070. get: function () {
  83071. return this.onTrackpadChangedObservable;
  83072. },
  83073. enumerable: true,
  83074. configurable: true
  83075. });
  83076. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83077. /**
  83078. * Fired when the touchpad values on this controller are modified
  83079. */
  83080. get: function () {
  83081. return this.onTrackpadValuesChangedObservable;
  83082. },
  83083. enumerable: true,
  83084. configurable: true
  83085. });
  83086. WindowsMotionController.prototype._updateTrackpad = function () {
  83087. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83088. this.trackpad.x = this.browserGamepad["axes"][2];
  83089. this.trackpad.y = this.browserGamepad["axes"][3];
  83090. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83091. }
  83092. };
  83093. /**
  83094. * Called once per frame by the engine.
  83095. */
  83096. WindowsMotionController.prototype.update = function () {
  83097. _super.prototype.update.call(this);
  83098. if (this.browserGamepad.axes) {
  83099. this._updateTrackpad();
  83100. // Only need to animate axes if there is a loaded mesh
  83101. if (this._loadedMeshInfo) {
  83102. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83103. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83104. }
  83105. }
  83106. }
  83107. };
  83108. /**
  83109. * Called once for each button that changed state since the last frame
  83110. * @param buttonIdx Which button index changed
  83111. * @param state New state of the button
  83112. * @param changes Which properties on the state changed since last frame
  83113. */
  83114. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83115. var buttonName = this._mapping.buttons[buttonIdx];
  83116. if (!buttonName) {
  83117. return;
  83118. }
  83119. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83120. this._updateTrackpad();
  83121. // Only emit events for buttons that we know how to map from index to name
  83122. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83123. if (observable) {
  83124. observable.notifyObservers(state);
  83125. }
  83126. this._lerpButtonTransform(buttonName, state.value);
  83127. };
  83128. /**
  83129. * Moves the buttons on the controller mesh based on their current state
  83130. * @param buttonName the name of the button to move
  83131. * @param buttonValue the value of the button which determines the buttons new position
  83132. */
  83133. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83134. // If there is no loaded mesh, there is nothing to transform.
  83135. if (!this._loadedMeshInfo) {
  83136. return;
  83137. }
  83138. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83139. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83140. return;
  83141. }
  83142. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83143. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83144. };
  83145. /**
  83146. * Moves the axis on the controller mesh based on its current state
  83147. * @param axis the index of the axis
  83148. * @param axisValue the value of the axis which determines the meshes new position
  83149. * @hidden
  83150. */
  83151. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83152. if (!this._loadedMeshInfo) {
  83153. return;
  83154. }
  83155. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83156. if (!meshInfo) {
  83157. return;
  83158. }
  83159. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83160. return;
  83161. }
  83162. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83163. var lerpValue = axisValue * 0.5 + 0.5;
  83164. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83165. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83166. };
  83167. /**
  83168. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83169. * @param scene scene in which to add meshes
  83170. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83171. */
  83172. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83173. var _this = this;
  83174. if (forceDefault === void 0) { forceDefault = false; }
  83175. var path;
  83176. var filename;
  83177. // Checking if GLB loader is present
  83178. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83179. // Determine the device specific folder based on the ID suffix
  83180. var device = 'default';
  83181. if (this.id && !forceDefault) {
  83182. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83183. device = ((match && match[0]) || device);
  83184. }
  83185. // Hand
  83186. if (this.hand === 'left') {
  83187. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83188. }
  83189. else { // Right is the default if no hand is specified
  83190. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83191. }
  83192. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83193. }
  83194. else {
  83195. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83196. path = BABYLON.GenericController.MODEL_BASE_URL;
  83197. filename = BABYLON.GenericController.MODEL_FILENAME;
  83198. }
  83199. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83200. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83201. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83202. if (!_this._loadedMeshInfo) {
  83203. return;
  83204. }
  83205. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83206. _this.attachToMesh(_this._defaultModel);
  83207. if (meshLoaded) {
  83208. meshLoaded(_this._defaultModel);
  83209. }
  83210. }, null, function (scene, message) {
  83211. BABYLON.Tools.Log(message);
  83212. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83213. if (!forceDefault) {
  83214. _this.initControllerMesh(scene, meshLoaded, true);
  83215. }
  83216. });
  83217. };
  83218. /**
  83219. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83220. * can be transformed by button presses and axes values, based on this._mapping.
  83221. *
  83222. * @param scene scene in which the meshes exist
  83223. * @param meshes list of meshes that make up the controller model to process
  83224. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83225. */
  83226. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83227. var loadedMeshInfo = null;
  83228. // Create a new mesh to contain the glTF hierarchy
  83229. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83230. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83231. var childMesh = null;
  83232. for (var i = 0; i < meshes.length; i++) {
  83233. var mesh = meshes[i];
  83234. if (!mesh.parent) {
  83235. // Exclude controller meshes from picking results
  83236. mesh.isPickable = false;
  83237. // Handle root node, attach to the new parentMesh
  83238. childMesh = mesh;
  83239. break;
  83240. }
  83241. }
  83242. if (childMesh) {
  83243. childMesh.setParent(parentMesh);
  83244. // Create our mesh info. Note that this method will always return non-null.
  83245. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83246. }
  83247. else {
  83248. BABYLON.Tools.Warn('Could not find root node in model file.');
  83249. }
  83250. return loadedMeshInfo;
  83251. };
  83252. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83253. var loadedMeshInfo = new LoadedMeshInfo();
  83254. var i;
  83255. loadedMeshInfo.rootNode = rootNode;
  83256. // Reset the caches
  83257. loadedMeshInfo.buttonMeshes = {};
  83258. loadedMeshInfo.axisMeshes = {};
  83259. // Button Meshes
  83260. for (i = 0; i < this._mapping.buttons.length; i++) {
  83261. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83262. if (!buttonMeshName) {
  83263. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83264. continue;
  83265. }
  83266. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83267. if (!buttonMesh) {
  83268. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83269. continue;
  83270. }
  83271. var buttonMeshInfo = {
  83272. index: i,
  83273. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83274. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83275. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83276. };
  83277. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83278. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83279. }
  83280. else {
  83281. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83282. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83283. '(VALUE: ' + !!buttonMeshInfo.value +
  83284. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83285. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83286. ')');
  83287. }
  83288. }
  83289. // Axis Meshes
  83290. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83291. var axisMeshName = this._mapping.axisMeshNames[i];
  83292. if (!axisMeshName) {
  83293. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83294. continue;
  83295. }
  83296. var axisMesh = getChildByName(rootNode, axisMeshName);
  83297. if (!axisMesh) {
  83298. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83299. continue;
  83300. }
  83301. var axisMeshInfo = {
  83302. index: i,
  83303. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83304. min: getImmediateChildByName(axisMesh, 'MIN'),
  83305. max: getImmediateChildByName(axisMesh, 'MAX')
  83306. };
  83307. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83308. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83309. }
  83310. else {
  83311. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83312. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83313. '(VALUE: ' + !!axisMeshInfo.value +
  83314. ', MIN: ' + !!axisMeshInfo.min +
  83315. ', MAX:' + !!axisMeshInfo.max +
  83316. ')');
  83317. }
  83318. }
  83319. // Pointing Ray
  83320. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83321. if (!loadedMeshInfo.pointingPoseNode) {
  83322. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83323. }
  83324. else {
  83325. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83326. }
  83327. return loadedMeshInfo;
  83328. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83329. function getChildByName(node, name) {
  83330. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  83331. }
  83332. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83333. function getImmediateChildByName(node, name) {
  83334. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  83335. }
  83336. };
  83337. /**
  83338. * Gets the ray of the controller in the direction the controller is pointing
  83339. * @param length the length the resulting ray should be
  83340. * @returns a ray in the direction the controller is pointing
  83341. */
  83342. WindowsMotionController.prototype.getForwardRay = function (length) {
  83343. if (length === void 0) { length = 100; }
  83344. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83345. return _super.prototype.getForwardRay.call(this, length);
  83346. }
  83347. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83348. var origin = m.getTranslation();
  83349. var forward = new BABYLON.Vector3(0, 0, -1);
  83350. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83351. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83352. return new BABYLON.Ray(origin, direction, length);
  83353. };
  83354. /**
  83355. * Disposes of the controller
  83356. */
  83357. WindowsMotionController.prototype.dispose = function () {
  83358. _super.prototype.dispose.call(this);
  83359. this.onTrackpadChangedObservable.clear();
  83360. };
  83361. /**
  83362. * The base url used to load the left and right controller models
  83363. */
  83364. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83365. /**
  83366. * The name of the left controller model file
  83367. */
  83368. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83369. /**
  83370. * The name of the right controller model file
  83371. */
  83372. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83373. /**
  83374. * The controller name prefix for this controller type
  83375. */
  83376. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83377. /**
  83378. * The controller id pattern for this controller type
  83379. */
  83380. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83381. return WindowsMotionController;
  83382. }(BABYLON.WebVRController));
  83383. BABYLON.WindowsMotionController = WindowsMotionController;
  83384. })(BABYLON || (BABYLON = {}));
  83385. //# sourceMappingURL=babylon.windowsMotionController.js.map
  83386. var BABYLON;
  83387. (function (BABYLON) {
  83388. /**
  83389. * Gear VR Controller
  83390. */
  83391. var GearVRController = /** @class */ (function (_super) {
  83392. __extends(GearVRController, _super);
  83393. /**
  83394. * Creates a new GearVRController from a gamepad
  83395. * @param vrGamepad the gamepad that the controller should be created from
  83396. */
  83397. function GearVRController(vrGamepad) {
  83398. var _this = _super.call(this, vrGamepad) || this;
  83399. _this._buttonIndexToObservableNameMap = [
  83400. 'onTrackpadChangedObservable',
  83401. 'onTriggerStateChangedObservable' // Trigger
  83402. ];
  83403. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83404. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83405. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83406. _this._disableTrackPosition(_this._calculatedPosition);
  83407. return _this;
  83408. }
  83409. /**
  83410. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83411. * @param scene scene in which to add meshes
  83412. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83413. */
  83414. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83415. var _this = this;
  83416. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83417. // Offset the controller so it will rotate around the users wrist
  83418. var mesh = new BABYLON.Mesh("", scene);
  83419. newMeshes[1].parent = mesh;
  83420. newMeshes[1].position.z = -0.15;
  83421. _this._defaultModel = mesh;
  83422. _this.attachToMesh(_this._defaultModel);
  83423. if (meshLoaded) {
  83424. meshLoaded(_this._defaultModel);
  83425. }
  83426. });
  83427. };
  83428. /**
  83429. * Called once for each button that changed state since the last frame
  83430. * @param buttonIdx Which button index changed
  83431. * @param state New state of the button
  83432. * @param changes Which properties on the state changed since last frame
  83433. */
  83434. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83435. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  83436. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  83437. // Only emit events for buttons that we know how to map from index to observable
  83438. var observable = this[observableName];
  83439. if (observable) {
  83440. observable.notifyObservers(state);
  83441. }
  83442. }
  83443. };
  83444. /**
  83445. * Base Url for the controller model.
  83446. */
  83447. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83448. /**
  83449. * File name for the controller model.
  83450. */
  83451. GearVRController.MODEL_FILENAME = 'generic.babylon';
  83452. /**
  83453. * Gamepad Id prefix used to identify this controller.
  83454. */
  83455. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  83456. return GearVRController;
  83457. }(BABYLON.WebVRController));
  83458. BABYLON.GearVRController = GearVRController;
  83459. })(BABYLON || (BABYLON = {}));
  83460. //# sourceMappingURL=babylon.gearVRController.js.map
  83461. var BABYLON;
  83462. (function (BABYLON) {
  83463. /**
  83464. * Google Daydream controller
  83465. */
  83466. var DaydreamController = /** @class */ (function (_super) {
  83467. __extends(DaydreamController, _super);
  83468. /**
  83469. * Creates a new DaydreamController from a gamepad
  83470. * @param vrGamepad the gamepad that the controller should be created from
  83471. */
  83472. function DaydreamController(vrGamepad) {
  83473. var _this = _super.call(this, vrGamepad) || this;
  83474. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  83475. return _this;
  83476. }
  83477. /**
  83478. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83479. * @param scene scene in which to add meshes
  83480. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83481. */
  83482. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83483. var _this = this;
  83484. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  83485. _this._defaultModel = newMeshes[1];
  83486. _this.attachToMesh(_this._defaultModel);
  83487. if (meshLoaded) {
  83488. meshLoaded(_this._defaultModel);
  83489. }
  83490. });
  83491. };
  83492. /**
  83493. * Called once for each button that changed state since the last frame
  83494. * @param buttonIdx Which button index changed
  83495. * @param state New state of the button
  83496. * @param changes Which properties on the state changed since last frame
  83497. */
  83498. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83499. // Daydream controller only has 1 GamepadButton (on the trackpad).
  83500. if (buttonIdx === 0) {
  83501. var observable = this.onTriggerStateChangedObservable;
  83502. if (observable) {
  83503. observable.notifyObservers(state);
  83504. }
  83505. }
  83506. else {
  83507. // If the app or home buttons are ever made available
  83508. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  83509. }
  83510. };
  83511. /**
  83512. * Base Url for the controller model.
  83513. */
  83514. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83515. /**
  83516. * File name for the controller model.
  83517. */
  83518. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  83519. /**
  83520. * Gamepad Id prefix used to identify Daydream Controller.
  83521. */
  83522. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  83523. return DaydreamController;
  83524. }(BABYLON.WebVRController));
  83525. BABYLON.DaydreamController = DaydreamController;
  83526. })(BABYLON || (BABYLON = {}));
  83527. //# sourceMappingURL=babylon.daydreamController.js.map
  83528. var BABYLON;
  83529. (function (BABYLON) {
  83530. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  83531. get: function () {
  83532. if (!this._gamepadManager) {
  83533. this._gamepadManager = new BABYLON.GamepadManager(this);
  83534. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  83535. if (!component) {
  83536. component = new GamepadSystemSceneComponent(this);
  83537. this._addComponent(component);
  83538. }
  83539. }
  83540. return this._gamepadManager;
  83541. },
  83542. enumerable: true,
  83543. configurable: true
  83544. });
  83545. /**
  83546. * Adds a gamepad to the free camera inputs manager
  83547. */
  83548. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  83549. this.add(new BABYLON.FreeCameraGamepadInput());
  83550. return this;
  83551. };
  83552. /**
  83553. * Adds a gamepad to the arc rotate camera inputs manager
  83554. */
  83555. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  83556. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  83557. return this;
  83558. };
  83559. /**
  83560. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  83561. */
  83562. var GamepadSystemSceneComponent = /** @class */ (function () {
  83563. /**
  83564. * Creates a new instance of the component for the given scene
  83565. * @param scene Defines the scene to register the component in
  83566. */
  83567. function GamepadSystemSceneComponent(scene) {
  83568. /**
  83569. * The component name helpfull to identify the component in the list of scene components.
  83570. */
  83571. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  83572. this.scene = scene;
  83573. }
  83574. /**
  83575. * Registers the component in a given scene
  83576. */
  83577. GamepadSystemSceneComponent.prototype.register = function () {
  83578. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  83579. };
  83580. /**
  83581. * Rebuilds the elements related to this component in case of
  83582. * context lost for instance.
  83583. */
  83584. GamepadSystemSceneComponent.prototype.rebuild = function () {
  83585. // Nothing to do for gamepads
  83586. };
  83587. /**
  83588. * Disposes the component and the associated ressources
  83589. */
  83590. GamepadSystemSceneComponent.prototype.dispose = function () {
  83591. var gamepadManager = this.scene._gamepadManager;
  83592. if (gamepadManager) {
  83593. gamepadManager.dispose();
  83594. this.scene._gamepadManager = null;
  83595. }
  83596. };
  83597. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  83598. var gamepadManager = this.scene._gamepadManager;
  83599. if (gamepadManager && gamepadManager._isMonitoring) {
  83600. gamepadManager._checkGamepadsStatus();
  83601. }
  83602. };
  83603. return GamepadSystemSceneComponent;
  83604. }());
  83605. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  83606. })(BABYLON || (BABYLON = {}));
  83607. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  83608. var BABYLON;
  83609. (function (BABYLON) {
  83610. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  83611. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  83612. });
  83613. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  83614. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  83615. });
  83616. /**
  83617. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  83618. * an arc rotate version arcFollowCamera are available.
  83619. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83620. */
  83621. var FollowCamera = /** @class */ (function (_super) {
  83622. __extends(FollowCamera, _super);
  83623. /**
  83624. * Instantiates the follow camera.
  83625. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83626. * @param name Define the name of the camera in the scene
  83627. * @param position Define the position of the camera
  83628. * @param scene Define the scene the camera belong to
  83629. * @param lockedTarget Define the target of the camera
  83630. */
  83631. function FollowCamera(name, position, scene, lockedTarget) {
  83632. if (lockedTarget === void 0) { lockedTarget = null; }
  83633. var _this = _super.call(this, name, position, scene) || this;
  83634. /**
  83635. * Distance the follow camera should follow an object at
  83636. */
  83637. _this.radius = 12;
  83638. /**
  83639. * Define a rotation offset between the camera and the object it follows
  83640. */
  83641. _this.rotationOffset = 0;
  83642. /**
  83643. * Define a height offset between the camera and the object it follows.
  83644. * It can help following an object from the top (like a car chaing a plane)
  83645. */
  83646. _this.heightOffset = 4;
  83647. /**
  83648. * Define how fast the camera can accelerate to follow it s target.
  83649. */
  83650. _this.cameraAcceleration = 0.05;
  83651. /**
  83652. * Define the speed limit of the camera following an object.
  83653. */
  83654. _this.maxCameraSpeed = 20;
  83655. _this.lockedTarget = lockedTarget;
  83656. return _this;
  83657. }
  83658. FollowCamera.prototype._follow = function (cameraTarget) {
  83659. if (!cameraTarget) {
  83660. return;
  83661. }
  83662. var yRotation;
  83663. if (cameraTarget.rotationQuaternion) {
  83664. var rotMatrix = new BABYLON.Matrix();
  83665. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  83666. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  83667. }
  83668. else {
  83669. yRotation = cameraTarget.rotation.y;
  83670. }
  83671. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  83672. var targetPosition = cameraTarget.getAbsolutePosition();
  83673. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  83674. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  83675. var dx = targetX - this.position.x;
  83676. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  83677. var dz = (targetZ) - this.position.z;
  83678. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  83679. var vy = dy * this.cameraAcceleration;
  83680. var vz = dz * this.cameraAcceleration * 2;
  83681. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  83682. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83683. }
  83684. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  83685. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83686. }
  83687. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  83688. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83689. }
  83690. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  83691. this.setTarget(targetPosition);
  83692. };
  83693. /** @hidden */
  83694. FollowCamera.prototype._checkInputs = function () {
  83695. _super.prototype._checkInputs.call(this);
  83696. if (this.lockedTarget) {
  83697. this._follow(this.lockedTarget);
  83698. }
  83699. };
  83700. /**
  83701. * Gets the camera class name.
  83702. * @returns the class name
  83703. */
  83704. FollowCamera.prototype.getClassName = function () {
  83705. return "FollowCamera";
  83706. };
  83707. __decorate([
  83708. BABYLON.serialize()
  83709. ], FollowCamera.prototype, "radius", void 0);
  83710. __decorate([
  83711. BABYLON.serialize()
  83712. ], FollowCamera.prototype, "rotationOffset", void 0);
  83713. __decorate([
  83714. BABYLON.serialize()
  83715. ], FollowCamera.prototype, "heightOffset", void 0);
  83716. __decorate([
  83717. BABYLON.serialize()
  83718. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  83719. __decorate([
  83720. BABYLON.serialize()
  83721. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  83722. __decorate([
  83723. BABYLON.serializeAsMeshReference("lockedTargetId")
  83724. ], FollowCamera.prototype, "lockedTarget", void 0);
  83725. return FollowCamera;
  83726. }(BABYLON.TargetCamera));
  83727. BABYLON.FollowCamera = FollowCamera;
  83728. /**
  83729. * Arc Rotate version of the follow camera.
  83730. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  83731. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83732. */
  83733. var ArcFollowCamera = /** @class */ (function (_super) {
  83734. __extends(ArcFollowCamera, _super);
  83735. /**
  83736. * Instantiates a new ArcFollowCamera
  83737. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83738. * @param name Define the name of the camera
  83739. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  83740. * @param beta Define the rotation angle of the camera around the elevation axis
  83741. * @param radius Define the radius of the camera from its target point
  83742. * @param target Define the target of the camera
  83743. * @param scene Define the scene the camera belongs to
  83744. */
  83745. function ArcFollowCamera(name,
  83746. /** The longitudinal angle of the camera */
  83747. alpha,
  83748. /** The latitudinal angle of the camera */
  83749. beta,
  83750. /** The radius of the camera from its target */
  83751. radius,
  83752. /** Define the camera target (the messh it should follow) */
  83753. target, scene) {
  83754. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  83755. _this.alpha = alpha;
  83756. _this.beta = beta;
  83757. _this.radius = radius;
  83758. _this.target = target;
  83759. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  83760. _this._follow();
  83761. return _this;
  83762. }
  83763. ArcFollowCamera.prototype._follow = function () {
  83764. if (!this.target) {
  83765. return;
  83766. }
  83767. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  83768. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  83769. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  83770. var targetPosition = this.target.getAbsolutePosition();
  83771. this.position = targetPosition.add(this._cartesianCoordinates);
  83772. this.setTarget(targetPosition);
  83773. };
  83774. /** @hidden */
  83775. ArcFollowCamera.prototype._checkInputs = function () {
  83776. _super.prototype._checkInputs.call(this);
  83777. this._follow();
  83778. };
  83779. /**
  83780. * Returns the class name of the object.
  83781. * It is mostly used internally for serialization purposes.
  83782. */
  83783. ArcFollowCamera.prototype.getClassName = function () {
  83784. return "ArcFollowCamera";
  83785. };
  83786. return ArcFollowCamera;
  83787. }(BABYLON.TargetCamera));
  83788. BABYLON.ArcFollowCamera = ArcFollowCamera;
  83789. })(BABYLON || (BABYLON = {}));
  83790. //# sourceMappingURL=babylon.followCamera.js.map
  83791. var BABYLON;
  83792. (function (BABYLON) {
  83793. /**
  83794. * 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,
  83795. * which still works and will still be found in many Playgrounds.
  83796. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83797. */
  83798. var UniversalCamera = /** @class */ (function (_super) {
  83799. __extends(UniversalCamera, _super);
  83800. /**
  83801. * 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,
  83802. * which still works and will still be found in many Playgrounds.
  83803. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83804. * @param name Define the name of the camera in the scene
  83805. * @param position Define the start position of the camera in the scene
  83806. * @param scene Define the scene the camera belongs to
  83807. */
  83808. function UniversalCamera(name, position, scene) {
  83809. var _this = _super.call(this, name, position, scene) || this;
  83810. _this.inputs.addGamepad();
  83811. return _this;
  83812. }
  83813. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  83814. /**
  83815. * Defines the gamepad rotation sensiblity.
  83816. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  83817. */
  83818. get: function () {
  83819. var gamepad = this.inputs.attached["gamepad"];
  83820. if (gamepad) {
  83821. return gamepad.gamepadAngularSensibility;
  83822. }
  83823. return 0;
  83824. },
  83825. set: function (value) {
  83826. var gamepad = this.inputs.attached["gamepad"];
  83827. if (gamepad) {
  83828. gamepad.gamepadAngularSensibility = value;
  83829. }
  83830. },
  83831. enumerable: true,
  83832. configurable: true
  83833. });
  83834. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  83835. /**
  83836. * Defines the gamepad move sensiblity.
  83837. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  83838. */
  83839. get: function () {
  83840. var gamepad = this.inputs.attached["gamepad"];
  83841. if (gamepad) {
  83842. return gamepad.gamepadMoveSensibility;
  83843. }
  83844. return 0;
  83845. },
  83846. set: function (value) {
  83847. var gamepad = this.inputs.attached["gamepad"];
  83848. if (gamepad) {
  83849. gamepad.gamepadMoveSensibility = value;
  83850. }
  83851. },
  83852. enumerable: true,
  83853. configurable: true
  83854. });
  83855. /**
  83856. * Gets the current object class name.
  83857. * @return the class name
  83858. */
  83859. UniversalCamera.prototype.getClassName = function () {
  83860. return "UniversalCamera";
  83861. };
  83862. return UniversalCamera;
  83863. }(BABYLON.TouchCamera));
  83864. BABYLON.UniversalCamera = UniversalCamera;
  83865. })(BABYLON || (BABYLON = {}));
  83866. //# sourceMappingURL=babylon.universalCamera.js.map
  83867. var BABYLON;
  83868. (function (BABYLON) {
  83869. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  83870. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  83871. });
  83872. /**
  83873. * This represents a FPS type of camera. This is only here for back compat purpose.
  83874. * Please use the UniversalCamera instead as both are identical.
  83875. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83876. */
  83877. var GamepadCamera = /** @class */ (function (_super) {
  83878. __extends(GamepadCamera, _super);
  83879. /**
  83880. * Instantiates a new Gamepad Camera
  83881. * This represents a FPS type of camera. This is only here for back compat purpose.
  83882. * Please use the UniversalCamera instead as both are identical.
  83883. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83884. * @param name Define the name of the camera in the scene
  83885. * @param position Define the start position of the camera in the scene
  83886. * @param scene Define the scene the camera belongs to
  83887. */
  83888. function GamepadCamera(name, position, scene) {
  83889. return _super.call(this, name, position, scene) || this;
  83890. }
  83891. /**
  83892. * Gets the current object class name.
  83893. * @return the class name
  83894. */
  83895. GamepadCamera.prototype.getClassName = function () {
  83896. return "GamepadCamera";
  83897. };
  83898. return GamepadCamera;
  83899. }(BABYLON.UniversalCamera));
  83900. BABYLON.GamepadCamera = GamepadCamera;
  83901. })(BABYLON || (BABYLON = {}));
  83902. //# sourceMappingURL=babylon.gamepadCamera.js.map
  83903. var BABYLON;
  83904. (function (BABYLON) {
  83905. /**
  83906. * PostProcessRenderPipelineManager class
  83907. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83908. */
  83909. var PostProcessRenderPipelineManager = /** @class */ (function () {
  83910. /**
  83911. * Initializes a PostProcessRenderPipelineManager
  83912. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83913. */
  83914. function PostProcessRenderPipelineManager() {
  83915. this._renderPipelines = {};
  83916. }
  83917. /**
  83918. * Adds a pipeline to the manager
  83919. * @param renderPipeline The pipeline to add
  83920. */
  83921. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  83922. this._renderPipelines[renderPipeline._name] = renderPipeline;
  83923. };
  83924. /**
  83925. * Attaches a camera to the pipeline
  83926. * @param renderPipelineName The name of the pipeline to attach to
  83927. * @param cameras the camera to attach
  83928. * @param unique if the camera can be attached multiple times to the pipeline
  83929. */
  83930. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  83931. if (unique === void 0) { unique = false; }
  83932. var renderPipeline = this._renderPipelines[renderPipelineName];
  83933. if (!renderPipeline) {
  83934. return;
  83935. }
  83936. renderPipeline._attachCameras(cameras, unique);
  83937. };
  83938. /**
  83939. * Detaches a camera from the pipeline
  83940. * @param renderPipelineName The name of the pipeline to detach from
  83941. * @param cameras the camera to detach
  83942. */
  83943. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  83944. var renderPipeline = this._renderPipelines[renderPipelineName];
  83945. if (!renderPipeline) {
  83946. return;
  83947. }
  83948. renderPipeline._detachCameras(cameras);
  83949. };
  83950. /**
  83951. * Enables an effect by name on a pipeline
  83952. * @param renderPipelineName the name of the pipeline to enable the effect in
  83953. * @param renderEffectName the name of the effect to enable
  83954. * @param cameras the cameras that the effect should be enabled on
  83955. */
  83956. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83957. var renderPipeline = this._renderPipelines[renderPipelineName];
  83958. if (!renderPipeline) {
  83959. return;
  83960. }
  83961. renderPipeline._enableEffect(renderEffectName, cameras);
  83962. };
  83963. /**
  83964. * Disables an effect by name on a pipeline
  83965. * @param renderPipelineName the name of the pipeline to disable the effect in
  83966. * @param renderEffectName the name of the effect to disable
  83967. * @param cameras the cameras that the effect should be disabled on
  83968. */
  83969. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83970. var renderPipeline = this._renderPipelines[renderPipelineName];
  83971. if (!renderPipeline) {
  83972. return;
  83973. }
  83974. renderPipeline._disableEffect(renderEffectName, cameras);
  83975. };
  83976. /**
  83977. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  83978. */
  83979. PostProcessRenderPipelineManager.prototype.update = function () {
  83980. for (var renderPipelineName in this._renderPipelines) {
  83981. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  83982. var pipeline = this._renderPipelines[renderPipelineName];
  83983. if (!pipeline.isSupported) {
  83984. pipeline.dispose();
  83985. delete this._renderPipelines[renderPipelineName];
  83986. }
  83987. else {
  83988. pipeline._update();
  83989. }
  83990. }
  83991. }
  83992. };
  83993. /** @hidden */
  83994. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  83995. for (var renderPipelineName in this._renderPipelines) {
  83996. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  83997. var pipeline = this._renderPipelines[renderPipelineName];
  83998. pipeline._rebuild();
  83999. }
  84000. }
  84001. };
  84002. /**
  84003. * Disposes of the manager and pipelines
  84004. */
  84005. PostProcessRenderPipelineManager.prototype.dispose = function () {
  84006. for (var renderPipelineName in this._renderPipelines) {
  84007. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84008. var pipeline = this._renderPipelines[renderPipelineName];
  84009. pipeline.dispose();
  84010. }
  84011. }
  84012. };
  84013. return PostProcessRenderPipelineManager;
  84014. }());
  84015. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  84016. })(BABYLON || (BABYLON = {}));
  84017. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  84018. var BABYLON;
  84019. (function (BABYLON) {
  84020. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  84021. get: function () {
  84022. if (!this._postProcessRenderPipelineManager) {
  84023. // Register the G Buffer component to the scene.
  84024. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84025. if (!component) {
  84026. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84027. this._addComponent(component);
  84028. }
  84029. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84030. }
  84031. return this._postProcessRenderPipelineManager;
  84032. },
  84033. enumerable: true,
  84034. configurable: true
  84035. });
  84036. /**
  84037. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84038. */
  84039. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84040. /**
  84041. * Creates a new instance of the component for the given scene
  84042. * @param scene Defines the scene to register the component in
  84043. */
  84044. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84045. /**
  84046. * The component name helpfull to identify the component in the list of scene components.
  84047. */
  84048. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84049. this.scene = scene;
  84050. }
  84051. /**
  84052. * Registers the component in a given scene
  84053. */
  84054. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84055. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84056. };
  84057. /**
  84058. * Rebuilds the elements related to this component in case of
  84059. * context lost for instance.
  84060. */
  84061. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84062. if (this.scene._postProcessRenderPipelineManager) {
  84063. this.scene._postProcessRenderPipelineManager._rebuild();
  84064. }
  84065. };
  84066. /**
  84067. * Disposes the component and the associated ressources
  84068. */
  84069. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84070. if (this.scene._postProcessRenderPipelineManager) {
  84071. this.scene._postProcessRenderPipelineManager.dispose();
  84072. }
  84073. };
  84074. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84075. if (this.scene._postProcessRenderPipelineManager) {
  84076. this.scene._postProcessRenderPipelineManager.update();
  84077. }
  84078. };
  84079. return PostProcessRenderPipelineManagerSceneComponent;
  84080. }());
  84081. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84082. })(BABYLON || (BABYLON = {}));
  84083. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  84084. var BABYLON;
  84085. (function (BABYLON) {
  84086. /**
  84087. * This represents a set of one or more post processes in Babylon.
  84088. * A post process can be used to apply a shader to a texture after it is rendered.
  84089. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84090. */
  84091. var PostProcessRenderEffect = /** @class */ (function () {
  84092. /**
  84093. * Instantiates a post process render effect.
  84094. * A post process can be used to apply a shader to a texture after it is rendered.
  84095. * @param engine The engine the effect is tied to
  84096. * @param name The name of the effect
  84097. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84098. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84099. */
  84100. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84101. this._name = name;
  84102. this._singleInstance = singleInstance || true;
  84103. this._getPostProcesses = getPostProcesses;
  84104. this._cameras = {};
  84105. this._indicesForCamera = {};
  84106. this._postProcesses = {};
  84107. }
  84108. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84109. /**
  84110. * Checks if all the post processes in the effect are supported.
  84111. */
  84112. get: function () {
  84113. for (var index in this._postProcesses) {
  84114. if (this._postProcesses.hasOwnProperty(index)) {
  84115. var pps = this._postProcesses[index];
  84116. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84117. if (!pps[ppIndex].isSupported) {
  84118. return false;
  84119. }
  84120. }
  84121. }
  84122. }
  84123. return true;
  84124. },
  84125. enumerable: true,
  84126. configurable: true
  84127. });
  84128. /**
  84129. * Updates the current state of the effect
  84130. * @hidden
  84131. */
  84132. PostProcessRenderEffect.prototype._update = function () {
  84133. };
  84134. /**
  84135. * Attaches the effect on cameras
  84136. * @param cameras The camera to attach to.
  84137. * @hidden
  84138. */
  84139. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84140. var _this = this;
  84141. var cameraKey;
  84142. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84143. if (!cams) {
  84144. return;
  84145. }
  84146. for (var i = 0; i < cams.length; i++) {
  84147. var camera = cams[i];
  84148. var cameraName = camera.name;
  84149. if (this._singleInstance) {
  84150. cameraKey = 0;
  84151. }
  84152. else {
  84153. cameraKey = cameraName;
  84154. }
  84155. if (!this._postProcesses[cameraKey]) {
  84156. var postProcess = this._getPostProcesses();
  84157. if (postProcess) {
  84158. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84159. }
  84160. }
  84161. if (!this._indicesForCamera[cameraName]) {
  84162. this._indicesForCamera[cameraName] = [];
  84163. }
  84164. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84165. var index = camera.attachPostProcess(postProcess);
  84166. _this._indicesForCamera[cameraName].push(index);
  84167. });
  84168. if (!this._cameras[cameraName]) {
  84169. this._cameras[cameraName] = camera;
  84170. }
  84171. }
  84172. };
  84173. /**
  84174. * Detatches the effect on cameras
  84175. * @param cameras The camera to detatch from.
  84176. * @hidden
  84177. */
  84178. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84179. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84180. if (!cams) {
  84181. return;
  84182. }
  84183. for (var i = 0; i < cams.length; i++) {
  84184. var camera = cams[i];
  84185. var cameraName = camera.name;
  84186. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84187. camera.detachPostProcess(postProcess);
  84188. });
  84189. if (this._cameras[cameraName]) {
  84190. //this._indicesForCamera.splice(index, 1);
  84191. this._cameras[cameraName] = null;
  84192. }
  84193. }
  84194. };
  84195. /**
  84196. * Enables the effect on given cameras
  84197. * @param cameras The camera to enable.
  84198. * @hidden
  84199. */
  84200. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84201. var _this = this;
  84202. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84203. if (!cams) {
  84204. return;
  84205. }
  84206. for (var i = 0; i < cams.length; i++) {
  84207. var camera = cams[i];
  84208. var cameraName = camera.name;
  84209. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84210. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84211. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84212. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84213. });
  84214. }
  84215. }
  84216. }
  84217. };
  84218. /**
  84219. * Disables the effect on the given cameras
  84220. * @param cameras The camera to disable.
  84221. * @hidden
  84222. */
  84223. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84224. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84225. if (!cams) {
  84226. return;
  84227. }
  84228. for (var i = 0; i < cams.length; i++) {
  84229. var camera = cams[i];
  84230. var cameraName = camera.name;
  84231. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84232. camera.detachPostProcess(postProcess);
  84233. });
  84234. }
  84235. };
  84236. /**
  84237. * Gets a list of the post processes contained in the effect.
  84238. * @param camera The camera to get the post processes on.
  84239. * @returns The list of the post processes in the effect.
  84240. */
  84241. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84242. if (this._singleInstance) {
  84243. return this._postProcesses[0];
  84244. }
  84245. else {
  84246. if (!camera) {
  84247. return null;
  84248. }
  84249. return this._postProcesses[camera.name];
  84250. }
  84251. };
  84252. return PostProcessRenderEffect;
  84253. }());
  84254. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84255. })(BABYLON || (BABYLON = {}));
  84256. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  84257. var BABYLON;
  84258. (function (BABYLON) {
  84259. /**
  84260. * PostProcessRenderPipeline
  84261. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84262. */
  84263. var PostProcessRenderPipeline = /** @class */ (function () {
  84264. /**
  84265. * Initializes a PostProcessRenderPipeline
  84266. * @param engine engine to add the pipeline to
  84267. * @param name name of the pipeline
  84268. */
  84269. function PostProcessRenderPipeline(engine, name) {
  84270. this.engine = engine;
  84271. this._name = name;
  84272. this._renderEffects = {};
  84273. this._renderEffectsForIsolatedPass = new Array();
  84274. this._cameras = [];
  84275. }
  84276. /**
  84277. * "PostProcessRenderPipeline"
  84278. * @returns "PostProcessRenderPipeline"
  84279. */
  84280. PostProcessRenderPipeline.prototype.getClassName = function () {
  84281. return "PostProcessRenderPipeline";
  84282. };
  84283. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84284. /**
  84285. * If all the render effects in the pipeline are support
  84286. */
  84287. get: function () {
  84288. for (var renderEffectName in this._renderEffects) {
  84289. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84290. if (!this._renderEffects[renderEffectName].isSupported) {
  84291. return false;
  84292. }
  84293. }
  84294. }
  84295. return true;
  84296. },
  84297. enumerable: true,
  84298. configurable: true
  84299. });
  84300. /**
  84301. * Adds an effect to the pipeline
  84302. * @param renderEffect the effect to add
  84303. */
  84304. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84305. this._renderEffects[renderEffect._name] = renderEffect;
  84306. };
  84307. // private
  84308. /** @hidden */
  84309. PostProcessRenderPipeline.prototype._rebuild = function () {
  84310. };
  84311. /** @hidden */
  84312. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84313. var renderEffects = this._renderEffects[renderEffectName];
  84314. if (!renderEffects) {
  84315. return;
  84316. }
  84317. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84318. };
  84319. /** @hidden */
  84320. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84321. var renderEffects = this._renderEffects[renderEffectName];
  84322. if (!renderEffects) {
  84323. return;
  84324. }
  84325. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84326. };
  84327. /** @hidden */
  84328. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84330. if (!cams) {
  84331. return;
  84332. }
  84333. var indicesToDelete = [];
  84334. var i;
  84335. for (i = 0; i < cams.length; i++) {
  84336. var camera = cams[i];
  84337. var cameraName = camera.name;
  84338. if (this._cameras.indexOf(camera) === -1) {
  84339. this._cameras[cameraName] = camera;
  84340. }
  84341. else if (unique) {
  84342. indicesToDelete.push(i);
  84343. }
  84344. }
  84345. for (i = 0; i < indicesToDelete.length; i++) {
  84346. cameras.splice(indicesToDelete[i], 1);
  84347. }
  84348. for (var renderEffectName in this._renderEffects) {
  84349. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84350. this._renderEffects[renderEffectName]._attachCameras(cams);
  84351. }
  84352. }
  84353. };
  84354. /** @hidden */
  84355. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84356. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84357. if (!cams) {
  84358. return;
  84359. }
  84360. for (var renderEffectName in this._renderEffects) {
  84361. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84362. this._renderEffects[renderEffectName]._detachCameras(cams);
  84363. }
  84364. }
  84365. for (var i = 0; i < cams.length; i++) {
  84366. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84367. }
  84368. };
  84369. /** @hidden */
  84370. PostProcessRenderPipeline.prototype._update = function () {
  84371. for (var renderEffectName in this._renderEffects) {
  84372. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84373. this._renderEffects[renderEffectName]._update();
  84374. }
  84375. }
  84376. for (var i = 0; i < this._cameras.length; i++) {
  84377. var cameraName = this._cameras[i].name;
  84378. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84379. this._renderEffectsForIsolatedPass[cameraName]._update();
  84380. }
  84381. }
  84382. };
  84383. /** @hidden */
  84384. PostProcessRenderPipeline.prototype._reset = function () {
  84385. this._renderEffects = {};
  84386. this._renderEffectsForIsolatedPass = new Array();
  84387. };
  84388. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84389. // 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)
  84390. var effectKeys = Object.keys(this._renderEffects);
  84391. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84392. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84393. if (postProcesses) {
  84394. postProcesses[0].samples = sampleCount;
  84395. return true;
  84396. }
  84397. }
  84398. return false;
  84399. };
  84400. /**
  84401. * Disposes of the pipeline
  84402. */
  84403. PostProcessRenderPipeline.prototype.dispose = function () {
  84404. // Must be implemented by children
  84405. };
  84406. __decorate([
  84407. BABYLON.serialize()
  84408. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84409. return PostProcessRenderPipeline;
  84410. }());
  84411. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84412. })(BABYLON || (BABYLON = {}));
  84413. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  84414. var BABYLON;
  84415. (function (BABYLON) {
  84416. /**
  84417. * This represents a depth renderer in Babylon.
  84418. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84419. */
  84420. var DepthRenderer = /** @class */ (function () {
  84421. /**
  84422. * Instantiates a depth renderer
  84423. * @param scene The scene the renderer belongs to
  84424. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  84425. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  84426. */
  84427. function DepthRenderer(scene, type, camera) {
  84428. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  84429. if (camera === void 0) { camera = null; }
  84430. var _this = this;
  84431. /**
  84432. * Specifiess that the depth renderer will only be used within
  84433. * the camera it is created for.
  84434. * This can help forcing its rendering during the camera processing.
  84435. */
  84436. this.useOnlyInActiveCamera = false;
  84437. this._scene = scene;
  84438. // Register the G Buffer component to the scene.
  84439. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  84440. if (!component) {
  84441. component = new BABYLON.DepthRendererSceneComponent(scene);
  84442. scene._addComponent(component);
  84443. }
  84444. this._camera = camera;
  84445. var engine = scene.getEngine();
  84446. // Render target
  84447. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  84448. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84449. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84450. this._depthMap.refreshRate = 1;
  84451. this._depthMap.renderParticles = false;
  84452. this._depthMap.renderList = null;
  84453. // Camera to get depth map from to support multiple concurrent cameras
  84454. this._depthMap.activeCamera = this._camera;
  84455. this._depthMap.ignoreCameraViewport = true;
  84456. this._depthMap.useCameraPostProcesses = false;
  84457. // set default depth value to 1.0 (far away)
  84458. this._depthMap.onClearObservable.add(function (engine) {
  84459. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  84460. });
  84461. // Custom render function
  84462. var renderSubMesh = function (subMesh) {
  84463. var mesh = subMesh.getRenderingMesh();
  84464. var scene = _this._scene;
  84465. var engine = scene.getEngine();
  84466. var material = subMesh.getMaterial();
  84467. if (!material) {
  84468. return;
  84469. }
  84470. // Culling and reverse (right handed system)
  84471. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84472. // Managing instances
  84473. var batch = mesh._getInstancesRenderList(subMesh._id);
  84474. if (batch.mustReturn) {
  84475. return;
  84476. }
  84477. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84478. var camera = _this._camera || scene.activeCamera;
  84479. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  84480. engine.enableEffect(_this._effect);
  84481. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84482. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84483. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  84484. // Alpha test
  84485. if (material && material.needAlphaTesting()) {
  84486. var alphaTexture = material.getAlphaTestTexture();
  84487. if (alphaTexture) {
  84488. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84489. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84490. }
  84491. }
  84492. // Bones
  84493. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84494. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84495. }
  84496. // Draw
  84497. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84498. }
  84499. };
  84500. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84501. var index;
  84502. if (depthOnlySubMeshes.length) {
  84503. engine.setColorWrite(false);
  84504. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84505. renderSubMesh(depthOnlySubMeshes.data[index]);
  84506. }
  84507. engine.setColorWrite(true);
  84508. }
  84509. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84510. renderSubMesh(opaqueSubMeshes.data[index]);
  84511. }
  84512. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84513. renderSubMesh(alphaTestSubMeshes.data[index]);
  84514. }
  84515. };
  84516. }
  84517. /**
  84518. * Creates the depth rendering effect and checks if the effect is ready.
  84519. * @param subMesh The submesh to be used to render the depth map of
  84520. * @param useInstances If multiple world instances should be used
  84521. * @returns if the depth renderer is ready to render the depth map
  84522. */
  84523. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  84524. var material = subMesh.getMaterial();
  84525. if (material.disableDepthWrite) {
  84526. return false;
  84527. }
  84528. var defines = [];
  84529. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84530. var mesh = subMesh.getMesh();
  84531. // Alpha test
  84532. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  84533. defines.push("#define ALPHATEST");
  84534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84535. attribs.push(BABYLON.VertexBuffer.UVKind);
  84536. defines.push("#define UV1");
  84537. }
  84538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84539. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84540. defines.push("#define UV2");
  84541. }
  84542. }
  84543. // Bones
  84544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84545. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84546. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84547. if (mesh.numBoneInfluencers > 4) {
  84548. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84549. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84550. }
  84551. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84552. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84553. }
  84554. else {
  84555. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84556. }
  84557. // Instances
  84558. if (useInstances) {
  84559. defines.push("#define INSTANCES");
  84560. attribs.push("world0");
  84561. attribs.push("world1");
  84562. attribs.push("world2");
  84563. attribs.push("world3");
  84564. }
  84565. // Get correct effect
  84566. var join = defines.join("\n");
  84567. if (this._cachedDefines !== join) {
  84568. this._cachedDefines = join;
  84569. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  84570. }
  84571. return this._effect.isReady();
  84572. };
  84573. /**
  84574. * Gets the texture which the depth map will be written to.
  84575. * @returns The depth map texture
  84576. */
  84577. DepthRenderer.prototype.getDepthMap = function () {
  84578. return this._depthMap;
  84579. };
  84580. /**
  84581. * Disposes of the depth renderer.
  84582. */
  84583. DepthRenderer.prototype.dispose = function () {
  84584. this._depthMap.dispose();
  84585. };
  84586. return DepthRenderer;
  84587. }());
  84588. BABYLON.DepthRenderer = DepthRenderer;
  84589. })(BABYLON || (BABYLON = {}));
  84590. //# sourceMappingURL=babylon.depthRenderer.js.map
  84591. var BABYLON;
  84592. (function (BABYLON) {
  84593. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  84594. camera = camera || this.activeCamera;
  84595. if (!camera) {
  84596. throw "No camera available to enable depth renderer";
  84597. }
  84598. if (!this._depthRenderer) {
  84599. this._depthRenderer = {};
  84600. }
  84601. if (!this._depthRenderer[camera.id]) {
  84602. var textureType = 0;
  84603. if (this.getEngine().getCaps().textureHalfFloatRender) {
  84604. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84605. }
  84606. else if (this.getEngine().getCaps().textureFloatRender) {
  84607. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84608. }
  84609. else {
  84610. throw "Depth renderer does not support int texture type";
  84611. }
  84612. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  84613. }
  84614. return this._depthRenderer[camera.id];
  84615. };
  84616. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  84617. camera = camera || this.activeCamera;
  84618. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  84619. return;
  84620. }
  84621. this._depthRenderer[camera.id].dispose();
  84622. delete this._depthRenderer[camera.id];
  84623. };
  84624. /**
  84625. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  84626. * in several rendering techniques.
  84627. */
  84628. var DepthRendererSceneComponent = /** @class */ (function () {
  84629. /**
  84630. * Creates a new instance of the component for the given scene
  84631. * @param scene Defines the scene to register the component in
  84632. */
  84633. function DepthRendererSceneComponent(scene) {
  84634. /**
  84635. * The component name helpfull to identify the component in the list of scene components.
  84636. */
  84637. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  84638. this.scene = scene;
  84639. }
  84640. /**
  84641. * Registers the component in a given scene
  84642. */
  84643. DepthRendererSceneComponent.prototype.register = function () {
  84644. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  84645. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  84646. };
  84647. /**
  84648. * Rebuilds the elements related to this component in case of
  84649. * context lost for instance.
  84650. */
  84651. DepthRendererSceneComponent.prototype.rebuild = function () {
  84652. // Nothing to do for this component
  84653. };
  84654. /**
  84655. * Disposes the component and the associated ressources
  84656. */
  84657. DepthRendererSceneComponent.prototype.dispose = function () {
  84658. for (var key in this.scene._depthRenderer) {
  84659. this.scene._depthRenderer[key].dispose();
  84660. }
  84661. };
  84662. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84663. if (this.scene._depthRenderer) {
  84664. for (var key in this.scene._depthRenderer) {
  84665. var depthRenderer = this.scene._depthRenderer[key];
  84666. if (!depthRenderer.useOnlyInActiveCamera) {
  84667. renderTargets.push(depthRenderer.getDepthMap());
  84668. }
  84669. }
  84670. }
  84671. };
  84672. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  84673. if (this.scene._depthRenderer) {
  84674. for (var key in this.scene._depthRenderer) {
  84675. var depthRenderer = this.scene._depthRenderer[key];
  84676. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  84677. renderTargets.push(depthRenderer.getDepthMap());
  84678. }
  84679. }
  84680. }
  84681. };
  84682. return DepthRendererSceneComponent;
  84683. }());
  84684. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  84685. })(BABYLON || (BABYLON = {}));
  84686. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  84687. var BABYLON;
  84688. (function (BABYLON) {
  84689. /**
  84690. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  84691. */
  84692. var GeometryBufferRenderer = /** @class */ (function () {
  84693. /**
  84694. * Creates a new G Buffer for the scene
  84695. * @param scene The scene the buffer belongs to
  84696. * @param ratio How big is the buffer related to the main canvas.
  84697. */
  84698. function GeometryBufferRenderer(scene, ratio) {
  84699. if (ratio === void 0) { ratio = 1; }
  84700. /**
  84701. * Dictionary used to store the previous transformation matrices of each rendered mesh
  84702. * in order to compute objects velocities when enableVelocity is set to "true"
  84703. * @hidden
  84704. */
  84705. this._previousTransformationMatrices = {};
  84706. this._enablePosition = false;
  84707. this._enableVelocity = false;
  84708. this._positionIndex = -1;
  84709. this._velocityIndex = -1;
  84710. this._scene = scene;
  84711. this._ratio = ratio;
  84712. // Register the G Buffer component to the scene.
  84713. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  84714. if (!component) {
  84715. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  84716. scene._addComponent(component);
  84717. }
  84718. // Render target
  84719. this._createRenderTargets();
  84720. }
  84721. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  84722. /**
  84723. * Set the render list (meshes to be rendered) used in the G buffer.
  84724. */
  84725. set: function (meshes) {
  84726. this._multiRenderTarget.renderList = meshes;
  84727. },
  84728. enumerable: true,
  84729. configurable: true
  84730. });
  84731. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  84732. /**
  84733. * Gets wether or not G buffer are supported by the running hardware.
  84734. * This requires draw buffer supports
  84735. */
  84736. get: function () {
  84737. return this._multiRenderTarget.isSupported;
  84738. },
  84739. enumerable: true,
  84740. configurable: true
  84741. });
  84742. /**
  84743. * Returns the index of the given texture type in the G-Buffer textures array
  84744. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  84745. * @returns the index of the given texture type in the G-Buffer textures array
  84746. */
  84747. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  84748. switch (textureType) {
  84749. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  84750. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  84751. default: return -1;
  84752. }
  84753. };
  84754. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  84755. /**
  84756. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  84757. */
  84758. get: function () {
  84759. return this._enablePosition;
  84760. },
  84761. /**
  84762. * Sets whether or not objects positions are enabled for the G buffer.
  84763. */
  84764. set: function (enable) {
  84765. this._enablePosition = enable;
  84766. this.dispose();
  84767. this._createRenderTargets();
  84768. },
  84769. enumerable: true,
  84770. configurable: true
  84771. });
  84772. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  84773. /**
  84774. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  84775. */
  84776. get: function () {
  84777. return this._enableVelocity;
  84778. },
  84779. /**
  84780. * Sets wether or not objects velocities are enabled for the G buffer.
  84781. */
  84782. set: function (enable) {
  84783. this._enableVelocity = enable;
  84784. this.dispose();
  84785. this._createRenderTargets();
  84786. },
  84787. enumerable: true,
  84788. configurable: true
  84789. });
  84790. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  84791. /**
  84792. * Gets the scene associated with the buffer.
  84793. */
  84794. get: function () {
  84795. return this._scene;
  84796. },
  84797. enumerable: true,
  84798. configurable: true
  84799. });
  84800. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  84801. /**
  84802. * Gets the ratio used by the buffer during its creation.
  84803. * How big is the buffer related to the main canvas.
  84804. */
  84805. get: function () {
  84806. return this._ratio;
  84807. },
  84808. enumerable: true,
  84809. configurable: true
  84810. });
  84811. /**
  84812. * Checks wether everything is ready to render a submesh to the G buffer.
  84813. * @param subMesh the submesh to check readiness for
  84814. * @param useInstances is the mesh drawn using instance or not
  84815. * @returns true if ready otherwise false
  84816. */
  84817. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  84818. var material = subMesh.getMaterial();
  84819. if (material && material.disableDepthWrite) {
  84820. return false;
  84821. }
  84822. var defines = [];
  84823. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84824. var mesh = subMesh.getMesh();
  84825. // Alpha test
  84826. if (material && material.needAlphaTesting()) {
  84827. defines.push("#define ALPHATEST");
  84828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84829. attribs.push(BABYLON.VertexBuffer.UVKind);
  84830. defines.push("#define UV1");
  84831. }
  84832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84834. defines.push("#define UV2");
  84835. }
  84836. }
  84837. // Buffers
  84838. if (this._enablePosition) {
  84839. defines.push("#define POSITION");
  84840. defines.push("#define POSITION_INDEX " + this._positionIndex);
  84841. }
  84842. if (this._enableVelocity) {
  84843. defines.push("#define VELOCITY");
  84844. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  84845. }
  84846. // Bones
  84847. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84848. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84849. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84850. if (mesh.numBoneInfluencers > 4) {
  84851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84853. }
  84854. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84855. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84856. }
  84857. else {
  84858. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84859. }
  84860. // Instances
  84861. if (useInstances) {
  84862. defines.push("#define INSTANCES");
  84863. attribs.push("world0");
  84864. attribs.push("world1");
  84865. attribs.push("world2");
  84866. attribs.push("world3");
  84867. }
  84868. // Setup textures count
  84869. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  84870. // Get correct effect
  84871. var join = defines.join("\n");
  84872. if (this._cachedDefines !== join) {
  84873. this._cachedDefines = join;
  84874. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  84875. }
  84876. return this._effect.isReady();
  84877. };
  84878. /**
  84879. * Gets the current underlying G Buffer.
  84880. * @returns the buffer
  84881. */
  84882. GeometryBufferRenderer.prototype.getGBuffer = function () {
  84883. return this._multiRenderTarget;
  84884. };
  84885. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  84886. /**
  84887. * Gets the number of samples used to render the buffer (anti aliasing).
  84888. */
  84889. get: function () {
  84890. return this._multiRenderTarget.samples;
  84891. },
  84892. /**
  84893. * Sets the number of samples used to render the buffer (anti aliasing).
  84894. */
  84895. set: function (value) {
  84896. this._multiRenderTarget.samples = value;
  84897. },
  84898. enumerable: true,
  84899. configurable: true
  84900. });
  84901. /**
  84902. * Disposes the renderer and frees up associated resources.
  84903. */
  84904. GeometryBufferRenderer.prototype.dispose = function () {
  84905. this.getGBuffer().dispose();
  84906. };
  84907. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  84908. var _this = this;
  84909. var engine = this._scene.getEngine();
  84910. var count = 2;
  84911. if (this._enablePosition) {
  84912. this._positionIndex = count;
  84913. count++;
  84914. }
  84915. if (this._enableVelocity) {
  84916. this._velocityIndex = count;
  84917. count++;
  84918. }
  84919. 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 });
  84920. if (!this.isSupported) {
  84921. return;
  84922. }
  84923. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84924. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84925. this._multiRenderTarget.refreshRate = 1;
  84926. this._multiRenderTarget.renderParticles = false;
  84927. this._multiRenderTarget.renderList = null;
  84928. // set default depth value to 1.0 (far away)
  84929. this._multiRenderTarget.onClearObservable.add(function (engine) {
  84930. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  84931. });
  84932. // Custom render function
  84933. var renderSubMesh = function (subMesh) {
  84934. var mesh = subMesh.getRenderingMesh();
  84935. var scene = _this._scene;
  84936. var engine = scene.getEngine();
  84937. var material = subMesh.getMaterial();
  84938. if (!material) {
  84939. return;
  84940. }
  84941. // Velocity
  84942. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  84943. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  84944. }
  84945. // Culling
  84946. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84947. // Managing instances
  84948. var batch = mesh._getInstancesRenderList(subMesh._id);
  84949. if (batch.mustReturn) {
  84950. return;
  84951. }
  84952. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84953. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  84954. engine.enableEffect(_this._effect);
  84955. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84956. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84957. _this._effect.setMatrix("view", scene.getViewMatrix());
  84958. // Alpha test
  84959. if (material && material.needAlphaTesting()) {
  84960. var alphaTexture = material.getAlphaTestTexture();
  84961. if (alphaTexture) {
  84962. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84963. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84964. }
  84965. }
  84966. // Bones
  84967. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84968. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84969. }
  84970. // Velocity
  84971. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  84972. // Draw
  84973. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84974. }
  84975. // Velocity
  84976. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  84977. };
  84978. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84979. var index;
  84980. if (depthOnlySubMeshes.length) {
  84981. engine.setColorWrite(false);
  84982. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84983. renderSubMesh(depthOnlySubMeshes.data[index]);
  84984. }
  84985. engine.setColorWrite(true);
  84986. }
  84987. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84988. renderSubMesh(opaqueSubMeshes.data[index]);
  84989. }
  84990. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84991. renderSubMesh(alphaTestSubMeshes.data[index]);
  84992. }
  84993. };
  84994. };
  84995. /**
  84996. * Constant used to retrieve the position texture index in the G-Buffer textures array
  84997. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  84998. */
  84999. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  85000. /**
  85001. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  85002. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  85003. */
  85004. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  85005. return GeometryBufferRenderer;
  85006. }());
  85007. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  85008. })(BABYLON || (BABYLON = {}));
  85009. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  85010. var BABYLON;
  85011. (function (BABYLON) {
  85012. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  85013. get: function () {
  85014. this._geometryBufferRenderer;
  85015. },
  85016. set: function (value) {
  85017. if (value && value.isSupported) {
  85018. this._geometryBufferRenderer = value;
  85019. }
  85020. },
  85021. enumerable: true,
  85022. configurable: true
  85023. });
  85024. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85025. if (ratio === void 0) { ratio = 1; }
  85026. if (this._geometryBufferRenderer) {
  85027. return this._geometryBufferRenderer;
  85028. }
  85029. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85030. if (!this._geometryBufferRenderer.isSupported) {
  85031. this._geometryBufferRenderer = null;
  85032. }
  85033. return this._geometryBufferRenderer;
  85034. };
  85035. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85036. if (!this._geometryBufferRenderer) {
  85037. return;
  85038. }
  85039. this._geometryBufferRenderer.dispose();
  85040. this._geometryBufferRenderer = null;
  85041. };
  85042. /**
  85043. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85044. * in several rendering techniques.
  85045. */
  85046. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85047. /**
  85048. * Creates a new instance of the component for the given scene
  85049. * @param scene Defines the scene to register the component in
  85050. */
  85051. function GeometryBufferRendererSceneComponent(scene) {
  85052. /**
  85053. * The component name helpful to identify the component in the list of scene components.
  85054. */
  85055. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85056. this.scene = scene;
  85057. }
  85058. /**
  85059. * Registers the component in a given scene
  85060. */
  85061. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85062. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85063. };
  85064. /**
  85065. * Rebuilds the elements related to this component in case of
  85066. * context lost for instance.
  85067. */
  85068. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85069. // Nothing to do for this component
  85070. };
  85071. /**
  85072. * Disposes the component and the associated ressources
  85073. */
  85074. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85075. // Nothing to do for this component
  85076. };
  85077. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85078. if (this.scene._geometryBufferRenderer) {
  85079. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85080. }
  85081. };
  85082. return GeometryBufferRendererSceneComponent;
  85083. }());
  85084. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85085. })(BABYLON || (BABYLON = {}));
  85086. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  85087. var BABYLON;
  85088. (function (BABYLON) {
  85089. /**
  85090. * Render pipeline to produce ssao effect
  85091. */
  85092. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85093. __extends(SSAORenderingPipeline, _super);
  85094. /**
  85095. * @constructor
  85096. * @param name - The rendering pipeline name
  85097. * @param scene - The scene linked to this pipeline
  85098. * @param 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 }
  85099. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85100. */
  85101. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85102. var _this = _super.call(this, scene.getEngine(), name) || this;
  85103. // Members
  85104. /**
  85105. * @ignore
  85106. * The PassPostProcess id in the pipeline that contains the original scene color
  85107. */
  85108. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85109. /**
  85110. * @ignore
  85111. * The SSAO PostProcess id in the pipeline
  85112. */
  85113. _this.SSAORenderEffect = "SSAORenderEffect";
  85114. /**
  85115. * @ignore
  85116. * The horizontal blur PostProcess id in the pipeline
  85117. */
  85118. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85119. /**
  85120. * @ignore
  85121. * The vertical blur PostProcess id in the pipeline
  85122. */
  85123. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85124. /**
  85125. * @ignore
  85126. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85127. */
  85128. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85129. /**
  85130. * The output strength of the SSAO post-process. Default value is 1.0.
  85131. */
  85132. _this.totalStrength = 1.0;
  85133. /**
  85134. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85135. */
  85136. _this.radius = 0.0001;
  85137. /**
  85138. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85139. * Must not be equal to fallOff and superior to fallOff.
  85140. * Default value is 0.975
  85141. */
  85142. _this.area = 0.0075;
  85143. /**
  85144. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85145. * Must not be equal to area and inferior to area.
  85146. * Default value is 0.0
  85147. */
  85148. _this.fallOff = 0.000001;
  85149. /**
  85150. * The base color of the SSAO post-process
  85151. * The final result is "base + ssao" between [0, 1]
  85152. */
  85153. _this.base = 0.5;
  85154. _this._firstUpdate = true;
  85155. _this._scene = scene;
  85156. // Set up assets
  85157. _this._createRandomTexture();
  85158. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85159. var ssaoRatio = ratio.ssaoRatio || ratio;
  85160. var combineRatio = ratio.combineRatio || ratio;
  85161. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85162. _this._createSSAOPostProcess(ssaoRatio);
  85163. _this._createBlurPostProcess(ssaoRatio);
  85164. _this._createSSAOCombinePostProcess(combineRatio);
  85165. // Set up pipeline
  85166. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85167. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85168. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85169. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85170. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85171. // Finish
  85172. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85173. if (cameras) {
  85174. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85175. }
  85176. return _this;
  85177. }
  85178. // Public Methods
  85179. /**
  85180. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85181. */
  85182. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85183. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85184. for (var i = 0; i < this._scene.cameras.length; i++) {
  85185. var camera = this._scene.cameras[i];
  85186. this._originalColorPostProcess.dispose(camera);
  85187. this._ssaoPostProcess.dispose(camera);
  85188. this._blurHPostProcess.dispose(camera);
  85189. this._blurVPostProcess.dispose(camera);
  85190. this._ssaoCombinePostProcess.dispose(camera);
  85191. }
  85192. this._randomTexture.dispose();
  85193. if (disableDepthRender) {
  85194. this._scene.disableDepthRenderer();
  85195. }
  85196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85197. _super.prototype.dispose.call(this);
  85198. };
  85199. // Private Methods
  85200. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85201. var _this = this;
  85202. var size = 16;
  85203. 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);
  85204. 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);
  85205. this._blurHPostProcess.onActivateObservable.add(function () {
  85206. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85207. _this._blurHPostProcess.kernel = size * dw;
  85208. });
  85209. this._blurVPostProcess.onActivateObservable.add(function () {
  85210. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85211. _this._blurVPostProcess.kernel = size * dw;
  85212. });
  85213. };
  85214. /** @hidden */
  85215. SSAORenderingPipeline.prototype._rebuild = function () {
  85216. this._firstUpdate = true;
  85217. _super.prototype._rebuild.call(this);
  85218. };
  85219. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85220. var _this = this;
  85221. var numSamples = 16;
  85222. var sampleSphere = [
  85223. 0.5381, 0.1856, -0.4319,
  85224. 0.1379, 0.2486, 0.4430,
  85225. 0.3371, 0.5679, -0.0057,
  85226. -0.6999, -0.0451, -0.0019,
  85227. 0.0689, -0.1598, -0.8547,
  85228. 0.0560, 0.0069, -0.1843,
  85229. -0.0146, 0.1402, 0.0762,
  85230. 0.0100, -0.1924, -0.0344,
  85231. -0.3577, -0.5301, -0.4358,
  85232. -0.3169, 0.1063, 0.0158,
  85233. 0.0103, -0.5869, 0.0046,
  85234. -0.0897, -0.4940, 0.3287,
  85235. 0.7119, -0.0154, -0.0918,
  85236. -0.0533, 0.0596, -0.5411,
  85237. 0.0352, -0.0631, 0.5460,
  85238. -0.4776, 0.2847, -0.0271
  85239. ];
  85240. var samplesFactor = 1.0 / numSamples;
  85241. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85242. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85243. "area", "fallOff", "base", "range", "viewport"
  85244. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85245. this._ssaoPostProcess.onApply = function (effect) {
  85246. if (_this._firstUpdate) {
  85247. effect.setArray3("sampleSphere", sampleSphere);
  85248. effect.setFloat("samplesFactor", samplesFactor);
  85249. effect.setFloat("randTextureTiles", 4.0);
  85250. }
  85251. effect.setFloat("totalStrength", _this.totalStrength);
  85252. effect.setFloat("radius", _this.radius);
  85253. effect.setFloat("area", _this.area);
  85254. effect.setFloat("fallOff", _this.fallOff);
  85255. effect.setFloat("base", _this.base);
  85256. effect.setTexture("textureSampler", _this._depthTexture);
  85257. effect.setTexture("randomSampler", _this._randomTexture);
  85258. };
  85259. };
  85260. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85261. var _this = this;
  85262. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85263. this._ssaoCombinePostProcess.onApply = function (effect) {
  85264. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85265. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85266. };
  85267. };
  85268. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85269. var size = 512;
  85270. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85271. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85272. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85273. var context = this._randomTexture.getContext();
  85274. var rand = function (min, max) {
  85275. return Math.random() * (max - min) + min;
  85276. };
  85277. var randVector = BABYLON.Vector3.Zero();
  85278. for (var x = 0; x < size; x++) {
  85279. for (var y = 0; y < size; y++) {
  85280. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85281. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85282. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85283. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85284. context.fillRect(x, y, 1, 1);
  85285. }
  85286. }
  85287. this._randomTexture.update(false);
  85288. };
  85289. __decorate([
  85290. BABYLON.serialize()
  85291. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85292. __decorate([
  85293. BABYLON.serialize()
  85294. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85295. __decorate([
  85296. BABYLON.serialize()
  85297. ], SSAORenderingPipeline.prototype, "area", void 0);
  85298. __decorate([
  85299. BABYLON.serialize()
  85300. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85301. __decorate([
  85302. BABYLON.serialize()
  85303. ], SSAORenderingPipeline.prototype, "base", void 0);
  85304. return SSAORenderingPipeline;
  85305. }(BABYLON.PostProcessRenderPipeline));
  85306. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85307. })(BABYLON || (BABYLON = {}));
  85308. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  85309. var BABYLON;
  85310. (function (BABYLON) {
  85311. /**
  85312. * Render pipeline to produce ssao effect
  85313. */
  85314. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85315. __extends(SSAO2RenderingPipeline, _super);
  85316. /**
  85317. * @constructor
  85318. * @param name The rendering pipeline name
  85319. * @param scene The scene linked to this pipeline
  85320. * @param 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 }
  85321. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85322. */
  85323. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85324. var _this = _super.call(this, scene.getEngine(), name) || this;
  85325. // Members
  85326. /**
  85327. * @ignore
  85328. * The PassPostProcess id in the pipeline that contains the original scene color
  85329. */
  85330. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85331. /**
  85332. * @ignore
  85333. * The SSAO PostProcess id in the pipeline
  85334. */
  85335. _this.SSAORenderEffect = "SSAORenderEffect";
  85336. /**
  85337. * @ignore
  85338. * The horizontal blur PostProcess id in the pipeline
  85339. */
  85340. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85341. /**
  85342. * @ignore
  85343. * The vertical blur PostProcess id in the pipeline
  85344. */
  85345. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85346. /**
  85347. * @ignore
  85348. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85349. */
  85350. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85351. /**
  85352. * The output strength of the SSAO post-process. Default value is 1.0.
  85353. */
  85354. _this.totalStrength = 1.0;
  85355. /**
  85356. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85357. */
  85358. _this.maxZ = 100.0;
  85359. /**
  85360. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85361. */
  85362. _this.minZAspect = 0.2;
  85363. _this._samples = 8;
  85364. _this._textureSamples = 1;
  85365. _this._expensiveBlur = true;
  85366. /**
  85367. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85368. */
  85369. _this.radius = 2.0;
  85370. /**
  85371. * The base color of the SSAO post-process
  85372. * The final result is "base + ssao" between [0, 1]
  85373. */
  85374. _this.base = 0;
  85375. _this._firstUpdate = true;
  85376. _this._bits = new Uint32Array(1);
  85377. _this._scene = scene;
  85378. _this._ratio = ratio;
  85379. if (!_this.isSupported) {
  85380. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85381. return _this;
  85382. }
  85383. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85384. var blurRatio = _this._ratio.blurRatio || ratio;
  85385. // Set up assets
  85386. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85387. _this._createRandomTexture();
  85388. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85389. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85390. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85391. _this._originalColorPostProcess.samples = _this.textureSamples;
  85392. _this._createSSAOPostProcess(1.0);
  85393. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85394. _this._createSSAOCombinePostProcess(blurRatio);
  85395. // Set up pipeline
  85396. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85398. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85399. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85400. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85401. // Finish
  85402. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85403. if (cameras) {
  85404. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85405. }
  85406. return _this;
  85407. }
  85408. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85409. get: function () {
  85410. return this._samples;
  85411. },
  85412. /**
  85413. * Number of samples used for the SSAO calculations. Default value is 8
  85414. */
  85415. set: function (n) {
  85416. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85417. this._samples = n;
  85418. this._sampleSphere = this._generateHemisphere();
  85419. this._firstUpdate = true;
  85420. },
  85421. enumerable: true,
  85422. configurable: true
  85423. });
  85424. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  85425. get: function () {
  85426. return this._textureSamples;
  85427. },
  85428. /**
  85429. * Number of samples to use for antialiasing
  85430. */
  85431. set: function (n) {
  85432. this._textureSamples = n;
  85433. this._originalColorPostProcess.samples = n;
  85434. this._blurHPostProcess.samples = n;
  85435. this._blurVPostProcess.samples = n;
  85436. this._ssaoPostProcess.samples = n;
  85437. this._ssaoCombinePostProcess.samples = n;
  85438. },
  85439. enumerable: true,
  85440. configurable: true
  85441. });
  85442. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  85443. get: function () {
  85444. return this._expensiveBlur;
  85445. },
  85446. /**
  85447. * If bilateral blur should be used
  85448. */
  85449. set: function (b) {
  85450. 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"]);
  85451. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  85452. this._expensiveBlur = b;
  85453. this._firstUpdate = true;
  85454. },
  85455. enumerable: true,
  85456. configurable: true
  85457. });
  85458. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  85459. /**
  85460. * Support test.
  85461. */
  85462. get: function () {
  85463. var engine = BABYLON.Engine.LastCreatedEngine;
  85464. if (!engine) {
  85465. return false;
  85466. }
  85467. return engine.getCaps().drawBuffersExtension;
  85468. },
  85469. enumerable: true,
  85470. configurable: true
  85471. });
  85472. // Public Methods
  85473. /**
  85474. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85475. */
  85476. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  85477. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  85478. for (var i = 0; i < this._scene.cameras.length; i++) {
  85479. var camera = this._scene.cameras[i];
  85480. this._originalColorPostProcess.dispose(camera);
  85481. this._ssaoPostProcess.dispose(camera);
  85482. this._blurHPostProcess.dispose(camera);
  85483. this._blurVPostProcess.dispose(camera);
  85484. this._ssaoCombinePostProcess.dispose(camera);
  85485. }
  85486. this._randomTexture.dispose();
  85487. if (disableGeometryBufferRenderer) {
  85488. this._scene.disableGeometryBufferRenderer();
  85489. }
  85490. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85491. _super.prototype.dispose.call(this);
  85492. };
  85493. // Private Methods
  85494. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  85495. var _this = this;
  85496. this._samplerOffsets = [];
  85497. var expensive = this.expensiveBlur;
  85498. for (var i = -8; i < 8; i++) {
  85499. this._samplerOffsets.push(i * 2 + 0.5);
  85500. }
  85501. 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");
  85502. this._blurHPostProcess.onApply = function (effect) {
  85503. if (!_this._scene.activeCamera) {
  85504. return;
  85505. }
  85506. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  85507. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85508. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85509. effect.setFloat("radius", _this.radius);
  85510. effect.setTexture("depthSampler", _this._depthTexture);
  85511. if (_this._firstUpdate) {
  85512. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85513. }
  85514. };
  85515. 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");
  85516. this._blurVPostProcess.onApply = function (effect) {
  85517. if (!_this._scene.activeCamera) {
  85518. return;
  85519. }
  85520. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  85521. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85522. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85523. effect.setFloat("radius", _this.radius);
  85524. effect.setTexture("depthSampler", _this._depthTexture);
  85525. if (_this._firstUpdate) {
  85526. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85527. _this._firstUpdate = false;
  85528. }
  85529. };
  85530. this._blurHPostProcess.samples = this.textureSamples;
  85531. this._blurVPostProcess.samples = this.textureSamples;
  85532. };
  85533. /** @hidden */
  85534. SSAO2RenderingPipeline.prototype._rebuild = function () {
  85535. this._firstUpdate = true;
  85536. _super.prototype._rebuild.call(this);
  85537. };
  85538. //Van der Corput radical inverse
  85539. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  85540. this._bits[0] = i;
  85541. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  85542. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  85543. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  85544. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  85545. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  85546. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  85547. };
  85548. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  85549. return [i / n, this._radicalInverse_VdC(i)];
  85550. };
  85551. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  85552. var phi = v * 2.0 * Math.PI;
  85553. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  85554. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  85555. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  85556. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  85557. };
  85558. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  85559. var numSamples = this.samples;
  85560. var result = [];
  85561. var vector;
  85562. var i = 0;
  85563. while (i < numSamples) {
  85564. if (numSamples < 16) {
  85565. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  85566. }
  85567. else {
  85568. var rand = this._hammersley(i, numSamples);
  85569. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  85570. }
  85571. result.push(vector.x, vector.y, vector.z);
  85572. i++;
  85573. }
  85574. return result;
  85575. };
  85576. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85577. var _this = this;
  85578. var numSamples = this.samples;
  85579. this._sampleSphere = this._generateHemisphere();
  85580. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  85581. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85582. "base", "range", "projection", "near", "far", "texelSize",
  85583. "xViewport", "yViewport", "maxZ", "minZAspect"
  85584. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85585. this._ssaoPostProcess.onApply = function (effect) {
  85586. if (_this._firstUpdate) {
  85587. effect.setArray3("sampleSphere", _this._sampleSphere);
  85588. effect.setFloat("randTextureTiles", 32.0);
  85589. }
  85590. if (!_this._scene.activeCamera) {
  85591. return;
  85592. }
  85593. effect.setFloat("samplesFactor", 1 / _this.samples);
  85594. effect.setFloat("totalStrength", _this.totalStrength);
  85595. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  85596. effect.setFloat("radius", _this.radius);
  85597. effect.setFloat("maxZ", _this.maxZ);
  85598. effect.setFloat("minZAspect", _this.minZAspect);
  85599. effect.setFloat("base", _this.base);
  85600. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85601. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85602. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  85603. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  85604. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  85605. effect.setTexture("textureSampler", _this._depthTexture);
  85606. effect.setTexture("normalSampler", _this._normalTexture);
  85607. effect.setTexture("randomSampler", _this._randomTexture);
  85608. };
  85609. this._ssaoPostProcess.samples = this.textureSamples;
  85610. };
  85611. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85612. var _this = this;
  85613. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85614. this._ssaoCombinePostProcess.onApply = function (effect) {
  85615. var viewport = _this._scene.activeCamera.viewport;
  85616. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  85617. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85618. };
  85619. this._ssaoCombinePostProcess.samples = this.textureSamples;
  85620. };
  85621. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  85622. var size = 128;
  85623. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85624. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85625. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85626. var context = this._randomTexture.getContext();
  85627. var rand = function (min, max) {
  85628. return Math.random() * (max - min) + min;
  85629. };
  85630. var randVector = BABYLON.Vector3.Zero();
  85631. for (var x = 0; x < size; x++) {
  85632. for (var y = 0; y < size; y++) {
  85633. randVector.x = rand(0.0, 1.0);
  85634. randVector.y = rand(0.0, 1.0);
  85635. randVector.z = 0.0;
  85636. randVector.normalize();
  85637. randVector.scaleInPlace(255);
  85638. randVector.x = Math.floor(randVector.x);
  85639. randVector.y = Math.floor(randVector.y);
  85640. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85641. context.fillRect(x, y, 1, 1);
  85642. }
  85643. }
  85644. this._randomTexture.update(false);
  85645. };
  85646. /**
  85647. * Serialize the rendering pipeline (Used when exporting)
  85648. * @returns the serialized object
  85649. */
  85650. SSAO2RenderingPipeline.prototype.serialize = function () {
  85651. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85652. serializationObject.customType = "SSAO2RenderingPipeline";
  85653. return serializationObject;
  85654. };
  85655. /**
  85656. * Parse the serialized pipeline
  85657. * @param source Source pipeline.
  85658. * @param scene The scene to load the pipeline to.
  85659. * @param rootUrl The URL of the serialized pipeline.
  85660. * @returns An instantiated pipeline from the serialized object.
  85661. */
  85662. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  85663. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85664. };
  85665. __decorate([
  85666. BABYLON.serialize()
  85667. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  85668. __decorate([
  85669. BABYLON.serialize()
  85670. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  85671. __decorate([
  85672. BABYLON.serialize()
  85673. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  85674. __decorate([
  85675. BABYLON.serialize("samples")
  85676. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  85677. __decorate([
  85678. BABYLON.serialize("textureSamples")
  85679. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  85680. __decorate([
  85681. BABYLON.serialize()
  85682. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  85683. __decorate([
  85684. BABYLON.serialize("expensiveBlur")
  85685. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  85686. __decorate([
  85687. BABYLON.serialize()
  85688. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  85689. __decorate([
  85690. BABYLON.serialize()
  85691. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  85692. return SSAO2RenderingPipeline;
  85693. }(BABYLON.PostProcessRenderPipeline));
  85694. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  85695. })(BABYLON || (BABYLON = {}));
  85696. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  85697. var BABYLON;
  85698. (function (BABYLON) {
  85699. /**
  85700. * BABYLON.JS Chromatic Aberration GLSL Shader
  85701. * Author: Olivier Guyot
  85702. * Separates very slightly R, G and B colors on the edges of the screen
  85703. * Inspired by Francois Tarlier & Martins Upitis
  85704. */
  85705. var LensRenderingPipeline = /** @class */ (function (_super) {
  85706. __extends(LensRenderingPipeline, _super);
  85707. /**
  85708. * @constructor
  85709. *
  85710. * Effect parameters are as follow:
  85711. * {
  85712. * chromatic_aberration: number; // from 0 to x (1 for realism)
  85713. * edge_blur: number; // from 0 to x (1 for realism)
  85714. * distortion: number; // from 0 to x (1 for realism)
  85715. * grain_amount: number; // from 0 to 1
  85716. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  85717. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  85718. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  85719. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  85720. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  85721. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  85722. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  85723. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  85724. * }
  85725. * Note: if an effect parameter is unset, effect is disabled
  85726. *
  85727. * @param name The rendering pipeline name
  85728. * @param parameters - An object containing all parameters (see above)
  85729. * @param scene The scene linked to this pipeline
  85730. * @param 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)
  85731. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85732. */
  85733. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  85734. if (ratio === void 0) { ratio = 1.0; }
  85735. var _this = _super.call(this, scene.getEngine(), name) || this;
  85736. // Lens effects can be of the following:
  85737. // - chromatic aberration (slight shift of RGB colors)
  85738. // - blur on the edge of the lens
  85739. // - lens distortion
  85740. // - depth-of-field blur & highlights enhancing
  85741. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  85742. // - grain effect (noise or custom texture)
  85743. // Two additional texture samplers are needed:
  85744. // - depth map (for depth-of-field)
  85745. // - grain texture
  85746. /**
  85747. * @ignore
  85748. * The chromatic aberration PostProcess id in the pipeline
  85749. */
  85750. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  85751. /**
  85752. * @ignore
  85753. * The highlights enhancing PostProcess id in the pipeline
  85754. */
  85755. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  85756. /**
  85757. * @ignore
  85758. * The depth-of-field PostProcess id in the pipeline
  85759. */
  85760. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  85761. _this._scene = scene;
  85762. // Fetch texture samplers
  85763. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85764. if (parameters.grain_texture) {
  85765. _this._grainTexture = parameters.grain_texture;
  85766. }
  85767. else {
  85768. _this._createGrainTexture();
  85769. }
  85770. // save parameters
  85771. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  85772. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  85773. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  85774. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  85775. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  85776. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  85777. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  85778. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  85779. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  85780. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  85781. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  85782. // Create effects
  85783. _this._createChromaticAberrationPostProcess(ratio);
  85784. _this._createHighlightsPostProcess(ratio);
  85785. _this._createDepthOfFieldPostProcess(ratio / 4);
  85786. // Set up pipeline
  85787. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  85788. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  85789. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  85790. if (_this._highlightsGain === -1) {
  85791. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  85792. }
  85793. // Finish
  85794. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85795. if (cameras) {
  85796. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85797. }
  85798. return _this;
  85799. }
  85800. // public methods (self explanatory)
  85801. /**
  85802. * Sets the amount of blur at the edges
  85803. * @param amount blur amount
  85804. */
  85805. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  85806. /**
  85807. * Sets edge blur to 0
  85808. */
  85809. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  85810. /**
  85811. * Sets the amout of grain
  85812. * @param amount Amount of grain
  85813. */
  85814. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  85815. /**
  85816. * Set grain amount to 0
  85817. */
  85818. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  85819. /**
  85820. * Sets the chromatic aberration amount
  85821. * @param amount amount of chromatic aberration
  85822. */
  85823. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  85824. /**
  85825. * Sets chromatic aberration amount to 0
  85826. */
  85827. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  85828. /**
  85829. * Sets the EdgeDistortion amount
  85830. * @param amount amount of EdgeDistortion
  85831. */
  85832. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  85833. /**
  85834. * Sets edge distortion to 0
  85835. */
  85836. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  85837. /**
  85838. * Sets the FocusDistance amount
  85839. * @param amount amount of FocusDistance
  85840. */
  85841. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  85842. /**
  85843. * Disables depth of field
  85844. */
  85845. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  85846. /**
  85847. * Sets the Aperture amount
  85848. * @param amount amount of Aperture
  85849. */
  85850. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  85851. /**
  85852. * Sets the DarkenOutOfFocus amount
  85853. * @param amount amount of DarkenOutOfFocus
  85854. */
  85855. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  85856. /**
  85857. * Creates a pentagon bokeh effect
  85858. */
  85859. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  85860. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  85861. };
  85862. /**
  85863. * Disables the pentagon bokeh effect
  85864. */
  85865. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  85866. this._highlightsPostProcess.updateEffect();
  85867. };
  85868. /**
  85869. * Enables noise blur
  85870. */
  85871. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  85872. /**
  85873. * Disables noise blur
  85874. */
  85875. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  85876. /**
  85877. * Sets the HighlightsGain amount
  85878. * @param amount amount of HighlightsGain
  85879. */
  85880. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  85881. this._highlightsGain = amount;
  85882. };
  85883. /**
  85884. * Sets the HighlightsThreshold amount
  85885. * @param amount amount of HighlightsThreshold
  85886. */
  85887. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  85888. if (this._highlightsGain === -1) {
  85889. this._highlightsGain = 1.0;
  85890. }
  85891. this._highlightsThreshold = amount;
  85892. };
  85893. /**
  85894. * Disables highlights
  85895. */
  85896. LensRenderingPipeline.prototype.disableHighlights = function () {
  85897. this._highlightsGain = -1;
  85898. };
  85899. /**
  85900. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  85901. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  85902. */
  85903. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85904. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85905. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85906. this._chromaticAberrationPostProcess = null;
  85907. this._highlightsPostProcess = null;
  85908. this._depthOfFieldPostProcess = null;
  85909. this._grainTexture.dispose();
  85910. if (disableDepthRender) {
  85911. this._scene.disableDepthRenderer();
  85912. }
  85913. };
  85914. // colors shifting and distortion
  85915. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  85916. var _this = this;
  85917. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  85918. [], // samplers
  85919. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85920. this._chromaticAberrationPostProcess.onApply = function (effect) {
  85921. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  85922. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85923. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85924. effect.setFloat('radialIntensity', 1);
  85925. effect.setFloat2('direction', 17, 17);
  85926. effect.setFloat2('centerPosition', 0.5, 0.5);
  85927. };
  85928. };
  85929. // highlights enhancing
  85930. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  85931. var _this = this;
  85932. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  85933. [], // samplers
  85934. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  85935. this._highlightsPostProcess.onApply = function (effect) {
  85936. effect.setFloat('gain', _this._highlightsGain);
  85937. effect.setFloat('threshold', _this._highlightsThreshold);
  85938. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  85939. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85940. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85941. };
  85942. };
  85943. // colors shifting and distortion
  85944. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  85945. var _this = this;
  85946. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  85947. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  85948. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  85949. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85950. this._depthOfFieldPostProcess.onApply = function (effect) {
  85951. effect.setTexture("depthSampler", _this._depthTexture);
  85952. effect.setTexture("grainSampler", _this._grainTexture);
  85953. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  85954. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  85955. effect.setFloat('grain_amount', _this._grainAmount);
  85956. effect.setBool('blur_noise', _this._blurNoise);
  85957. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85958. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85959. effect.setFloat('distortion', _this._distortion);
  85960. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  85961. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  85962. effect.setFloat('aperture', _this._dofAperture);
  85963. effect.setFloat('darken', _this._dofDarken);
  85964. effect.setFloat('edge_blur', _this._edgeBlur);
  85965. effect.setBool('highlights', (_this._highlightsGain !== -1));
  85966. if (_this._scene.activeCamera) {
  85967. effect.setFloat('near', _this._scene.activeCamera.minZ);
  85968. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  85969. }
  85970. };
  85971. };
  85972. // creates a black and white random noise texture, 512x512
  85973. LensRenderingPipeline.prototype._createGrainTexture = function () {
  85974. var size = 512;
  85975. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85976. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85977. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85978. var context = this._grainTexture.getContext();
  85979. var rand = function (min, max) {
  85980. return Math.random() * (max - min) + min;
  85981. };
  85982. var value;
  85983. for (var x = 0; x < size; x++) {
  85984. for (var y = 0; y < size; y++) {
  85985. value = Math.floor(rand(0.42, 0.58) * 255);
  85986. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  85987. context.fillRect(x, y, 1, 1);
  85988. }
  85989. }
  85990. this._grainTexture.update(false);
  85991. };
  85992. return LensRenderingPipeline;
  85993. }(BABYLON.PostProcessRenderPipeline));
  85994. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  85995. })(BABYLON || (BABYLON = {}));
  85996. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  85997. var BABYLON;
  85998. (function (BABYLON) {
  85999. /**
  86000. * Standard rendering pipeline
  86001. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86002. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  86003. */
  86004. var StandardRenderingPipeline = /** @class */ (function (_super) {
  86005. __extends(StandardRenderingPipeline, _super);
  86006. /**
  86007. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86008. * @constructor
  86009. * @param name The rendering pipeline name
  86010. * @param scene The scene linked to this pipeline
  86011. * @param 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)
  86012. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  86013. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86014. */
  86015. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  86016. if (originalPostProcess === void 0) { originalPostProcess = null; }
  86017. var _this = _super.call(this, scene.getEngine(), name) || this;
  86018. /**
  86019. * Post-process used to down scale an image x4
  86020. */
  86021. _this.downSampleX4PostProcess = null;
  86022. /**
  86023. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86024. */
  86025. _this.brightPassPostProcess = null;
  86026. /**
  86027. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86028. */
  86029. _this.blurHPostProcesses = [];
  86030. /**
  86031. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86032. */
  86033. _this.blurVPostProcesses = [];
  86034. /**
  86035. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86036. */
  86037. _this.textureAdderPostProcess = null;
  86038. /**
  86039. * Post-process used to create volumetric lighting effect
  86040. */
  86041. _this.volumetricLightPostProcess = null;
  86042. /**
  86043. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86044. */
  86045. _this.volumetricLightSmoothXPostProcess = null;
  86046. /**
  86047. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86048. */
  86049. _this.volumetricLightSmoothYPostProcess = null;
  86050. /**
  86051. * Post-process used to merge the volumetric light effect and the real scene color
  86052. */
  86053. _this.volumetricLightMergePostProces = null;
  86054. /**
  86055. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86056. */
  86057. _this.volumetricLightFinalPostProcess = null;
  86058. /**
  86059. * Base post-process used to calculate the average luminance of the final image for HDR
  86060. */
  86061. _this.luminancePostProcess = null;
  86062. /**
  86063. * Post-processes used to create down sample post-processes in order to get
  86064. * the average luminance of the final image for HDR
  86065. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86066. */
  86067. _this.luminanceDownSamplePostProcesses = [];
  86068. /**
  86069. * Post-process used to create a HDR effect (light adaptation)
  86070. */
  86071. _this.hdrPostProcess = null;
  86072. /**
  86073. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86074. */
  86075. _this.textureAdderFinalPostProcess = null;
  86076. /**
  86077. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86078. */
  86079. _this.lensFlareFinalPostProcess = null;
  86080. /**
  86081. * Post-process used to merge the final HDR post-process and the real scene color
  86082. */
  86083. _this.hdrFinalPostProcess = null;
  86084. /**
  86085. * Post-process used to create a lens flare effect
  86086. */
  86087. _this.lensFlarePostProcess = null;
  86088. /**
  86089. * Post-process that merges the result of the lens flare post-process and the real scene color
  86090. */
  86091. _this.lensFlareComposePostProcess = null;
  86092. /**
  86093. * Post-process used to create a motion blur effect
  86094. */
  86095. _this.motionBlurPostProcess = null;
  86096. /**
  86097. * Post-process used to create a depth of field effect
  86098. */
  86099. _this.depthOfFieldPostProcess = null;
  86100. /**
  86101. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86102. */
  86103. _this.fxaaPostProcess = null;
  86104. // Values
  86105. /**
  86106. * Represents the brightness threshold in order to configure the illuminated surfaces
  86107. */
  86108. _this.brightThreshold = 1.0;
  86109. /**
  86110. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86111. */
  86112. _this.blurWidth = 512.0;
  86113. /**
  86114. * Sets if the blur for highlighted surfaces must be only horizontal
  86115. */
  86116. _this.horizontalBlur = false;
  86117. /**
  86118. * Sets the overall exposure used by the pipeline
  86119. */
  86120. _this.exposure = 1.0;
  86121. /**
  86122. * Texture used typically to simulate "dirty" on camera lens
  86123. */
  86124. _this.lensTexture = null;
  86125. /**
  86126. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86127. */
  86128. _this.volumetricLightCoefficient = 0.2;
  86129. /**
  86130. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86131. */
  86132. _this.volumetricLightPower = 4.0;
  86133. /**
  86134. * Used the set the blur intensity to smooth the volumetric lights
  86135. */
  86136. _this.volumetricLightBlurScale = 64.0;
  86137. /**
  86138. * Light (spot or directional) used to generate the volumetric lights rays
  86139. * The source light must have a shadow generate so the pipeline can get its
  86140. * depth map
  86141. */
  86142. _this.sourceLight = null;
  86143. /**
  86144. * For eye adaptation, represents the minimum luminance the eye can see
  86145. */
  86146. _this.hdrMinimumLuminance = 1.0;
  86147. /**
  86148. * For eye adaptation, represents the decrease luminance speed
  86149. */
  86150. _this.hdrDecreaseRate = 0.5;
  86151. /**
  86152. * For eye adaptation, represents the increase luminance speed
  86153. */
  86154. _this.hdrIncreaseRate = 0.5;
  86155. /**
  86156. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86157. */
  86158. _this.lensColorTexture = null;
  86159. /**
  86160. * The overall strengh for the lens flare effect
  86161. */
  86162. _this.lensFlareStrength = 20.0;
  86163. /**
  86164. * Dispersion coefficient for lens flare ghosts
  86165. */
  86166. _this.lensFlareGhostDispersal = 1.4;
  86167. /**
  86168. * Main lens flare halo width
  86169. */
  86170. _this.lensFlareHaloWidth = 0.7;
  86171. /**
  86172. * Based on the lens distortion effect, defines how much the lens flare result
  86173. * is distorted
  86174. */
  86175. _this.lensFlareDistortionStrength = 16.0;
  86176. /**
  86177. * Lens star texture must be used to simulate rays on the flares and is available
  86178. * in the documentation
  86179. */
  86180. _this.lensStarTexture = null;
  86181. /**
  86182. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86183. * flare effect by taking account of the dirt texture
  86184. */
  86185. _this.lensFlareDirtTexture = null;
  86186. /**
  86187. * Represents the focal length for the depth of field effect
  86188. */
  86189. _this.depthOfFieldDistance = 10.0;
  86190. /**
  86191. * Represents the blur intensity for the blurred part of the depth of field effect
  86192. */
  86193. _this.depthOfFieldBlurWidth = 64.0;
  86194. /**
  86195. * For motion blur, defines how much the image is blurred by the movement
  86196. */
  86197. _this.motionStrength = 1.0;
  86198. /**
  86199. * List of animations for the pipeline (IAnimatable implementation)
  86200. */
  86201. _this.animations = [];
  86202. _this._currentDepthOfFieldSource = null;
  86203. _this._hdrCurrentLuminance = 1.0;
  86204. // Getters and setters
  86205. _this._bloomEnabled = false;
  86206. _this._depthOfFieldEnabled = false;
  86207. _this._vlsEnabled = false;
  86208. _this._lensFlareEnabled = false;
  86209. _this._hdrEnabled = false;
  86210. _this._motionBlurEnabled = false;
  86211. _this._fxaaEnabled = false;
  86212. _this._motionBlurSamples = 64.0;
  86213. _this._volumetricLightStepsCount = 50.0;
  86214. _this._samples = 1;
  86215. _this._cameras = cameras || [];
  86216. // Initialize
  86217. _this._scene = scene;
  86218. _this._basePostProcess = originalPostProcess;
  86219. _this._ratio = ratio;
  86220. // Misc
  86221. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86222. // Finish
  86223. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86224. _this._buildPipeline();
  86225. return _this;
  86226. }
  86227. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86228. /**
  86229. * @ignore
  86230. * Specifies if the bloom pipeline is enabled
  86231. */
  86232. get: function () {
  86233. return this._bloomEnabled;
  86234. },
  86235. set: function (enabled) {
  86236. if (this._bloomEnabled === enabled) {
  86237. return;
  86238. }
  86239. this._bloomEnabled = enabled;
  86240. this._buildPipeline();
  86241. },
  86242. enumerable: true,
  86243. configurable: true
  86244. });
  86245. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86246. /**
  86247. * @ignore
  86248. * Specifies if the depth of field pipeline is enabed
  86249. */
  86250. get: function () {
  86251. return this._depthOfFieldEnabled;
  86252. },
  86253. set: function (enabled) {
  86254. if (this._depthOfFieldEnabled === enabled) {
  86255. return;
  86256. }
  86257. this._depthOfFieldEnabled = enabled;
  86258. this._buildPipeline();
  86259. },
  86260. enumerable: true,
  86261. configurable: true
  86262. });
  86263. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86264. /**
  86265. * @ignore
  86266. * Specifies if the lens flare pipeline is enabed
  86267. */
  86268. get: function () {
  86269. return this._lensFlareEnabled;
  86270. },
  86271. set: function (enabled) {
  86272. if (this._lensFlareEnabled === enabled) {
  86273. return;
  86274. }
  86275. this._lensFlareEnabled = enabled;
  86276. this._buildPipeline();
  86277. },
  86278. enumerable: true,
  86279. configurable: true
  86280. });
  86281. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86282. /**
  86283. * @ignore
  86284. * Specifies if the HDR pipeline is enabled
  86285. */
  86286. get: function () {
  86287. return this._hdrEnabled;
  86288. },
  86289. set: function (enabled) {
  86290. if (this._hdrEnabled === enabled) {
  86291. return;
  86292. }
  86293. this._hdrEnabled = enabled;
  86294. this._buildPipeline();
  86295. },
  86296. enumerable: true,
  86297. configurable: true
  86298. });
  86299. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86300. /**
  86301. * @ignore
  86302. * Specifies if the volumetric lights scattering effect is enabled
  86303. */
  86304. get: function () {
  86305. return this._vlsEnabled;
  86306. },
  86307. set: function (enabled) {
  86308. if (this._vlsEnabled === enabled) {
  86309. return;
  86310. }
  86311. if (enabled) {
  86312. var geometry = this._scene.enableGeometryBufferRenderer();
  86313. if (!geometry) {
  86314. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86315. return;
  86316. }
  86317. }
  86318. this._vlsEnabled = enabled;
  86319. this._buildPipeline();
  86320. },
  86321. enumerable: true,
  86322. configurable: true
  86323. });
  86324. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86325. /**
  86326. * @ignore
  86327. * Specifies if the motion blur effect is enabled
  86328. */
  86329. get: function () {
  86330. return this._motionBlurEnabled;
  86331. },
  86332. set: function (enabled) {
  86333. if (this._motionBlurEnabled === enabled) {
  86334. return;
  86335. }
  86336. this._motionBlurEnabled = enabled;
  86337. this._buildPipeline();
  86338. },
  86339. enumerable: true,
  86340. configurable: true
  86341. });
  86342. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86343. /**
  86344. * Specifies if anti-aliasing is enabled
  86345. */
  86346. get: function () {
  86347. return this._fxaaEnabled;
  86348. },
  86349. set: function (enabled) {
  86350. if (this._fxaaEnabled === enabled) {
  86351. return;
  86352. }
  86353. this._fxaaEnabled = enabled;
  86354. this._buildPipeline();
  86355. },
  86356. enumerable: true,
  86357. configurable: true
  86358. });
  86359. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86360. /**
  86361. * Specifies the number of steps used to calculate the volumetric lights
  86362. * Typically in interval [50, 200]
  86363. */
  86364. get: function () {
  86365. return this._volumetricLightStepsCount;
  86366. },
  86367. set: function (count) {
  86368. if (this.volumetricLightPostProcess) {
  86369. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86370. }
  86371. this._volumetricLightStepsCount = count;
  86372. },
  86373. enumerable: true,
  86374. configurable: true
  86375. });
  86376. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86377. /**
  86378. * Specifies the number of samples used for the motion blur effect
  86379. * Typically in interval [16, 64]
  86380. */
  86381. get: function () {
  86382. return this._motionBlurSamples;
  86383. },
  86384. set: function (samples) {
  86385. if (this.motionBlurPostProcess) {
  86386. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86387. }
  86388. this._motionBlurSamples = samples;
  86389. },
  86390. enumerable: true,
  86391. configurable: true
  86392. });
  86393. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86394. /**
  86395. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86396. */
  86397. get: function () {
  86398. return this._samples;
  86399. },
  86400. set: function (sampleCount) {
  86401. if (this._samples === sampleCount) {
  86402. return;
  86403. }
  86404. this._samples = sampleCount;
  86405. this._buildPipeline();
  86406. },
  86407. enumerable: true,
  86408. configurable: true
  86409. });
  86410. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86411. var _this = this;
  86412. var ratio = this._ratio;
  86413. var scene = this._scene;
  86414. this._disposePostProcesses();
  86415. this._reset();
  86416. // Create pass post-process
  86417. if (!this._basePostProcess) {
  86418. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86419. this.originalPostProcess.onApply = function (effect) {
  86420. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86421. };
  86422. }
  86423. else {
  86424. this.originalPostProcess = this._basePostProcess;
  86425. }
  86426. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  86427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  86428. }
  86429. this._currentDepthOfFieldSource = this.originalPostProcess;
  86430. if (this._bloomEnabled) {
  86431. // Create down sample X4 post-process
  86432. this._createDownSampleX4PostProcess(scene, ratio / 2);
  86433. // Create bright pass post-process
  86434. this._createBrightPassPostProcess(scene, ratio / 2);
  86435. // Create gaussian blur post-processes (down sampling blurs)
  86436. this._createBlurPostProcesses(scene, ratio / 4, 1);
  86437. // Create texture adder post-process
  86438. this._createTextureAdderPostProcess(scene, ratio);
  86439. // Create depth-of-field source post-process
  86440. 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);
  86441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  86442. }
  86443. if (this._vlsEnabled) {
  86444. // Create volumetric light
  86445. this._createVolumetricLightPostProcess(scene, ratio);
  86446. // Create volumetric light final post-process
  86447. 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);
  86448. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  86449. }
  86450. if (this._lensFlareEnabled) {
  86451. // Create lens flare post-process
  86452. this._createLensFlarePostProcess(scene, ratio);
  86453. // Create depth-of-field source post-process post lens-flare and disable it now
  86454. 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);
  86455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  86456. }
  86457. if (this._hdrEnabled) {
  86458. // Create luminance
  86459. this._createLuminancePostProcesses(scene, this._floatTextureType);
  86460. // Create HDR
  86461. this._createHdrPostProcess(scene, ratio);
  86462. // Create depth-of-field source post-process post hdr and disable it now
  86463. 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);
  86464. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  86465. }
  86466. if (this._depthOfFieldEnabled) {
  86467. // Create gaussian blur used by depth-of-field
  86468. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  86469. // Create depth-of-field post-process
  86470. this._createDepthOfFieldPostProcess(scene, ratio);
  86471. }
  86472. if (this._motionBlurEnabled) {
  86473. // Create motion blur post-process
  86474. this._createMotionBlurPostProcess(scene, ratio);
  86475. }
  86476. if (this._fxaaEnabled) {
  86477. // Create fxaa post-process
  86478. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86479. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  86480. }
  86481. if (this._cameras !== null) {
  86482. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86483. }
  86484. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  86485. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86486. }
  86487. };
  86488. // Down Sample X4 Post-Processs
  86489. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  86490. var _this = this;
  86491. var downSampleX4Offsets = new Array(32);
  86492. 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);
  86493. this.downSampleX4PostProcess.onApply = function (effect) {
  86494. var id = 0;
  86495. var width = _this.downSampleX4PostProcess.width;
  86496. var height = _this.downSampleX4PostProcess.height;
  86497. for (var i = -2; i < 2; i++) {
  86498. for (var j = -2; j < 2; j++) {
  86499. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  86500. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  86501. id += 2;
  86502. }
  86503. }
  86504. effect.setArray2("dsOffsets", downSampleX4Offsets);
  86505. };
  86506. // Add to pipeline
  86507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  86508. };
  86509. // Brightpass Post-Process
  86510. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  86511. var _this = this;
  86512. var brightOffsets = new Array(8);
  86513. 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);
  86514. this.brightPassPostProcess.onApply = function (effect) {
  86515. var sU = (1.0 / _this.brightPassPostProcess.width);
  86516. var sV = (1.0 / _this.brightPassPostProcess.height);
  86517. brightOffsets[0] = -0.5 * sU;
  86518. brightOffsets[1] = 0.5 * sV;
  86519. brightOffsets[2] = 0.5 * sU;
  86520. brightOffsets[3] = 0.5 * sV;
  86521. brightOffsets[4] = -0.5 * sU;
  86522. brightOffsets[5] = -0.5 * sV;
  86523. brightOffsets[6] = 0.5 * sU;
  86524. brightOffsets[7] = -0.5 * sV;
  86525. effect.setArray2("dsOffsets", brightOffsets);
  86526. effect.setFloat("brightThreshold", _this.brightThreshold);
  86527. };
  86528. // Add to pipeline
  86529. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  86530. };
  86531. // Create blur H&V post-processes
  86532. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  86533. var _this = this;
  86534. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  86535. var engine = scene.getEngine();
  86536. 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);
  86537. 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);
  86538. blurX.onActivateObservable.add(function () {
  86539. var dw = blurX.width / engine.getRenderWidth();
  86540. blurX.kernel = _this[blurWidthKey] * dw;
  86541. });
  86542. blurY.onActivateObservable.add(function () {
  86543. var dw = blurY.height / engine.getRenderHeight();
  86544. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  86545. });
  86546. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  86547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  86548. this.blurHPostProcesses.push(blurX);
  86549. this.blurVPostProcesses.push(blurY);
  86550. };
  86551. // Create texture adder post-process
  86552. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  86553. var _this = this;
  86554. 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);
  86555. this.textureAdderPostProcess.onApply = function (effect) {
  86556. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  86557. effect.setTexture("lensSampler", _this.lensTexture);
  86558. effect.setFloat("exposure", _this.exposure);
  86559. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  86560. };
  86561. // Add to pipeline
  86562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  86563. };
  86564. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  86565. var _this = this;
  86566. var geometryRenderer = scene.enableGeometryBufferRenderer();
  86567. geometryRenderer.enablePosition = true;
  86568. var geometry = geometryRenderer.getGBuffer();
  86569. // Base post-process
  86570. 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));
  86571. var depthValues = BABYLON.Vector2.Zero();
  86572. this.volumetricLightPostProcess.onApply = function (effect) {
  86573. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  86574. var generator = _this.sourceLight.getShadowGenerator();
  86575. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  86576. effect.setTexture("positionSampler", geometry.textures[2]);
  86577. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  86578. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  86579. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  86580. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  86581. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  86582. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  86583. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  86584. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  86585. effect.setVector2("depthValues", depthValues);
  86586. }
  86587. };
  86588. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  86589. // Smooth
  86590. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  86591. // Merge
  86592. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  86593. this.volumetricLightMergePostProces.onApply = function (effect) {
  86594. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  86595. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  86596. };
  86597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  86598. };
  86599. // Create luminance
  86600. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  86601. var _this = this;
  86602. // Create luminance
  86603. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  86604. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  86605. var offsets = [];
  86606. this.luminancePostProcess.onApply = function (effect) {
  86607. var sU = (1.0 / _this.luminancePostProcess.width);
  86608. var sV = (1.0 / _this.luminancePostProcess.height);
  86609. offsets[0] = -0.5 * sU;
  86610. offsets[1] = 0.5 * sV;
  86611. offsets[2] = 0.5 * sU;
  86612. offsets[3] = 0.5 * sV;
  86613. offsets[4] = -0.5 * sU;
  86614. offsets[5] = -0.5 * sV;
  86615. offsets[6] = 0.5 * sU;
  86616. offsets[7] = -0.5 * sV;
  86617. effect.setArray2("lumOffsets", offsets);
  86618. };
  86619. // Add to pipeline
  86620. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  86621. // Create down sample luminance
  86622. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  86623. var size = Math.pow(3, i);
  86624. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  86625. if (i === 0) {
  86626. defines += "#define FINAL_DOWN_SAMPLER";
  86627. }
  86628. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  86629. this.luminanceDownSamplePostProcesses.push(postProcess);
  86630. }
  86631. // Create callbacks and add effects
  86632. var lastLuminance = this.luminancePostProcess;
  86633. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  86634. var downSampleOffsets = new Array(18);
  86635. pp.onApply = function (effect) {
  86636. if (!lastLuminance) {
  86637. return;
  86638. }
  86639. var id = 0;
  86640. for (var x = -1; x < 2; x++) {
  86641. for (var y = -1; y < 2; y++) {
  86642. downSampleOffsets[id] = x / lastLuminance.width;
  86643. downSampleOffsets[id + 1] = y / lastLuminance.height;
  86644. id += 2;
  86645. }
  86646. }
  86647. effect.setArray2("dsOffsets", downSampleOffsets);
  86648. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  86649. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86650. lastLuminance = _this.luminancePostProcess;
  86651. }
  86652. else {
  86653. lastLuminance = pp;
  86654. }
  86655. };
  86656. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86657. pp.onAfterRender = function (effect) {
  86658. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  86659. 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);
  86660. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  86661. };
  86662. }
  86663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  86664. });
  86665. };
  86666. // Create HDR post-process
  86667. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  86668. var _this = this;
  86669. 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);
  86670. var outputLiminance = 1;
  86671. var time = 0;
  86672. var lastTime = 0;
  86673. this.hdrPostProcess.onApply = function (effect) {
  86674. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  86675. time += scene.getEngine().getDeltaTime();
  86676. if (outputLiminance < 0) {
  86677. outputLiminance = _this._hdrCurrentLuminance;
  86678. }
  86679. else {
  86680. var dt = (lastTime - time) / 1000.0;
  86681. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  86682. outputLiminance += _this.hdrDecreaseRate * dt;
  86683. }
  86684. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  86685. outputLiminance -= _this.hdrIncreaseRate * dt;
  86686. }
  86687. else {
  86688. outputLiminance = _this._hdrCurrentLuminance;
  86689. }
  86690. }
  86691. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  86692. effect.setFloat("averageLuminance", outputLiminance);
  86693. lastTime = time;
  86694. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  86695. };
  86696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  86697. };
  86698. // Create lens flare post-process
  86699. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  86700. var _this = this;
  86701. 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);
  86702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  86703. this._createBlurPostProcesses(scene, ratio / 4, 2);
  86704. 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);
  86705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  86706. var resolution = new BABYLON.Vector2(0, 0);
  86707. // Lens flare
  86708. this.lensFlarePostProcess.onApply = function (effect) {
  86709. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  86710. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  86711. effect.setFloat("strength", _this.lensFlareStrength);
  86712. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  86713. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  86714. // Shift
  86715. resolution.x = _this.lensFlarePostProcess.width;
  86716. resolution.y = _this.lensFlarePostProcess.height;
  86717. effect.setVector2("resolution", resolution);
  86718. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  86719. };
  86720. // Compose
  86721. 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);
  86722. 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);
  86723. this.lensFlareComposePostProcess.onApply = function (effect) {
  86724. if (!_this._scene.activeCamera) {
  86725. return;
  86726. }
  86727. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86728. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  86729. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  86730. // Lens start rotation matrix
  86731. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  86732. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  86733. 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));
  86734. camRot *= 4.0;
  86735. 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);
  86736. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  86737. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  86738. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  86739. };
  86740. };
  86741. // Create depth-of-field post-process
  86742. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  86743. var _this = this;
  86744. 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);
  86745. this.depthOfFieldPostProcess.onApply = function (effect) {
  86746. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86747. effect.setTexture("depthSampler", _this._getDepthTexture());
  86748. effect.setFloat("distance", _this.depthOfFieldDistance);
  86749. };
  86750. // Add to pipeline
  86751. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  86752. };
  86753. // Create motion blur post-process
  86754. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  86755. var _this = this;
  86756. 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);
  86757. var motionScale = 0;
  86758. var prevViewProjection = BABYLON.Matrix.Identity();
  86759. var invViewProjection = BABYLON.Matrix.Identity();
  86760. var viewProjection = BABYLON.Matrix.Identity();
  86761. var screenSize = BABYLON.Vector2.Zero();
  86762. this.motionBlurPostProcess.onApply = function (effect) {
  86763. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  86764. viewProjection.invertToRef(invViewProjection);
  86765. effect.setMatrix("inverseViewProjection", invViewProjection);
  86766. effect.setMatrix("prevViewProjection", prevViewProjection);
  86767. prevViewProjection = viewProjection;
  86768. screenSize.x = _this.motionBlurPostProcess.width;
  86769. screenSize.y = _this.motionBlurPostProcess.height;
  86770. effect.setVector2("screenSize", screenSize);
  86771. motionScale = scene.getEngine().getFps() / 60.0;
  86772. effect.setFloat("motionScale", motionScale);
  86773. effect.setFloat("motionStrength", _this.motionStrength);
  86774. effect.setTexture("depthSampler", _this._getDepthTexture());
  86775. };
  86776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  86777. };
  86778. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  86779. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  86780. var renderer = this._scene.enableGeometryBufferRenderer();
  86781. return renderer.getGBuffer().textures[0];
  86782. }
  86783. return this._scene.enableDepthRenderer().getDepthMap();
  86784. };
  86785. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  86786. for (var i = 0; i < this._cameras.length; i++) {
  86787. var camera = this._cameras[i];
  86788. if (this.originalPostProcess) {
  86789. this.originalPostProcess.dispose(camera);
  86790. }
  86791. if (this.downSampleX4PostProcess) {
  86792. this.downSampleX4PostProcess.dispose(camera);
  86793. }
  86794. if (this.brightPassPostProcess) {
  86795. this.brightPassPostProcess.dispose(camera);
  86796. }
  86797. if (this.textureAdderPostProcess) {
  86798. this.textureAdderPostProcess.dispose(camera);
  86799. }
  86800. if (this.textureAdderFinalPostProcess) {
  86801. this.textureAdderFinalPostProcess.dispose(camera);
  86802. }
  86803. if (this.volumetricLightPostProcess) {
  86804. this.volumetricLightPostProcess.dispose(camera);
  86805. }
  86806. if (this.volumetricLightSmoothXPostProcess) {
  86807. this.volumetricLightSmoothXPostProcess.dispose(camera);
  86808. }
  86809. if (this.volumetricLightSmoothYPostProcess) {
  86810. this.volumetricLightSmoothYPostProcess.dispose(camera);
  86811. }
  86812. if (this.volumetricLightMergePostProces) {
  86813. this.volumetricLightMergePostProces.dispose(camera);
  86814. }
  86815. if (this.volumetricLightFinalPostProcess) {
  86816. this.volumetricLightFinalPostProcess.dispose(camera);
  86817. }
  86818. if (this.lensFlarePostProcess) {
  86819. this.lensFlarePostProcess.dispose(camera);
  86820. }
  86821. if (this.lensFlareComposePostProcess) {
  86822. this.lensFlareComposePostProcess.dispose(camera);
  86823. }
  86824. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  86825. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  86826. }
  86827. if (this.luminancePostProcess) {
  86828. this.luminancePostProcess.dispose(camera);
  86829. }
  86830. if (this.hdrPostProcess) {
  86831. this.hdrPostProcess.dispose(camera);
  86832. }
  86833. if (this.hdrFinalPostProcess) {
  86834. this.hdrFinalPostProcess.dispose(camera);
  86835. }
  86836. if (this.depthOfFieldPostProcess) {
  86837. this.depthOfFieldPostProcess.dispose(camera);
  86838. }
  86839. if (this.motionBlurPostProcess) {
  86840. this.motionBlurPostProcess.dispose(camera);
  86841. }
  86842. if (this.fxaaPostProcess) {
  86843. this.fxaaPostProcess.dispose(camera);
  86844. }
  86845. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  86846. this.blurHPostProcesses[j].dispose(camera);
  86847. }
  86848. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  86849. this.blurVPostProcesses[j].dispose(camera);
  86850. }
  86851. }
  86852. this.originalPostProcess = null;
  86853. this.downSampleX4PostProcess = null;
  86854. this.brightPassPostProcess = null;
  86855. this.textureAdderPostProcess = null;
  86856. this.textureAdderFinalPostProcess = null;
  86857. this.volumetricLightPostProcess = null;
  86858. this.volumetricLightSmoothXPostProcess = null;
  86859. this.volumetricLightSmoothYPostProcess = null;
  86860. this.volumetricLightMergePostProces = null;
  86861. this.volumetricLightFinalPostProcess = null;
  86862. this.lensFlarePostProcess = null;
  86863. this.lensFlareComposePostProcess = null;
  86864. this.luminancePostProcess = null;
  86865. this.hdrPostProcess = null;
  86866. this.hdrFinalPostProcess = null;
  86867. this.depthOfFieldPostProcess = null;
  86868. this.motionBlurPostProcess = null;
  86869. this.fxaaPostProcess = null;
  86870. this.luminanceDownSamplePostProcesses = [];
  86871. this.blurHPostProcesses = [];
  86872. this.blurVPostProcesses = [];
  86873. };
  86874. /**
  86875. * Dispose of the pipeline and stop all post processes
  86876. */
  86877. StandardRenderingPipeline.prototype.dispose = function () {
  86878. this._disposePostProcesses();
  86879. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86880. _super.prototype.dispose.call(this);
  86881. };
  86882. /**
  86883. * Serialize the rendering pipeline (Used when exporting)
  86884. * @returns the serialized object
  86885. */
  86886. StandardRenderingPipeline.prototype.serialize = function () {
  86887. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86888. if (this.sourceLight) {
  86889. serializationObject.sourceLightId = this.sourceLight.id;
  86890. }
  86891. serializationObject.customType = "StandardRenderingPipeline";
  86892. return serializationObject;
  86893. };
  86894. /**
  86895. * Parse the serialized pipeline
  86896. * @param source Source pipeline.
  86897. * @param scene The scene to load the pipeline to.
  86898. * @param rootUrl The URL of the serialized pipeline.
  86899. * @returns An instantiated pipeline from the serialized object.
  86900. */
  86901. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86902. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86903. if (source.sourceLightId) {
  86904. p.sourceLight = scene.getLightByID(source.sourceLightId);
  86905. }
  86906. return p;
  86907. };
  86908. /**
  86909. * Luminance steps
  86910. */
  86911. StandardRenderingPipeline.LuminanceSteps = 6;
  86912. __decorate([
  86913. BABYLON.serialize()
  86914. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  86915. __decorate([
  86916. BABYLON.serialize()
  86917. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  86918. __decorate([
  86919. BABYLON.serialize()
  86920. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  86921. __decorate([
  86922. BABYLON.serialize()
  86923. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  86924. __decorate([
  86925. BABYLON.serializeAsTexture("lensTexture")
  86926. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  86927. __decorate([
  86928. BABYLON.serialize()
  86929. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  86930. __decorate([
  86931. BABYLON.serialize()
  86932. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  86933. __decorate([
  86934. BABYLON.serialize()
  86935. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  86936. __decorate([
  86937. BABYLON.serialize()
  86938. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  86939. __decorate([
  86940. BABYLON.serialize()
  86941. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  86942. __decorate([
  86943. BABYLON.serialize()
  86944. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  86945. __decorate([
  86946. BABYLON.serializeAsTexture("lensColorTexture")
  86947. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  86948. __decorate([
  86949. BABYLON.serialize()
  86950. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  86951. __decorate([
  86952. BABYLON.serialize()
  86953. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  86954. __decorate([
  86955. BABYLON.serialize()
  86956. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  86957. __decorate([
  86958. BABYLON.serialize()
  86959. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  86960. __decorate([
  86961. BABYLON.serializeAsTexture("lensStarTexture")
  86962. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  86963. __decorate([
  86964. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  86965. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  86966. __decorate([
  86967. BABYLON.serialize()
  86968. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  86969. __decorate([
  86970. BABYLON.serialize()
  86971. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  86972. __decorate([
  86973. BABYLON.serialize()
  86974. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  86975. __decorate([
  86976. BABYLON.serialize()
  86977. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  86978. __decorate([
  86979. BABYLON.serialize()
  86980. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  86981. __decorate([
  86982. BABYLON.serialize()
  86983. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  86984. __decorate([
  86985. BABYLON.serialize()
  86986. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  86987. __decorate([
  86988. BABYLON.serialize()
  86989. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  86990. __decorate([
  86991. BABYLON.serialize()
  86992. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  86993. __decorate([
  86994. BABYLON.serialize()
  86995. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  86996. __decorate([
  86997. BABYLON.serialize()
  86998. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  86999. __decorate([
  87000. BABYLON.serialize()
  87001. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  87002. __decorate([
  87003. BABYLON.serialize()
  87004. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  87005. __decorate([
  87006. BABYLON.serialize()
  87007. ], StandardRenderingPipeline.prototype, "samples", null);
  87008. return StandardRenderingPipeline;
  87009. }(BABYLON.PostProcessRenderPipeline));
  87010. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  87011. })(BABYLON || (BABYLON = {}));
  87012. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  87013. var BABYLON;
  87014. (function (BABYLON) {
  87015. /**
  87016. * Fxaa post process
  87017. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  87018. */
  87019. var FxaaPostProcess = /** @class */ (function (_super) {
  87020. __extends(FxaaPostProcess, _super);
  87021. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87022. if (camera === void 0) { camera = null; }
  87023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87024. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87025. var defines = _this._getDefines();
  87026. _this.updateEffect(defines);
  87027. _this.onApplyObservable.add(function (effect) {
  87028. var texelSize = _this.texelSize;
  87029. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87030. });
  87031. return _this;
  87032. }
  87033. FxaaPostProcess.prototype._getDefines = function () {
  87034. var engine = this.getEngine();
  87035. if (!engine) {
  87036. return null;
  87037. }
  87038. var glInfo = engine.getGlInfo();
  87039. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87040. return "#define MALI 1\n";
  87041. }
  87042. return null;
  87043. };
  87044. return FxaaPostProcess;
  87045. }(BABYLON.PostProcess));
  87046. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. /**
  87052. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87053. */
  87054. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87055. __extends(ChromaticAberrationPostProcess, _super);
  87056. /**
  87057. * Creates a new instance ChromaticAberrationPostProcess
  87058. * @param name The name of the effect.
  87059. * @param screenWidth The width of the screen to apply the effect on.
  87060. * @param screenHeight The height of the screen to apply the effect on.
  87061. * @param options The required width/height ratio to downsize to before computing the render pass.
  87062. * @param camera The camera to apply the render pass to.
  87063. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87064. * @param engine The engine which the post process will be applied. (default: current engine)
  87065. * @param reusable If the post process can be reused on the same frame. (default: false)
  87066. * @param textureType Type of textures used when performing the post process. (default: 0)
  87067. * @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)
  87068. */
  87069. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87070. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87071. if (blockCompilation === void 0) { blockCompilation = false; }
  87072. 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;
  87073. /**
  87074. * The amount of seperation of rgb channels (default: 30)
  87075. */
  87076. _this.aberrationAmount = 30;
  87077. /**
  87078. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87079. */
  87080. _this.radialIntensity = 0;
  87081. /**
  87082. * 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))
  87083. */
  87084. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87085. /**
  87086. * 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))
  87087. */
  87088. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87089. _this.onApplyObservable.add(function (effect) {
  87090. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87091. effect.setFloat('screen_width', screenWidth);
  87092. effect.setFloat('screen_height', screenHeight);
  87093. effect.setFloat('radialIntensity', _this.radialIntensity);
  87094. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87095. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87096. });
  87097. return _this;
  87098. }
  87099. return ChromaticAberrationPostProcess;
  87100. }(BABYLON.PostProcess));
  87101. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87102. })(BABYLON || (BABYLON = {}));
  87103. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  87104. var BABYLON;
  87105. (function (BABYLON) {
  87106. /**
  87107. * The GrainPostProcess adds noise to the image at mid luminance levels
  87108. */
  87109. var GrainPostProcess = /** @class */ (function (_super) {
  87110. __extends(GrainPostProcess, _super);
  87111. /**
  87112. * Creates a new instance of @see GrainPostProcess
  87113. * @param name The name of the effect.
  87114. * @param options The required width/height ratio to downsize to before computing the render pass.
  87115. * @param camera The camera to apply the render pass to.
  87116. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87117. * @param engine The engine which the post process will be applied. (default: current engine)
  87118. * @param reusable If the post process can be reused on the same frame. (default: false)
  87119. * @param textureType Type of textures used when performing the post process. (default: 0)
  87120. * @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)
  87121. */
  87122. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87123. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87124. if (blockCompilation === void 0) { blockCompilation = false; }
  87125. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87126. /**
  87127. * The intensity of the grain added (default: 30)
  87128. */
  87129. _this.intensity = 30;
  87130. /**
  87131. * If the grain should be randomized on every frame
  87132. */
  87133. _this.animated = false;
  87134. _this.onApplyObservable.add(function (effect) {
  87135. effect.setFloat('intensity', _this.intensity);
  87136. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87137. });
  87138. return _this;
  87139. }
  87140. return GrainPostProcess;
  87141. }(BABYLON.PostProcess));
  87142. BABYLON.GrainPostProcess = GrainPostProcess;
  87143. })(BABYLON || (BABYLON = {}));
  87144. //# sourceMappingURL=babylon.grainPostProcess.js.map
  87145. var BABYLON;
  87146. (function (BABYLON) {
  87147. /**
  87148. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87149. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87150. */
  87151. var SharpenPostProcess = /** @class */ (function (_super) {
  87152. __extends(SharpenPostProcess, _super);
  87153. /**
  87154. * Creates a new instance ConvolutionPostProcess
  87155. * @param name The name of the effect.
  87156. * @param options The required width/height ratio to downsize to before computing the render pass.
  87157. * @param camera The camera to apply the render pass to.
  87158. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87159. * @param engine The engine which the post process will be applied. (default: current engine)
  87160. * @param reusable If the post process can be reused on the same frame. (default: false)
  87161. * @param textureType Type of textures used when performing the post process. (default: 0)
  87162. * @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)
  87163. */
  87164. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87166. if (blockCompilation === void 0) { blockCompilation = false; }
  87167. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87168. /**
  87169. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87170. */
  87171. _this.colorAmount = 1.0;
  87172. /**
  87173. * How much sharpness should be applied (default: 0.3)
  87174. */
  87175. _this.edgeAmount = 0.3;
  87176. _this.onApply = function (effect) {
  87177. effect.setFloat2("screenSize", _this.width, _this.height);
  87178. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87179. };
  87180. return _this;
  87181. }
  87182. return SharpenPostProcess;
  87183. }(BABYLON.PostProcess));
  87184. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87185. })(BABYLON || (BABYLON = {}));
  87186. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  87187. var BABYLON;
  87188. (function (BABYLON) {
  87189. /**
  87190. * The Blur Post Process which blurs an image based on a kernel and direction.
  87191. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87192. */
  87193. var BlurPostProcess = /** @class */ (function (_super) {
  87194. __extends(BlurPostProcess, _super);
  87195. /**
  87196. * Creates a new instance BlurPostProcess
  87197. * @param name The name of the effect.
  87198. * @param direction The direction in which to blur the image.
  87199. * @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.
  87200. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87201. * @param camera The camera to apply the render pass to.
  87202. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87203. * @param engine The engine which the post process will be applied. (default: current engine)
  87204. * @param reusable If the post process can be reused on the same frame. (default: false)
  87205. * @param textureType Type of textures used when performing the post process. (default: 0)
  87206. * @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)
  87207. */
  87208. function BlurPostProcess(name,
  87209. /** The direction in which to blur the image. */
  87210. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87212. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87213. if (defines === void 0) { defines = ""; }
  87214. if (blockCompilation === void 0) { blockCompilation = false; }
  87215. 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;
  87216. _this.direction = direction;
  87217. _this.blockCompilation = blockCompilation;
  87218. _this._packedFloat = false;
  87219. _this._staticDefines = "";
  87220. _this._staticDefines = defines;
  87221. _this.onApplyObservable.add(function (effect) {
  87222. if (_this._outputTexture) {
  87223. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87224. }
  87225. else {
  87226. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87227. }
  87228. });
  87229. _this.kernel = kernel;
  87230. return _this;
  87231. }
  87232. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87233. /**
  87234. * Gets the length in pixels of the blur sample region
  87235. */
  87236. get: function () {
  87237. return this._idealKernel;
  87238. },
  87239. /**
  87240. * Sets the length in pixels of the blur sample region
  87241. */
  87242. set: function (v) {
  87243. if (this._idealKernel === v) {
  87244. return;
  87245. }
  87246. v = Math.max(v, 1);
  87247. this._idealKernel = v;
  87248. this._kernel = this._nearestBestKernel(v);
  87249. if (!this.blockCompilation) {
  87250. this._updateParameters();
  87251. }
  87252. },
  87253. enumerable: true,
  87254. configurable: true
  87255. });
  87256. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87257. /**
  87258. * Gets wether or not the blur is unpacking/repacking floats
  87259. */
  87260. get: function () {
  87261. return this._packedFloat;
  87262. },
  87263. /**
  87264. * Sets wether or not the blur needs to unpack/repack floats
  87265. */
  87266. set: function (v) {
  87267. if (this._packedFloat === v) {
  87268. return;
  87269. }
  87270. this._packedFloat = v;
  87271. if (!this.blockCompilation) {
  87272. this._updateParameters();
  87273. }
  87274. },
  87275. enumerable: true,
  87276. configurable: true
  87277. });
  87278. /**
  87279. * Updates the effect with the current post process compile time values and recompiles the shader.
  87280. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87281. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87282. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87283. * @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
  87284. * @param onCompiled Called when the shader has been compiled.
  87285. * @param onError Called if there is an error when compiling a shader.
  87286. */
  87287. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87288. if (defines === void 0) { defines = null; }
  87289. if (uniforms === void 0) { uniforms = null; }
  87290. if (samplers === void 0) { samplers = null; }
  87291. this._updateParameters(onCompiled, onError);
  87292. };
  87293. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87294. // Generate sampling offsets and weights
  87295. var N = this._kernel;
  87296. var centerIndex = (N - 1) / 2;
  87297. // Generate Gaussian sampling weights over kernel
  87298. var offsets = [];
  87299. var weights = [];
  87300. var totalWeight = 0;
  87301. for (var i = 0; i < N; i++) {
  87302. var u = i / (N - 1);
  87303. var w = this._gaussianWeight(u * 2.0 - 1);
  87304. offsets[i] = (i - centerIndex);
  87305. weights[i] = w;
  87306. totalWeight += w;
  87307. }
  87308. // Normalize weights
  87309. for (var i = 0; i < weights.length; i++) {
  87310. weights[i] /= totalWeight;
  87311. }
  87312. // Optimize: combine samples to take advantage of hardware linear sampling
  87313. // Walk from left to center, combining pairs (symmetrically)
  87314. var linearSamplingWeights = [];
  87315. var linearSamplingOffsets = [];
  87316. var linearSamplingMap = [];
  87317. for (var i = 0; i <= centerIndex; i += 2) {
  87318. var j = Math.min(i + 1, Math.floor(centerIndex));
  87319. var singleCenterSample = i === j;
  87320. if (singleCenterSample) {
  87321. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87322. }
  87323. else {
  87324. var sharedCell = j === centerIndex;
  87325. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87326. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87327. if (offsetLinear === 0) {
  87328. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87329. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87330. }
  87331. else {
  87332. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87333. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87334. }
  87335. }
  87336. }
  87337. for (var i = 0; i < linearSamplingMap.length; i++) {
  87338. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87339. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87340. }
  87341. // Replace with optimized
  87342. offsets = linearSamplingOffsets;
  87343. weights = linearSamplingWeights;
  87344. // Generate shaders
  87345. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87346. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87347. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87348. var defines = "";
  87349. defines += this._staticDefines;
  87350. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87351. if (this._staticDefines.indexOf("DOF") != -1) {
  87352. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87353. varyingCount--;
  87354. }
  87355. for (var i = 0; i < varyingCount; i++) {
  87356. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87357. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87358. }
  87359. var depCount = 0;
  87360. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87361. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87362. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87363. depCount++;
  87364. }
  87365. if (this.packedFloat) {
  87366. defines += "#define PACKEDFLOAT 1";
  87367. }
  87368. this.blockCompilation = false;
  87369. _super.prototype.updateEffect.call(this, defines, null, null, {
  87370. varyingCount: varyingCount,
  87371. depCount: depCount
  87372. }, onCompiled, onError);
  87373. };
  87374. /**
  87375. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87376. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87377. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87378. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87379. * The gaps between physical kernels are compensated for in the weighting of the samples
  87380. * @param idealKernel Ideal blur kernel.
  87381. * @return Nearest best kernel.
  87382. */
  87383. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87384. var v = Math.round(idealKernel);
  87385. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87386. var k = _a[_i];
  87387. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87388. return Math.max(k, 3);
  87389. }
  87390. }
  87391. return Math.max(v, 3);
  87392. };
  87393. /**
  87394. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87395. * @param x The point on the Gaussian distribution to sample.
  87396. * @return the value of the Gaussian function at x.
  87397. */
  87398. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87399. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87400. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87401. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87402. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87403. // truncated at around 1.3% of peak strength.
  87404. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87405. var sigma = (1 / 3);
  87406. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87407. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87408. var weight = (1.0 / denominator) * Math.exp(exponent);
  87409. return weight;
  87410. };
  87411. /**
  87412. * Generates a string that can be used as a floating point number in GLSL.
  87413. * @param x Value to print.
  87414. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87415. * @return GLSL float string.
  87416. */
  87417. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87418. if (decimalFigures === void 0) { decimalFigures = 8; }
  87419. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87420. };
  87421. return BlurPostProcess;
  87422. }(BABYLON.PostProcess));
  87423. BABYLON.BlurPostProcess = BlurPostProcess;
  87424. })(BABYLON || (BABYLON = {}));
  87425. //# sourceMappingURL=babylon.blurPostProcess.js.map
  87426. var BABYLON;
  87427. (function (BABYLON) {
  87428. /**
  87429. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  87430. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  87431. * based on samples that have a large difference in distance than the center pixel.
  87432. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87433. */
  87434. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  87435. __extends(DepthOfFieldBlurPostProcess, _super);
  87436. /**
  87437. * Creates a new instance CircleOfConfusionPostProcess
  87438. * @param name The name of the effect.
  87439. * @param scene The scene the effect belongs to.
  87440. * @param direction The direction the blur should be applied.
  87441. * @param kernel The size of the kernel used to blur.
  87442. * @param options The required width/height ratio to downsize to before computing the render pass.
  87443. * @param camera The camera to apply the render pass to.
  87444. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  87445. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  87446. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87447. * @param engine The engine which the post process will be applied. (default: current engine)
  87448. * @param reusable If the post process can be reused on the same frame. (default: false)
  87449. * @param textureType Type of textures used when performing the post process. (default: 0)
  87450. * @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)
  87451. */
  87452. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  87453. if (imageToBlur === void 0) { imageToBlur = null; }
  87454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87455. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87456. if (blockCompilation === void 0) { blockCompilation = false; }
  87457. 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;
  87458. _this.direction = direction;
  87459. _this.onApplyObservable.add(function (effect) {
  87460. if (imageToBlur != null) {
  87461. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  87462. }
  87463. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87464. if (scene.activeCamera) {
  87465. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87466. }
  87467. });
  87468. return _this;
  87469. }
  87470. return DepthOfFieldBlurPostProcess;
  87471. }(BABYLON.BlurPostProcess));
  87472. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  87473. })(BABYLON || (BABYLON = {}));
  87474. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  87475. var BABYLON;
  87476. (function (BABYLON) {
  87477. /**
  87478. * Options to be set when merging outputs from the default pipeline.
  87479. */
  87480. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  87481. function DepthOfFieldMergePostProcessOptions() {
  87482. }
  87483. return DepthOfFieldMergePostProcessOptions;
  87484. }());
  87485. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  87486. /**
  87487. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87488. */
  87489. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  87490. __extends(DepthOfFieldMergePostProcess, _super);
  87491. /**
  87492. * Creates a new instance of DepthOfFieldMergePostProcess
  87493. * @param name The name of the effect.
  87494. * @param originalFromInput Post process which's input will be used for the merge.
  87495. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  87496. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  87497. * @param options The required width/height ratio to downsize to before computing the render pass.
  87498. * @param camera The camera to apply the render pass to.
  87499. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87500. * @param engine The engine which the post process will be applied. (default: current engine)
  87501. * @param reusable If the post process can be reused on the same frame. (default: false)
  87502. * @param textureType Type of textures used when performing the post process. (default: 0)
  87503. * @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)
  87504. */
  87505. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87506. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87507. if (blockCompilation === void 0) { blockCompilation = false; }
  87508. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87509. _this.blurSteps = blurSteps;
  87510. _this.onApplyObservable.add(function (effect) {
  87511. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87512. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87513. blurSteps.forEach(function (step, index) {
  87514. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  87515. });
  87516. });
  87517. if (!blockCompilation) {
  87518. _this.updateEffect();
  87519. }
  87520. return _this;
  87521. }
  87522. /**
  87523. * Updates the effect with the current post process compile time values and recompiles the shader.
  87524. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87525. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87526. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87527. * @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
  87528. * @param onCompiled Called when the shader has been compiled.
  87529. * @param onError Called if there is an error when compiling a shader.
  87530. */
  87531. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87532. if (defines === void 0) { defines = null; }
  87533. if (uniforms === void 0) { uniforms = null; }
  87534. if (samplers === void 0) { samplers = null; }
  87535. if (!defines) {
  87536. defines = "";
  87537. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  87538. }
  87539. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  87540. };
  87541. return DepthOfFieldMergePostProcess;
  87542. }(BABYLON.PostProcess));
  87543. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  87544. })(BABYLON || (BABYLON = {}));
  87545. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  87546. var BABYLON;
  87547. (function (BABYLON) {
  87548. /**
  87549. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  87550. */
  87551. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  87552. __extends(CircleOfConfusionPostProcess, _super);
  87553. /**
  87554. * Creates a new instance CircleOfConfusionPostProcess
  87555. * @param name The name of the effect.
  87556. * @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.
  87557. * @param options The required width/height ratio to downsize to before computing the render pass.
  87558. * @param camera The camera to apply the render pass to.
  87559. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87560. * @param engine The engine which the post process will be applied. (default: current engine)
  87561. * @param reusable If the post process can be reused on the same frame. (default: false)
  87562. * @param textureType Type of textures used when performing the post process. (default: 0)
  87563. * @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)
  87564. */
  87565. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87566. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87567. if (blockCompilation === void 0) { blockCompilation = false; }
  87568. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87569. /**
  87570. * 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.
  87571. */
  87572. _this.lensSize = 50;
  87573. /**
  87574. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87575. */
  87576. _this.fStop = 1.4;
  87577. /**
  87578. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87579. */
  87580. _this.focusDistance = 2000;
  87581. /**
  87582. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  87583. */
  87584. _this.focalLength = 50;
  87585. _this._depthTexture = null;
  87586. _this._depthTexture = depthTexture;
  87587. _this.onApplyObservable.add(function (effect) {
  87588. if (!_this._depthTexture) {
  87589. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  87590. return;
  87591. }
  87592. effect.setTexture("depthSampler", _this._depthTexture);
  87593. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  87594. var aperture = _this.lensSize / _this.fStop;
  87595. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  87596. effect.setFloat('focusDistance', _this.focusDistance);
  87597. effect.setFloat('cocPrecalculation', cocPrecalculation);
  87598. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  87599. });
  87600. return _this;
  87601. }
  87602. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  87603. /**
  87604. * 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.
  87605. */
  87606. set: function (value) {
  87607. this._depthTexture = value;
  87608. },
  87609. enumerable: true,
  87610. configurable: true
  87611. });
  87612. return CircleOfConfusionPostProcess;
  87613. }(BABYLON.PostProcess));
  87614. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  87615. })(BABYLON || (BABYLON = {}));
  87616. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  87617. var BABYLON;
  87618. (function (BABYLON) {
  87619. /**
  87620. * Specifies the level of max blur that should be applied when using the depth of field effect
  87621. */
  87622. var DepthOfFieldEffectBlurLevel;
  87623. (function (DepthOfFieldEffectBlurLevel) {
  87624. /**
  87625. * Subtle blur
  87626. */
  87627. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  87628. /**
  87629. * Medium blur
  87630. */
  87631. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  87632. /**
  87633. * Large blur
  87634. */
  87635. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  87636. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  87637. /**
  87638. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  87639. */
  87640. var DepthOfFieldEffect = /** @class */ (function (_super) {
  87641. __extends(DepthOfFieldEffect, _super);
  87642. /**
  87643. * Creates a new instance DepthOfFieldEffect
  87644. * @param scene The scene the effect belongs to.
  87645. * @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.
  87646. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87647. * @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)
  87648. */
  87649. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  87650. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  87651. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87652. if (blockCompilation === void 0) { blockCompilation = false; }
  87653. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  87654. return _this._effects;
  87655. }, true) || this;
  87656. /**
  87657. * @hidden Internal post processes in depth of field effect
  87658. */
  87659. _this._effects = [];
  87660. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  87661. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87662. // 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)
  87663. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  87664. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87665. _this._depthOfFieldBlurY = [];
  87666. _this._depthOfFieldBlurX = [];
  87667. var blurCount = 1;
  87668. var kernelSize = 15;
  87669. switch (blurLevel) {
  87670. case DepthOfFieldEffectBlurLevel.High: {
  87671. blurCount = 3;
  87672. kernelSize = 51;
  87673. break;
  87674. }
  87675. case DepthOfFieldEffectBlurLevel.Medium: {
  87676. blurCount = 2;
  87677. kernelSize = 31;
  87678. break;
  87679. }
  87680. default: {
  87681. kernelSize = 15;
  87682. blurCount = 1;
  87683. break;
  87684. }
  87685. }
  87686. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  87687. var ratio = 1.0;
  87688. for (var i = 0; i < blurCount; i++) {
  87689. 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);
  87690. blurY.autoClear = false;
  87691. ratio = 0.75 / Math.pow(2, i);
  87692. 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);
  87693. blurX.autoClear = false;
  87694. _this._depthOfFieldBlurY.push(blurY);
  87695. _this._depthOfFieldBlurX.push(blurX);
  87696. }
  87697. // Set all post processes on the effect.
  87698. _this._effects = [_this._circleOfConfusion];
  87699. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  87700. _this._effects.push(_this._depthOfFieldBlurY[i]);
  87701. _this._effects.push(_this._depthOfFieldBlurX[i]);
  87702. }
  87703. // Merge blurred images with original image based on circleOfConfusion
  87704. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87705. _this._dofMerge.autoClear = false;
  87706. _this._effects.push(_this._dofMerge);
  87707. return _this;
  87708. }
  87709. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  87710. get: function () {
  87711. return this._circleOfConfusion.focalLength;
  87712. },
  87713. /**
  87714. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  87715. */
  87716. set: function (value) {
  87717. this._circleOfConfusion.focalLength = value;
  87718. },
  87719. enumerable: true,
  87720. configurable: true
  87721. });
  87722. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  87723. get: function () {
  87724. return this._circleOfConfusion.fStop;
  87725. },
  87726. /**
  87727. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87728. */
  87729. set: function (value) {
  87730. this._circleOfConfusion.fStop = value;
  87731. },
  87732. enumerable: true,
  87733. configurable: true
  87734. });
  87735. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  87736. get: function () {
  87737. return this._circleOfConfusion.focusDistance;
  87738. },
  87739. /**
  87740. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87741. */
  87742. set: function (value) {
  87743. this._circleOfConfusion.focusDistance = value;
  87744. },
  87745. enumerable: true,
  87746. configurable: true
  87747. });
  87748. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  87749. get: function () {
  87750. return this._circleOfConfusion.lensSize;
  87751. },
  87752. /**
  87753. * 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.
  87754. */
  87755. set: function (value) {
  87756. this._circleOfConfusion.lensSize = value;
  87757. },
  87758. enumerable: true,
  87759. configurable: true
  87760. });
  87761. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  87762. /**
  87763. * 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.
  87764. */
  87765. set: function (value) {
  87766. this._circleOfConfusion.depthTexture = value;
  87767. },
  87768. enumerable: true,
  87769. configurable: true
  87770. });
  87771. /**
  87772. * Disposes each of the internal effects for a given camera.
  87773. * @param camera The camera to dispose the effect on.
  87774. */
  87775. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  87776. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87777. this._effects[effectIndex].dispose(camera);
  87778. }
  87779. };
  87780. /**
  87781. * @hidden Internal
  87782. */
  87783. DepthOfFieldEffect.prototype._updateEffects = function () {
  87784. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87785. this._effects[effectIndex].updateEffect();
  87786. }
  87787. };
  87788. /**
  87789. * Internal
  87790. * @returns if all the contained post processes are ready.
  87791. * @hidden
  87792. */
  87793. DepthOfFieldEffect.prototype._isReady = function () {
  87794. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87795. if (!this._effects[effectIndex].isReady()) {
  87796. return false;
  87797. }
  87798. }
  87799. return true;
  87800. };
  87801. return DepthOfFieldEffect;
  87802. }(BABYLON.PostProcessRenderEffect));
  87803. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  87804. })(BABYLON || (BABYLON = {}));
  87805. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  87806. var BABYLON;
  87807. (function (BABYLON) {
  87808. /**
  87809. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87810. */
  87811. var BloomMergePostProcess = /** @class */ (function (_super) {
  87812. __extends(BloomMergePostProcess, _super);
  87813. /**
  87814. * Creates a new instance of @see BloomMergePostProcess
  87815. * @param name The name of the effect.
  87816. * @param originalFromInput Post process which's input will be used for the merge.
  87817. * @param blurred Blurred highlights post process which's output will be used.
  87818. * @param weight Weight of the bloom to be added to the original input.
  87819. * @param options The required width/height ratio to downsize to before computing the render pass.
  87820. * @param camera The camera to apply the render pass to.
  87821. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87822. * @param engine The engine which the post process will be applied. (default: current engine)
  87823. * @param reusable If the post process can be reused on the same frame. (default: false)
  87824. * @param textureType Type of textures used when performing the post process. (default: 0)
  87825. * @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)
  87826. */
  87827. function BloomMergePostProcess(name, originalFromInput, blurred,
  87828. /** Weight of the bloom to be added to the original input. */
  87829. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87830. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87831. if (blockCompilation === void 0) { blockCompilation = false; }
  87832. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87833. _this.weight = weight;
  87834. _this.onApplyObservable.add(function (effect) {
  87835. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87836. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  87837. effect.setFloat("bloomWeight", _this.weight);
  87838. });
  87839. if (!blockCompilation) {
  87840. _this.updateEffect();
  87841. }
  87842. return _this;
  87843. }
  87844. return BloomMergePostProcess;
  87845. }(BABYLON.PostProcess));
  87846. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  87847. })(BABYLON || (BABYLON = {}));
  87848. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  87849. var BABYLON;
  87850. (function (BABYLON) {
  87851. /**
  87852. * 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.
  87853. */
  87854. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  87855. __extends(ExtractHighlightsPostProcess, _super);
  87856. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87857. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87858. if (blockCompilation === void 0) { blockCompilation = false; }
  87859. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87860. /**
  87861. * The luminance threshold, pixels below this value will be set to black.
  87862. */
  87863. _this.threshold = 0.9;
  87864. /** @hidden */
  87865. _this._exposure = 1;
  87866. /**
  87867. * Post process which has the input texture to be used when performing highlight extraction
  87868. * @hidden
  87869. */
  87870. _this._inputPostProcess = null;
  87871. _this.onApplyObservable.add(function (effect) {
  87872. if (_this._inputPostProcess) {
  87873. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  87874. }
  87875. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  87876. effect.setFloat('exposure', _this._exposure);
  87877. });
  87878. return _this;
  87879. }
  87880. return ExtractHighlightsPostProcess;
  87881. }(BABYLON.PostProcess));
  87882. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  87883. })(BABYLON || (BABYLON = {}));
  87884. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  87885. var BABYLON;
  87886. (function (BABYLON) {
  87887. /**
  87888. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  87889. */
  87890. var BloomEffect = /** @class */ (function (_super) {
  87891. __extends(BloomEffect, _super);
  87892. /**
  87893. * Creates a new instance of @see BloomEffect
  87894. * @param scene The scene the effect belongs to.
  87895. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  87896. * @param bloomKernel The size of the kernel to be used when applying the blur.
  87897. * @param bloomWeight The the strength of bloom.
  87898. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87899. * @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)
  87900. */
  87901. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  87902. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87903. if (blockCompilation === void 0) { blockCompilation = false; }
  87904. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  87905. return _this._effects;
  87906. }, true) || this;
  87907. _this.bloomScale = bloomScale;
  87908. /**
  87909. * @hidden Internal
  87910. */
  87911. _this._effects = [];
  87912. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87913. _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);
  87914. _this._blurX.alwaysForcePOT = true;
  87915. _this._blurX.autoClear = false;
  87916. _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);
  87917. _this._blurY.alwaysForcePOT = true;
  87918. _this._blurY.autoClear = false;
  87919. _this.kernel = bloomKernel;
  87920. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  87921. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87922. _this._merge.autoClear = false;
  87923. _this._effects.push(_this._merge);
  87924. return _this;
  87925. }
  87926. Object.defineProperty(BloomEffect.prototype, "threshold", {
  87927. /**
  87928. * The luminance threshold to find bright areas of the image to bloom.
  87929. */
  87930. get: function () {
  87931. return this._downscale.threshold;
  87932. },
  87933. set: function (value) {
  87934. this._downscale.threshold = value;
  87935. },
  87936. enumerable: true,
  87937. configurable: true
  87938. });
  87939. Object.defineProperty(BloomEffect.prototype, "weight", {
  87940. /**
  87941. * The strength of the bloom.
  87942. */
  87943. get: function () {
  87944. return this._merge.weight;
  87945. },
  87946. set: function (value) {
  87947. this._merge.weight = value;
  87948. },
  87949. enumerable: true,
  87950. configurable: true
  87951. });
  87952. Object.defineProperty(BloomEffect.prototype, "kernel", {
  87953. /**
  87954. * Specifies the size of the bloom blur kernel, relative to the final output size
  87955. */
  87956. get: function () {
  87957. return this._blurX.kernel / this.bloomScale;
  87958. },
  87959. set: function (value) {
  87960. this._blurX.kernel = value * this.bloomScale;
  87961. this._blurY.kernel = value * this.bloomScale;
  87962. },
  87963. enumerable: true,
  87964. configurable: true
  87965. });
  87966. /**
  87967. * Disposes each of the internal effects for a given camera.
  87968. * @param camera The camera to dispose the effect on.
  87969. */
  87970. BloomEffect.prototype.disposeEffects = function (camera) {
  87971. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87972. this._effects[effectIndex].dispose(camera);
  87973. }
  87974. };
  87975. /**
  87976. * @hidden Internal
  87977. */
  87978. BloomEffect.prototype._updateEffects = function () {
  87979. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87980. this._effects[effectIndex].updateEffect();
  87981. }
  87982. };
  87983. /**
  87984. * Internal
  87985. * @returns if all the contained post processes are ready.
  87986. * @hidden
  87987. */
  87988. BloomEffect.prototype._isReady = function () {
  87989. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87990. if (!this._effects[effectIndex].isReady()) {
  87991. return false;
  87992. }
  87993. }
  87994. return true;
  87995. };
  87996. return BloomEffect;
  87997. }(BABYLON.PostProcessRenderEffect));
  87998. BABYLON.BloomEffect = BloomEffect;
  87999. })(BABYLON || (BABYLON = {}));
  88000. //# sourceMappingURL=babylon.bloomEffect.js.map
  88001. var BABYLON;
  88002. (function (BABYLON) {
  88003. /**
  88004. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  88005. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  88006. */
  88007. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  88008. __extends(DefaultRenderingPipeline, _super);
  88009. /**
  88010. * @constructor
  88011. * @param name - The rendering pipeline name (default: "")
  88012. * @param hdr - If high dynamic range textures should be used (default: true)
  88013. * @param scene - The scene linked to this pipeline (default: the last created scene)
  88014. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  88015. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  88016. */
  88017. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  88018. if (name === void 0) { name = ""; }
  88019. if (hdr === void 0) { hdr = true; }
  88020. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  88021. if (automaticBuild === void 0) { automaticBuild = true; }
  88022. var _this = _super.call(this, scene.getEngine(), name) || this;
  88023. _this._camerasToBeAttached = [];
  88024. /**
  88025. * ID of the sharpen post process,
  88026. */
  88027. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88028. /**
  88029. * @ignore
  88030. * ID of the image processing post process;
  88031. */
  88032. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88033. /**
  88034. * @ignore
  88035. * ID of the Fast Approximate Anti-Aliasing post process;
  88036. */
  88037. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88038. /**
  88039. * ID of the chromatic aberration post process,
  88040. */
  88041. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88042. /**
  88043. * ID of the grain post process
  88044. */
  88045. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88046. /**
  88047. * Glow post process which adds a glow to emmisive areas of the image
  88048. */
  88049. _this._glowLayer = null;
  88050. /**
  88051. * Animations which can be used to tweak settings over a period of time
  88052. */
  88053. _this.animations = [];
  88054. _this._imageProcessingConfigurationObserver = null;
  88055. // Values
  88056. _this._sharpenEnabled = false;
  88057. _this._bloomEnabled = false;
  88058. _this._depthOfFieldEnabled = false;
  88059. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88060. _this._fxaaEnabled = false;
  88061. _this._imageProcessingEnabled = true;
  88062. _this._bloomScale = 0.5;
  88063. _this._chromaticAberrationEnabled = false;
  88064. _this._grainEnabled = false;
  88065. _this._buildAllowed = true;
  88066. _this._resizeObserver = null;
  88067. _this._hardwareScaleLevel = 1.0;
  88068. _this._bloomKernel = 64;
  88069. /**
  88070. * Specifies the weight of the bloom in the final rendering
  88071. */
  88072. _this._bloomWeight = 0.15;
  88073. /**
  88074. * Specifies the luma threshold for the area that will be blurred by the bloom
  88075. */
  88076. _this._bloomThreshold = 0.9;
  88077. _this._samples = 1;
  88078. _this._hasCleared = false;
  88079. _this._prevPostProcess = null;
  88080. _this._prevPrevPostProcess = null;
  88081. _this._depthOfFieldSceneObserver = null;
  88082. _this._cameras = cameras || scene.cameras;
  88083. _this._cameras = _this._cameras.slice();
  88084. _this._camerasToBeAttached = _this._cameras.slice();
  88085. _this._buildAllowed = automaticBuild;
  88086. // Initialize
  88087. _this._scene = scene;
  88088. var caps = _this._scene.getEngine().getCaps();
  88089. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88090. // Misc
  88091. if (_this._hdr) {
  88092. if (caps.textureHalfFloatRender) {
  88093. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88094. }
  88095. else if (caps.textureFloatRender) {
  88096. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88097. }
  88098. }
  88099. else {
  88100. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88101. }
  88102. // Attach
  88103. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88104. var engine = _this._scene.getEngine();
  88105. // Create post processes before hand so they can be modified before enabled.
  88106. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88107. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88108. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88109. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88110. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88111. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88112. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88113. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88114. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88115. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88116. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88117. _this.bloomKernel = _this.bloomKernel;
  88118. });
  88119. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88120. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88121. });
  88122. _this._buildPipeline();
  88123. return _this;
  88124. }
  88125. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88126. get: function () {
  88127. return this._sharpenEnabled;
  88128. },
  88129. /**
  88130. * Enable or disable the sharpen process from the pipeline
  88131. */
  88132. set: function (enabled) {
  88133. if (this._sharpenEnabled === enabled) {
  88134. return;
  88135. }
  88136. this._sharpenEnabled = enabled;
  88137. this._buildPipeline();
  88138. },
  88139. enumerable: true,
  88140. configurable: true
  88141. });
  88142. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88143. /**
  88144. * Specifies the size of the bloom blur kernel, relative to the final output size
  88145. */
  88146. get: function () {
  88147. return this._bloomKernel;
  88148. },
  88149. set: function (value) {
  88150. this._bloomKernel = value;
  88151. this.bloom.kernel = value / this._hardwareScaleLevel;
  88152. },
  88153. enumerable: true,
  88154. configurable: true
  88155. });
  88156. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88157. get: function () {
  88158. return this._bloomWeight;
  88159. },
  88160. /**
  88161. * The strength of the bloom.
  88162. */
  88163. set: function (value) {
  88164. if (this._bloomWeight === value) {
  88165. return;
  88166. }
  88167. this.bloom.weight = value;
  88168. this._bloomWeight = value;
  88169. },
  88170. enumerable: true,
  88171. configurable: true
  88172. });
  88173. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88174. get: function () {
  88175. return this._bloomThreshold;
  88176. },
  88177. /**
  88178. * The strength of the bloom.
  88179. */
  88180. set: function (value) {
  88181. if (this._bloomThreshold === value) {
  88182. return;
  88183. }
  88184. this.bloom.threshold = value;
  88185. this._bloomThreshold = value;
  88186. },
  88187. enumerable: true,
  88188. configurable: true
  88189. });
  88190. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88191. get: function () {
  88192. return this._bloomScale;
  88193. },
  88194. /**
  88195. * The scale of the bloom, lower value will provide better performance.
  88196. */
  88197. set: function (value) {
  88198. if (this._bloomScale === value) {
  88199. return;
  88200. }
  88201. this._bloomScale = value;
  88202. // recreate bloom and dispose old as this setting is not dynamic
  88203. this._rebuildBloom();
  88204. this._buildPipeline();
  88205. },
  88206. enumerable: true,
  88207. configurable: true
  88208. });
  88209. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88210. get: function () {
  88211. return this._bloomEnabled;
  88212. },
  88213. /**
  88214. * Enable or disable the bloom from the pipeline
  88215. */
  88216. set: function (enabled) {
  88217. if (this._bloomEnabled === enabled) {
  88218. return;
  88219. }
  88220. this._bloomEnabled = enabled;
  88221. this._buildPipeline();
  88222. },
  88223. enumerable: true,
  88224. configurable: true
  88225. });
  88226. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88227. // recreate bloom and dispose old as this setting is not dynamic
  88228. var oldBloom = this.bloom;
  88229. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88230. this.bloom.threshold = oldBloom.threshold;
  88231. for (var i = 0; i < this._cameras.length; i++) {
  88232. oldBloom.disposeEffects(this._cameras[i]);
  88233. }
  88234. };
  88235. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88236. /**
  88237. * If the depth of field is enabled.
  88238. */
  88239. get: function () {
  88240. return this._depthOfFieldEnabled;
  88241. },
  88242. set: function (enabled) {
  88243. if (this._depthOfFieldEnabled === enabled) {
  88244. return;
  88245. }
  88246. this._depthOfFieldEnabled = enabled;
  88247. this._buildPipeline();
  88248. },
  88249. enumerable: true,
  88250. configurable: true
  88251. });
  88252. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88253. /**
  88254. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88255. */
  88256. get: function () {
  88257. return this._depthOfFieldBlurLevel;
  88258. },
  88259. set: function (value) {
  88260. if (this._depthOfFieldBlurLevel === value) {
  88261. return;
  88262. }
  88263. this._depthOfFieldBlurLevel = value;
  88264. // recreate dof and dispose old as this setting is not dynamic
  88265. var oldDof = this.depthOfField;
  88266. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88267. this.depthOfField.focalLength = oldDof.focalLength;
  88268. this.depthOfField.focusDistance = oldDof.focusDistance;
  88269. this.depthOfField.fStop = oldDof.fStop;
  88270. this.depthOfField.lensSize = oldDof.lensSize;
  88271. for (var i = 0; i < this._cameras.length; i++) {
  88272. oldDof.disposeEffects(this._cameras[i]);
  88273. }
  88274. this._buildPipeline();
  88275. },
  88276. enumerable: true,
  88277. configurable: true
  88278. });
  88279. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88280. get: function () {
  88281. return this._fxaaEnabled;
  88282. },
  88283. /**
  88284. * If the anti aliasing is enabled.
  88285. */
  88286. set: function (enabled) {
  88287. if (this._fxaaEnabled === enabled) {
  88288. return;
  88289. }
  88290. this._fxaaEnabled = enabled;
  88291. this._buildPipeline();
  88292. },
  88293. enumerable: true,
  88294. configurable: true
  88295. });
  88296. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88297. get: function () {
  88298. return this._samples;
  88299. },
  88300. /**
  88301. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88302. */
  88303. set: function (sampleCount) {
  88304. if (this._samples === sampleCount) {
  88305. return;
  88306. }
  88307. this._samples = sampleCount;
  88308. this._buildPipeline();
  88309. },
  88310. enumerable: true,
  88311. configurable: true
  88312. });
  88313. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88314. get: function () {
  88315. return this._imageProcessingEnabled;
  88316. },
  88317. /**
  88318. * If image processing is enabled.
  88319. */
  88320. set: function (enabled) {
  88321. if (this._imageProcessingEnabled === enabled) {
  88322. return;
  88323. }
  88324. this._imageProcessingEnabled = enabled;
  88325. this._buildPipeline();
  88326. },
  88327. enumerable: true,
  88328. configurable: true
  88329. });
  88330. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88331. get: function () {
  88332. return this._glowLayer == null;
  88333. },
  88334. /**
  88335. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88336. */
  88337. set: function (enabled) {
  88338. if (enabled && !this._glowLayer) {
  88339. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88340. }
  88341. else if (!enabled && this._glowLayer) {
  88342. this._glowLayer.dispose();
  88343. this._glowLayer = null;
  88344. }
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88350. get: function () {
  88351. return this._chromaticAberrationEnabled;
  88352. },
  88353. /**
  88354. * Enable or disable the chromaticAberration process from the pipeline
  88355. */
  88356. set: function (enabled) {
  88357. if (this._chromaticAberrationEnabled === enabled) {
  88358. return;
  88359. }
  88360. this._chromaticAberrationEnabled = enabled;
  88361. this._buildPipeline();
  88362. },
  88363. enumerable: true,
  88364. configurable: true
  88365. });
  88366. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88367. get: function () {
  88368. return this._grainEnabled;
  88369. },
  88370. /**
  88371. * Enable or disable the grain process from the pipeline
  88372. */
  88373. set: function (enabled) {
  88374. if (this._grainEnabled === enabled) {
  88375. return;
  88376. }
  88377. this._grainEnabled = enabled;
  88378. this._buildPipeline();
  88379. },
  88380. enumerable: true,
  88381. configurable: true
  88382. });
  88383. /**
  88384. * Force the compilation of the entire pipeline.
  88385. */
  88386. DefaultRenderingPipeline.prototype.prepare = function () {
  88387. var previousState = this._buildAllowed;
  88388. this._buildAllowed = true;
  88389. this._buildPipeline();
  88390. this._buildAllowed = previousState;
  88391. };
  88392. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88393. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88394. if (this._hasCleared) {
  88395. postProcess.autoClear = false;
  88396. }
  88397. else {
  88398. postProcess.autoClear = true;
  88399. this._scene.autoClear = false;
  88400. this._hasCleared = true;
  88401. }
  88402. if (!skipTextureSharing) {
  88403. if (this._prevPrevPostProcess) {
  88404. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88405. }
  88406. else {
  88407. postProcess.useOwnOutput();
  88408. }
  88409. if (this._prevPostProcess) {
  88410. this._prevPrevPostProcess = this._prevPostProcess;
  88411. }
  88412. this._prevPostProcess = postProcess;
  88413. }
  88414. };
  88415. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88416. var _this = this;
  88417. if (!this._buildAllowed) {
  88418. return;
  88419. }
  88420. this._scene.autoClear = true;
  88421. var engine = this._scene.getEngine();
  88422. this._disposePostProcesses();
  88423. if (this._cameras !== null) {
  88424. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88425. // get back cameras to be used to reattach pipeline
  88426. this._cameras = this._camerasToBeAttached.slice();
  88427. }
  88428. this._reset();
  88429. this._prevPostProcess = null;
  88430. this._prevPrevPostProcess = null;
  88431. this._hasCleared = false;
  88432. if (this.depthOfFieldEnabled) {
  88433. // Multi camera suport
  88434. if (this._cameras.length > 1) {
  88435. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  88436. var camera = _a[_i];
  88437. var depthRenderer = this._scene.enableDepthRenderer(camera);
  88438. depthRenderer.useOnlyInActiveCamera = true;
  88439. }
  88440. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  88441. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  88442. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  88443. }
  88444. });
  88445. }
  88446. else {
  88447. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88448. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  88449. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  88450. }
  88451. if (!this.depthOfField._isReady()) {
  88452. this.depthOfField._updateEffects();
  88453. }
  88454. this.addEffect(this.depthOfField);
  88455. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  88456. }
  88457. else {
  88458. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88459. }
  88460. if (this.bloomEnabled) {
  88461. if (!this.bloom._isReady()) {
  88462. this.bloom._updateEffects();
  88463. }
  88464. this.addEffect(this.bloom);
  88465. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  88466. }
  88467. if (this._imageProcessingEnabled) {
  88468. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88469. if (this._hdr) {
  88470. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  88471. this._setAutoClearAndTextureSharing(this.imageProcessing);
  88472. }
  88473. else {
  88474. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  88475. }
  88476. }
  88477. if (this.sharpenEnabled) {
  88478. if (!this.sharpen.isReady()) {
  88479. this.sharpen.updateEffect();
  88480. }
  88481. this.addEffect(this._sharpenEffect);
  88482. this._setAutoClearAndTextureSharing(this.sharpen);
  88483. }
  88484. if (this.grainEnabled) {
  88485. if (!this.grain.isReady()) {
  88486. this.grain.updateEffect();
  88487. }
  88488. this.addEffect(this._grainEffect);
  88489. this._setAutoClearAndTextureSharing(this.grain);
  88490. }
  88491. if (this.chromaticAberrationEnabled) {
  88492. if (!this.chromaticAberration.isReady()) {
  88493. this.chromaticAberration.updateEffect();
  88494. }
  88495. this.addEffect(this._chromaticAberrationEffect);
  88496. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  88497. }
  88498. if (this.fxaaEnabled) {
  88499. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88500. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  88501. this._setAutoClearAndTextureSharing(this.fxaa, true);
  88502. }
  88503. if (this._cameras !== null) {
  88504. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  88505. }
  88506. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  88507. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  88508. }
  88509. };
  88510. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  88511. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  88512. for (var i = 0; i < this._cameras.length; i++) {
  88513. var camera = this._cameras[i];
  88514. if (this.imageProcessing) {
  88515. this.imageProcessing.dispose(camera);
  88516. }
  88517. if (this.fxaa) {
  88518. this.fxaa.dispose(camera);
  88519. }
  88520. // These are created in the constructor and should not be disposed on every pipeline change
  88521. if (disposeNonRecreated) {
  88522. if (this.sharpen) {
  88523. this.sharpen.dispose(camera);
  88524. }
  88525. if (this.depthOfField) {
  88526. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88527. this.depthOfField.disposeEffects(camera);
  88528. }
  88529. if (this.bloom) {
  88530. this.bloom.disposeEffects(camera);
  88531. }
  88532. if (this.chromaticAberration) {
  88533. this.chromaticAberration.dispose(camera);
  88534. }
  88535. if (this.grain) {
  88536. this.grain.dispose(camera);
  88537. }
  88538. if (this._glowLayer) {
  88539. this._glowLayer.dispose();
  88540. }
  88541. }
  88542. }
  88543. this.imageProcessing = null;
  88544. this.fxaa = null;
  88545. if (disposeNonRecreated) {
  88546. this.sharpen = null;
  88547. this._sharpenEffect = null;
  88548. this.depthOfField = null;
  88549. this.bloom = null;
  88550. this.chromaticAberration = null;
  88551. this._chromaticAberrationEffect = null;
  88552. this.grain = null;
  88553. this._grainEffect = null;
  88554. this._glowLayer = null;
  88555. }
  88556. };
  88557. /**
  88558. * Adds a camera to the pipeline
  88559. * @param camera the camera to be added
  88560. */
  88561. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  88562. this._camerasToBeAttached.push(camera);
  88563. this._buildPipeline();
  88564. };
  88565. /**
  88566. * Removes a camera from the pipeline
  88567. * @param camera the camera to remove
  88568. */
  88569. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  88570. var index = this._camerasToBeAttached.indexOf(camera);
  88571. this._camerasToBeAttached.splice(index, 1);
  88572. this._buildPipeline();
  88573. };
  88574. /**
  88575. * Dispose of the pipeline and stop all post processes
  88576. */
  88577. DefaultRenderingPipeline.prototype.dispose = function () {
  88578. this._disposePostProcesses(true);
  88579. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88580. this._scene.autoClear = true;
  88581. if (this._resizeObserver) {
  88582. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  88583. this._resizeObserver = null;
  88584. }
  88585. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  88586. _super.prototype.dispose.call(this);
  88587. };
  88588. /**
  88589. * Serialize the rendering pipeline (Used when exporting)
  88590. * @returns the serialized object
  88591. */
  88592. DefaultRenderingPipeline.prototype.serialize = function () {
  88593. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88594. serializationObject.customType = "DefaultRenderingPipeline";
  88595. return serializationObject;
  88596. };
  88597. /**
  88598. * Parse the serialized pipeline
  88599. * @param source Source pipeline.
  88600. * @param scene The scene to load the pipeline to.
  88601. * @param rootUrl The URL of the serialized pipeline.
  88602. * @returns An instantiated pipeline from the serialized object.
  88603. */
  88604. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88605. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  88606. };
  88607. __decorate([
  88608. BABYLON.serialize()
  88609. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  88610. __decorate([
  88611. BABYLON.serialize()
  88612. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  88613. __decorate([
  88614. BABYLON.serialize()
  88615. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  88616. __decorate([
  88617. BABYLON.serialize()
  88618. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  88619. __decorate([
  88620. BABYLON.serialize()
  88621. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  88622. __decorate([
  88623. BABYLON.serialize()
  88624. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  88625. __decorate([
  88626. BABYLON.serialize()
  88627. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  88628. __decorate([
  88629. BABYLON.serialize()
  88630. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  88631. __decorate([
  88632. BABYLON.serialize()
  88633. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  88634. __decorate([
  88635. BABYLON.serialize()
  88636. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  88637. __decorate([
  88638. BABYLON.serialize()
  88639. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  88640. __decorate([
  88641. BABYLON.serialize()
  88642. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  88643. __decorate([
  88644. BABYLON.serialize()
  88645. ], DefaultRenderingPipeline.prototype, "samples", null);
  88646. __decorate([
  88647. BABYLON.serialize()
  88648. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  88649. __decorate([
  88650. BABYLON.serialize()
  88651. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  88652. __decorate([
  88653. BABYLON.serialize()
  88654. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  88655. __decorate([
  88656. BABYLON.serialize()
  88657. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  88658. return DefaultRenderingPipeline;
  88659. }(BABYLON.PostProcessRenderPipeline));
  88660. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  88661. })(BABYLON || (BABYLON = {}));
  88662. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  88663. var BABYLON;
  88664. (function (BABYLON) {
  88665. /**
  88666. * @hidden
  88667. */
  88668. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  88669. __extends(ImageProcessingConfigurationDefines, _super);
  88670. function ImageProcessingConfigurationDefines() {
  88671. var _this = _super.call(this) || this;
  88672. _this.IMAGEPROCESSING = false;
  88673. _this.VIGNETTE = false;
  88674. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88675. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88676. _this.TONEMAPPING = false;
  88677. _this.TONEMAPPING_ACES = false;
  88678. _this.CONTRAST = false;
  88679. _this.COLORCURVES = false;
  88680. _this.COLORGRADING = false;
  88681. _this.COLORGRADING3D = false;
  88682. _this.SAMPLER3DGREENDEPTH = false;
  88683. _this.SAMPLER3DBGRMAP = false;
  88684. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88685. _this.EXPOSURE = false;
  88686. _this.rebuild();
  88687. return _this;
  88688. }
  88689. return ImageProcessingConfigurationDefines;
  88690. }(BABYLON.MaterialDefines));
  88691. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  88692. /**
  88693. * This groups together the common properties used for image processing either in direct forward pass
  88694. * or through post processing effect depending on the use of the image processing pipeline in your scene
  88695. * or not.
  88696. */
  88697. var ImageProcessingConfiguration = /** @class */ (function () {
  88698. function ImageProcessingConfiguration() {
  88699. /**
  88700. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  88701. */
  88702. this.colorCurves = new BABYLON.ColorCurves();
  88703. this._colorCurvesEnabled = false;
  88704. this._colorGradingEnabled = false;
  88705. this._colorGradingWithGreenDepth = true;
  88706. this._colorGradingBGR = true;
  88707. /** @hidden */
  88708. this._exposure = 1.0;
  88709. this._toneMappingEnabled = false;
  88710. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  88711. this._contrast = 1.0;
  88712. /**
  88713. * Vignette stretch size.
  88714. */
  88715. this.vignetteStretch = 0;
  88716. /**
  88717. * Vignette centre X Offset.
  88718. */
  88719. this.vignetteCentreX = 0;
  88720. /**
  88721. * Vignette centre Y Offset.
  88722. */
  88723. this.vignetteCentreY = 0;
  88724. /**
  88725. * Vignette weight or intensity of the vignette effect.
  88726. */
  88727. this.vignetteWeight = 1.5;
  88728. /**
  88729. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88730. * if vignetteEnabled is set to true.
  88731. */
  88732. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88733. /**
  88734. * Camera field of view used by the Vignette effect.
  88735. */
  88736. this.vignetteCameraFov = 0.5;
  88737. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  88738. this._vignetteEnabled = false;
  88739. this._applyByPostProcess = false;
  88740. this._isEnabled = true;
  88741. /**
  88742. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  88743. */
  88744. this.onUpdateParameters = new BABYLON.Observable();
  88745. }
  88746. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  88747. /**
  88748. * Gets wether the color curves effect is enabled.
  88749. */
  88750. get: function () {
  88751. return this._colorCurvesEnabled;
  88752. },
  88753. /**
  88754. * Sets wether the color curves effect is enabled.
  88755. */
  88756. set: function (value) {
  88757. if (this._colorCurvesEnabled === value) {
  88758. return;
  88759. }
  88760. this._colorCurvesEnabled = value;
  88761. this._updateParameters();
  88762. },
  88763. enumerable: true,
  88764. configurable: true
  88765. });
  88766. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  88767. /**
  88768. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88769. */
  88770. get: function () {
  88771. return this._colorGradingTexture;
  88772. },
  88773. /**
  88774. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88775. */
  88776. set: function (value) {
  88777. if (this._colorGradingTexture === value) {
  88778. return;
  88779. }
  88780. this._colorGradingTexture = value;
  88781. this._updateParameters();
  88782. },
  88783. enumerable: true,
  88784. configurable: true
  88785. });
  88786. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  88787. /**
  88788. * Gets wether the color grading effect is enabled.
  88789. */
  88790. get: function () {
  88791. return this._colorGradingEnabled;
  88792. },
  88793. /**
  88794. * Sets wether the color grading effect is enabled.
  88795. */
  88796. set: function (value) {
  88797. if (this._colorGradingEnabled === value) {
  88798. return;
  88799. }
  88800. this._colorGradingEnabled = value;
  88801. this._updateParameters();
  88802. },
  88803. enumerable: true,
  88804. configurable: true
  88805. });
  88806. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  88807. /**
  88808. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  88809. */
  88810. get: function () {
  88811. return this._colorGradingWithGreenDepth;
  88812. },
  88813. /**
  88814. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  88815. */
  88816. set: function (value) {
  88817. if (this._colorGradingWithGreenDepth === value) {
  88818. return;
  88819. }
  88820. this._colorGradingWithGreenDepth = value;
  88821. this._updateParameters();
  88822. },
  88823. enumerable: true,
  88824. configurable: true
  88825. });
  88826. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  88827. /**
  88828. * Gets wether the color grading texture contains BGR values.
  88829. */
  88830. get: function () {
  88831. return this._colorGradingBGR;
  88832. },
  88833. /**
  88834. * Sets wether the color grading texture contains BGR values.
  88835. */
  88836. set: function (value) {
  88837. if (this._colorGradingBGR === value) {
  88838. return;
  88839. }
  88840. this._colorGradingBGR = value;
  88841. this._updateParameters();
  88842. },
  88843. enumerable: true,
  88844. configurable: true
  88845. });
  88846. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  88847. /**
  88848. * Gets the Exposure used in the effect.
  88849. */
  88850. get: function () {
  88851. return this._exposure;
  88852. },
  88853. /**
  88854. * Sets the Exposure used in the effect.
  88855. */
  88856. set: function (value) {
  88857. if (this._exposure === value) {
  88858. return;
  88859. }
  88860. this._exposure = value;
  88861. this._updateParameters();
  88862. },
  88863. enumerable: true,
  88864. configurable: true
  88865. });
  88866. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  88867. /**
  88868. * Gets wether the tone mapping effect is enabled.
  88869. */
  88870. get: function () {
  88871. return this._toneMappingEnabled;
  88872. },
  88873. /**
  88874. * Sets wether the tone mapping effect is enabled.
  88875. */
  88876. set: function (value) {
  88877. if (this._toneMappingEnabled === value) {
  88878. return;
  88879. }
  88880. this._toneMappingEnabled = value;
  88881. this._updateParameters();
  88882. },
  88883. enumerable: true,
  88884. configurable: true
  88885. });
  88886. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  88887. /**
  88888. * Gets the type of tone mapping effect.
  88889. */
  88890. get: function () {
  88891. return this._toneMappingType;
  88892. },
  88893. /**
  88894. * Sets the type of tone mapping effect used in BabylonJS.
  88895. */
  88896. set: function (value) {
  88897. if (this._toneMappingType === value) {
  88898. return;
  88899. }
  88900. this._toneMappingType = value;
  88901. this._updateParameters();
  88902. },
  88903. enumerable: true,
  88904. configurable: true
  88905. });
  88906. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  88907. /**
  88908. * Gets the contrast used in the effect.
  88909. */
  88910. get: function () {
  88911. return this._contrast;
  88912. },
  88913. /**
  88914. * Sets the contrast used in the effect.
  88915. */
  88916. set: function (value) {
  88917. if (this._contrast === value) {
  88918. return;
  88919. }
  88920. this._contrast = value;
  88921. this._updateParameters();
  88922. },
  88923. enumerable: true,
  88924. configurable: true
  88925. });
  88926. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  88927. /**
  88928. * Gets the vignette blend mode allowing different kind of effect.
  88929. */
  88930. get: function () {
  88931. return this._vignetteBlendMode;
  88932. },
  88933. /**
  88934. * Sets the vignette blend mode allowing different kind of effect.
  88935. */
  88936. set: function (value) {
  88937. if (this._vignetteBlendMode === value) {
  88938. return;
  88939. }
  88940. this._vignetteBlendMode = value;
  88941. this._updateParameters();
  88942. },
  88943. enumerable: true,
  88944. configurable: true
  88945. });
  88946. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  88947. /**
  88948. * Gets wether the vignette effect is enabled.
  88949. */
  88950. get: function () {
  88951. return this._vignetteEnabled;
  88952. },
  88953. /**
  88954. * Sets wether the vignette effect is enabled.
  88955. */
  88956. set: function (value) {
  88957. if (this._vignetteEnabled === value) {
  88958. return;
  88959. }
  88960. this._vignetteEnabled = value;
  88961. this._updateParameters();
  88962. },
  88963. enumerable: true,
  88964. configurable: true
  88965. });
  88966. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  88967. /**
  88968. * Gets wether the image processing is applied through a post process or not.
  88969. */
  88970. get: function () {
  88971. return this._applyByPostProcess;
  88972. },
  88973. /**
  88974. * Sets wether the image processing is applied through a post process or not.
  88975. */
  88976. set: function (value) {
  88977. if (this._applyByPostProcess === value) {
  88978. return;
  88979. }
  88980. this._applyByPostProcess = value;
  88981. this._updateParameters();
  88982. },
  88983. enumerable: true,
  88984. configurable: true
  88985. });
  88986. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  88987. /**
  88988. * Gets wether the image processing is enabled or not.
  88989. */
  88990. get: function () {
  88991. return this._isEnabled;
  88992. },
  88993. /**
  88994. * Sets wether the image processing is enabled or not.
  88995. */
  88996. set: function (value) {
  88997. if (this._isEnabled === value) {
  88998. return;
  88999. }
  89000. this._isEnabled = value;
  89001. this._updateParameters();
  89002. },
  89003. enumerable: true,
  89004. configurable: true
  89005. });
  89006. /**
  89007. * Method called each time the image processing information changes requires to recompile the effect.
  89008. */
  89009. ImageProcessingConfiguration.prototype._updateParameters = function () {
  89010. this.onUpdateParameters.notifyObservers(this);
  89011. };
  89012. /**
  89013. * Gets the current class name.
  89014. * @return "ImageProcessingConfiguration"
  89015. */
  89016. ImageProcessingConfiguration.prototype.getClassName = function () {
  89017. return "ImageProcessingConfiguration";
  89018. };
  89019. /**
  89020. * Prepare the list of uniforms associated with the Image Processing effects.
  89021. * @param uniforms The list of uniforms used in the effect
  89022. * @param defines the list of defines currently in use
  89023. */
  89024. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89025. if (defines.EXPOSURE) {
  89026. uniforms.push("exposureLinear");
  89027. }
  89028. if (defines.CONTRAST) {
  89029. uniforms.push("contrast");
  89030. }
  89031. if (defines.COLORGRADING) {
  89032. uniforms.push("colorTransformSettings");
  89033. }
  89034. if (defines.VIGNETTE) {
  89035. uniforms.push("vInverseScreenSize");
  89036. uniforms.push("vignetteSettings1");
  89037. uniforms.push("vignetteSettings2");
  89038. }
  89039. if (defines.COLORCURVES) {
  89040. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89041. }
  89042. };
  89043. /**
  89044. * Prepare the list of samplers associated with the Image Processing effects.
  89045. * @param samplersList The list of uniforms used in the effect
  89046. * @param defines the list of defines currently in use
  89047. */
  89048. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89049. if (defines.COLORGRADING) {
  89050. samplersList.push("txColorTransform");
  89051. }
  89052. };
  89053. /**
  89054. * Prepare the list of defines associated to the shader.
  89055. * @param defines the list of defines to complete
  89056. * @param forPostProcess Define if we are currently in post process mode or not
  89057. */
  89058. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89059. if (forPostProcess === void 0) { forPostProcess = false; }
  89060. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89061. defines.VIGNETTE = false;
  89062. defines.TONEMAPPING = false;
  89063. defines.TONEMAPPING_ACES = false;
  89064. defines.CONTRAST = false;
  89065. defines.EXPOSURE = false;
  89066. defines.COLORCURVES = false;
  89067. defines.COLORGRADING = false;
  89068. defines.COLORGRADING3D = false;
  89069. defines.IMAGEPROCESSING = false;
  89070. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89071. return;
  89072. }
  89073. defines.VIGNETTE = this.vignetteEnabled;
  89074. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89075. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89076. defines.TONEMAPPING = this.toneMappingEnabled;
  89077. switch (this._toneMappingType) {
  89078. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89079. defines.TONEMAPPING_ACES = true;
  89080. break;
  89081. }
  89082. defines.CONTRAST = (this.contrast !== 1.0);
  89083. defines.EXPOSURE = (this.exposure !== 1.0);
  89084. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89085. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89086. if (defines.COLORGRADING) {
  89087. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89088. }
  89089. else {
  89090. defines.COLORGRADING3D = false;
  89091. }
  89092. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89093. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89094. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89095. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89096. };
  89097. /**
  89098. * Returns true if all the image processing information are ready.
  89099. * @returns True if ready, otherwise, false
  89100. */
  89101. ImageProcessingConfiguration.prototype.isReady = function () {
  89102. // Color Grading texure can not be none blocking.
  89103. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89104. };
  89105. /**
  89106. * Binds the image processing to the shader.
  89107. * @param effect The effect to bind to
  89108. * @param aspectRatio Define the current aspect ratio of the effect
  89109. */
  89110. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89111. if (aspectRatio === void 0) { aspectRatio = 1; }
  89112. // Color Curves
  89113. if (this._colorCurvesEnabled && this.colorCurves) {
  89114. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89115. }
  89116. // Vignette
  89117. if (this._vignetteEnabled) {
  89118. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89119. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89120. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89121. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89122. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89123. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89124. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89125. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89126. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89127. var vignettePower = -2.0 * this.vignetteWeight;
  89128. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89129. }
  89130. // Exposure
  89131. effect.setFloat("exposureLinear", this.exposure);
  89132. // Contrast
  89133. effect.setFloat("contrast", this.contrast);
  89134. // Color transform settings
  89135. if (this.colorGradingTexture) {
  89136. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89137. var textureSize = this.colorGradingTexture.getSize().height;
  89138. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89139. 0.5 / textureSize, // textureOffset
  89140. textureSize, // textureSize
  89141. this.colorGradingTexture.level // weight
  89142. );
  89143. }
  89144. };
  89145. /**
  89146. * Clones the current image processing instance.
  89147. * @return The cloned image processing
  89148. */
  89149. ImageProcessingConfiguration.prototype.clone = function () {
  89150. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89151. };
  89152. /**
  89153. * Serializes the current image processing instance to a json representation.
  89154. * @return a JSON representation
  89155. */
  89156. ImageProcessingConfiguration.prototype.serialize = function () {
  89157. return BABYLON.SerializationHelper.Serialize(this);
  89158. };
  89159. /**
  89160. * Parses the image processing from a json representation.
  89161. * @param source the JSON source to parse
  89162. * @return The parsed image processing
  89163. */
  89164. ImageProcessingConfiguration.Parse = function (source) {
  89165. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89166. };
  89167. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89168. /**
  89169. * Used to apply the vignette as a mix with the pixel color.
  89170. */
  89171. get: function () {
  89172. return this._VIGNETTEMODE_MULTIPLY;
  89173. },
  89174. enumerable: true,
  89175. configurable: true
  89176. });
  89177. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89178. /**
  89179. * Used to apply the vignette as a replacement of the pixel color.
  89180. */
  89181. get: function () {
  89182. return this._VIGNETTEMODE_OPAQUE;
  89183. },
  89184. enumerable: true,
  89185. configurable: true
  89186. });
  89187. /**
  89188. * Default tone mapping applied in BabylonJS.
  89189. */
  89190. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89191. /**
  89192. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89193. * to other engines rendering to increase portability.
  89194. */
  89195. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89196. // Static constants associated to the image processing.
  89197. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89198. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89199. __decorate([
  89200. BABYLON.serializeAsColorCurves()
  89201. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89202. __decorate([
  89203. BABYLON.serialize()
  89204. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89205. __decorate([
  89206. BABYLON.serializeAsTexture("colorGradingTexture")
  89207. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89208. __decorate([
  89209. BABYLON.serialize()
  89210. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89211. __decorate([
  89212. BABYLON.serialize()
  89213. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89214. __decorate([
  89215. BABYLON.serialize()
  89216. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89217. __decorate([
  89218. BABYLON.serialize()
  89219. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89220. __decorate([
  89221. BABYLON.serialize()
  89222. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89223. __decorate([
  89224. BABYLON.serialize()
  89225. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89226. __decorate([
  89227. BABYLON.serialize()
  89228. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89229. __decorate([
  89230. BABYLON.serialize()
  89231. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89232. __decorate([
  89233. BABYLON.serialize()
  89234. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89235. __decorate([
  89236. BABYLON.serialize()
  89237. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89238. __decorate([
  89239. BABYLON.serialize()
  89240. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89241. __decorate([
  89242. BABYLON.serializeAsColor4()
  89243. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89244. __decorate([
  89245. BABYLON.serialize()
  89246. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89247. __decorate([
  89248. BABYLON.serialize()
  89249. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89250. __decorate([
  89251. BABYLON.serialize()
  89252. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89253. __decorate([
  89254. BABYLON.serialize()
  89255. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89256. __decorate([
  89257. BABYLON.serialize()
  89258. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89259. return ImageProcessingConfiguration;
  89260. }());
  89261. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89262. })(BABYLON || (BABYLON = {}));
  89263. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  89264. var BABYLON;
  89265. (function (BABYLON) {
  89266. /**
  89267. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89268. * It can help converting any input color in a desired output one. This can then be used to create effects
  89269. * from sepia, black and white to sixties or futuristic rendering...
  89270. *
  89271. * The only supported format is currently 3dl.
  89272. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89273. */
  89274. var ColorGradingTexture = /** @class */ (function (_super) {
  89275. __extends(ColorGradingTexture, _super);
  89276. /**
  89277. * Instantiates a ColorGradingTexture from the following parameters.
  89278. *
  89279. * @param url The location of the color gradind data (currently only supporting 3dl)
  89280. * @param scene The scene the texture will be used in
  89281. */
  89282. function ColorGradingTexture(url, scene) {
  89283. var _this = _super.call(this, scene) || this;
  89284. if (!url) {
  89285. return _this;
  89286. }
  89287. _this._engine = scene.getEngine();
  89288. _this._textureMatrix = BABYLON.Matrix.Identity();
  89289. _this.name = url;
  89290. _this.url = url;
  89291. _this.hasAlpha = false;
  89292. _this.isCube = false;
  89293. _this.is3D = _this._engine.webGLVersion > 1;
  89294. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89295. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89296. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89297. _this.anisotropicFilteringLevel = 1;
  89298. _this._texture = _this._getFromCache(url, true);
  89299. if (!_this._texture) {
  89300. if (!scene.useDelayedTextureLoading) {
  89301. _this.loadTexture();
  89302. }
  89303. else {
  89304. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89305. }
  89306. }
  89307. return _this;
  89308. }
  89309. /**
  89310. * Returns the texture matrix used in most of the material.
  89311. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89312. */
  89313. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89314. return this._textureMatrix;
  89315. };
  89316. /**
  89317. * Occurs when the file being loaded is a .3dl LUT file.
  89318. */
  89319. ColorGradingTexture.prototype.load3dlTexture = function () {
  89320. var engine = this._engine;
  89321. var texture;
  89322. if (engine.webGLVersion === 1) {
  89323. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89324. }
  89325. else {
  89326. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89327. }
  89328. this._texture = texture;
  89329. var callback = function (text) {
  89330. if (typeof text !== "string") {
  89331. return;
  89332. }
  89333. var data = null;
  89334. var tempData = null;
  89335. var line;
  89336. var lines = text.split('\n');
  89337. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89338. var maxColor = 0;
  89339. for (var i = 0; i < lines.length; i++) {
  89340. line = lines[i];
  89341. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89342. continue;
  89343. }
  89344. if (line.indexOf('#') === 0) {
  89345. continue;
  89346. }
  89347. var words = line.split(" ");
  89348. if (size === 0) {
  89349. // Number of space + one
  89350. size = words.length;
  89351. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89352. tempData = new Float32Array(size * size * size * 4);
  89353. continue;
  89354. }
  89355. if (size != 0) {
  89356. var r = Math.max(parseInt(words[0]), 0);
  89357. var g = Math.max(parseInt(words[1]), 0);
  89358. var b = Math.max(parseInt(words[2]), 0);
  89359. maxColor = Math.max(r, maxColor);
  89360. maxColor = Math.max(g, maxColor);
  89361. maxColor = Math.max(b, maxColor);
  89362. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89363. if (tempData) {
  89364. tempData[pixelStorageIndex + 0] = r;
  89365. tempData[pixelStorageIndex + 1] = g;
  89366. tempData[pixelStorageIndex + 2] = b;
  89367. }
  89368. // Keep for reference in case of back compat problems.
  89369. // pixelIndexSlice++;
  89370. // if (pixelIndexSlice % size == 0) {
  89371. // pixelIndexH++;
  89372. // pixelIndexSlice = 0;
  89373. // if (pixelIndexH % size == 0) {
  89374. // pixelIndexW++;
  89375. // pixelIndexH = 0;
  89376. // }
  89377. // }
  89378. pixelIndexH++;
  89379. if (pixelIndexH % size == 0) {
  89380. pixelIndexSlice++;
  89381. pixelIndexH = 0;
  89382. if (pixelIndexSlice % size == 0) {
  89383. pixelIndexW++;
  89384. pixelIndexSlice = 0;
  89385. }
  89386. }
  89387. }
  89388. }
  89389. if (tempData && data) {
  89390. for (var i = 0; i < tempData.length; i++) {
  89391. if (i > 0 && (i + 1) % 4 === 0) {
  89392. data[i] = 255;
  89393. }
  89394. else {
  89395. var value = tempData[i];
  89396. data[i] = (value / maxColor * 255);
  89397. }
  89398. }
  89399. }
  89400. if (texture.is3D) {
  89401. texture.updateSize(size, size, size);
  89402. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89403. }
  89404. else {
  89405. texture.updateSize(size * size, size);
  89406. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89407. }
  89408. };
  89409. var scene = this.getScene();
  89410. if (scene) {
  89411. scene._loadFile(this.url, callback);
  89412. }
  89413. else {
  89414. this._engine._loadFile(this.url, callback);
  89415. }
  89416. return this._texture;
  89417. };
  89418. /**
  89419. * Starts the loading process of the texture.
  89420. */
  89421. ColorGradingTexture.prototype.loadTexture = function () {
  89422. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89423. this.load3dlTexture();
  89424. }
  89425. };
  89426. /**
  89427. * Clones the color gradind texture.
  89428. */
  89429. ColorGradingTexture.prototype.clone = function () {
  89430. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  89431. // Base texture
  89432. newTexture.level = this.level;
  89433. return newTexture;
  89434. };
  89435. /**
  89436. * Called during delayed load for textures.
  89437. */
  89438. ColorGradingTexture.prototype.delayLoad = function () {
  89439. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89440. return;
  89441. }
  89442. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89443. this._texture = this._getFromCache(this.url, true);
  89444. if (!this._texture) {
  89445. this.loadTexture();
  89446. }
  89447. };
  89448. /**
  89449. * Parses a color grading texture serialized by Babylon.
  89450. * @param parsedTexture The texture information being parsedTexture
  89451. * @param scene The scene to load the texture in
  89452. * @param rootUrl The root url of the data assets to load
  89453. * @return A color gradind texture
  89454. */
  89455. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89456. var texture = null;
  89457. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89458. texture = new ColorGradingTexture(parsedTexture.name, scene);
  89459. texture.name = parsedTexture.name;
  89460. texture.level = parsedTexture.level;
  89461. }
  89462. return texture;
  89463. };
  89464. /**
  89465. * Serializes the LUT texture to json format.
  89466. */
  89467. ColorGradingTexture.prototype.serialize = function () {
  89468. if (!this.name) {
  89469. return null;
  89470. }
  89471. var serializationObject = {};
  89472. serializationObject.name = this.name;
  89473. serializationObject.level = this.level;
  89474. serializationObject.customType = "BABYLON.ColorGradingTexture";
  89475. return serializationObject;
  89476. };
  89477. /**
  89478. * Empty line regex stored for GC.
  89479. */
  89480. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  89481. return ColorGradingTexture;
  89482. }(BABYLON.BaseTexture));
  89483. BABYLON.ColorGradingTexture = ColorGradingTexture;
  89484. })(BABYLON || (BABYLON = {}));
  89485. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  89486. var BABYLON;
  89487. (function (BABYLON) {
  89488. /**
  89489. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89490. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89491. * 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;
  89492. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89493. */
  89494. var ColorCurves = /** @class */ (function () {
  89495. function ColorCurves() {
  89496. this._dirty = true;
  89497. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  89498. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  89499. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89500. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  89501. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89502. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  89503. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  89504. this._globalHue = 30;
  89505. this._globalDensity = 0;
  89506. this._globalSaturation = 0;
  89507. this._globalExposure = 0;
  89508. this._highlightsHue = 30;
  89509. this._highlightsDensity = 0;
  89510. this._highlightsSaturation = 0;
  89511. this._highlightsExposure = 0;
  89512. this._midtonesHue = 30;
  89513. this._midtonesDensity = 0;
  89514. this._midtonesSaturation = 0;
  89515. this._midtonesExposure = 0;
  89516. this._shadowsHue = 30;
  89517. this._shadowsDensity = 0;
  89518. this._shadowsSaturation = 0;
  89519. this._shadowsExposure = 0;
  89520. }
  89521. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  89522. /**
  89523. * Gets the global Hue value.
  89524. * 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).
  89525. */
  89526. get: function () {
  89527. return this._globalHue;
  89528. },
  89529. /**
  89530. * Sets the global Hue value.
  89531. * 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).
  89532. */
  89533. set: function (value) {
  89534. this._globalHue = value;
  89535. this._dirty = true;
  89536. },
  89537. enumerable: true,
  89538. configurable: true
  89539. });
  89540. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  89541. /**
  89542. * Gets the global Density value.
  89543. * 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.
  89544. * Values less than zero provide a filter of opposite hue.
  89545. */
  89546. get: function () {
  89547. return this._globalDensity;
  89548. },
  89549. /**
  89550. * Sets the global Density value.
  89551. * 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.
  89552. * Values less than zero provide a filter of opposite hue.
  89553. */
  89554. set: function (value) {
  89555. this._globalDensity = value;
  89556. this._dirty = true;
  89557. },
  89558. enumerable: true,
  89559. configurable: true
  89560. });
  89561. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  89562. /**
  89563. * Gets the global Saturation value.
  89564. * 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.
  89565. */
  89566. get: function () {
  89567. return this._globalSaturation;
  89568. },
  89569. /**
  89570. * Sets the global Saturation value.
  89571. * 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.
  89572. */
  89573. set: function (value) {
  89574. this._globalSaturation = value;
  89575. this._dirty = true;
  89576. },
  89577. enumerable: true,
  89578. configurable: true
  89579. });
  89580. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  89581. /**
  89582. * Gets the global Exposure value.
  89583. * 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.
  89584. */
  89585. get: function () {
  89586. return this._globalExposure;
  89587. },
  89588. /**
  89589. * Sets the global Exposure value.
  89590. * 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.
  89591. */
  89592. set: function (value) {
  89593. this._globalExposure = value;
  89594. this._dirty = true;
  89595. },
  89596. enumerable: true,
  89597. configurable: true
  89598. });
  89599. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  89600. /**
  89601. * Gets the highlights Hue value.
  89602. * 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).
  89603. */
  89604. get: function () {
  89605. return this._highlightsHue;
  89606. },
  89607. /**
  89608. * Sets the highlights Hue value.
  89609. * 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).
  89610. */
  89611. set: function (value) {
  89612. this._highlightsHue = value;
  89613. this._dirty = true;
  89614. },
  89615. enumerable: true,
  89616. configurable: true
  89617. });
  89618. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  89619. /**
  89620. * Gets the highlights Density value.
  89621. * 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.
  89622. * Values less than zero provide a filter of opposite hue.
  89623. */
  89624. get: function () {
  89625. return this._highlightsDensity;
  89626. },
  89627. /**
  89628. * Sets the highlights Density value.
  89629. * 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.
  89630. * Values less than zero provide a filter of opposite hue.
  89631. */
  89632. set: function (value) {
  89633. this._highlightsDensity = value;
  89634. this._dirty = true;
  89635. },
  89636. enumerable: true,
  89637. configurable: true
  89638. });
  89639. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  89640. /**
  89641. * Gets the highlights Saturation value.
  89642. * 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.
  89643. */
  89644. get: function () {
  89645. return this._highlightsSaturation;
  89646. },
  89647. /**
  89648. * Sets the highlights Saturation value.
  89649. * 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.
  89650. */
  89651. set: function (value) {
  89652. this._highlightsSaturation = value;
  89653. this._dirty = true;
  89654. },
  89655. enumerable: true,
  89656. configurable: true
  89657. });
  89658. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  89659. /**
  89660. * Gets the highlights Exposure value.
  89661. * 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.
  89662. */
  89663. get: function () {
  89664. return this._highlightsExposure;
  89665. },
  89666. /**
  89667. * Sets the highlights Exposure value.
  89668. * 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.
  89669. */
  89670. set: function (value) {
  89671. this._highlightsExposure = value;
  89672. this._dirty = true;
  89673. },
  89674. enumerable: true,
  89675. configurable: true
  89676. });
  89677. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  89678. /**
  89679. * Gets the midtones Hue value.
  89680. * 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).
  89681. */
  89682. get: function () {
  89683. return this._midtonesHue;
  89684. },
  89685. /**
  89686. * Sets the midtones Hue value.
  89687. * 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).
  89688. */
  89689. set: function (value) {
  89690. this._midtonesHue = value;
  89691. this._dirty = true;
  89692. },
  89693. enumerable: true,
  89694. configurable: true
  89695. });
  89696. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  89697. /**
  89698. * Gets the midtones Density value.
  89699. * 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.
  89700. * Values less than zero provide a filter of opposite hue.
  89701. */
  89702. get: function () {
  89703. return this._midtonesDensity;
  89704. },
  89705. /**
  89706. * Sets the midtones Density value.
  89707. * 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.
  89708. * Values less than zero provide a filter of opposite hue.
  89709. */
  89710. set: function (value) {
  89711. this._midtonesDensity = value;
  89712. this._dirty = true;
  89713. },
  89714. enumerable: true,
  89715. configurable: true
  89716. });
  89717. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  89718. /**
  89719. * Gets the midtones Saturation value.
  89720. * 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.
  89721. */
  89722. get: function () {
  89723. return this._midtonesSaturation;
  89724. },
  89725. /**
  89726. * Sets the midtones Saturation value.
  89727. * 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.
  89728. */
  89729. set: function (value) {
  89730. this._midtonesSaturation = value;
  89731. this._dirty = true;
  89732. },
  89733. enumerable: true,
  89734. configurable: true
  89735. });
  89736. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  89737. /**
  89738. * Gets the midtones Exposure value.
  89739. * 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.
  89740. */
  89741. get: function () {
  89742. return this._midtonesExposure;
  89743. },
  89744. /**
  89745. * Sets the midtones Exposure value.
  89746. * 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.
  89747. */
  89748. set: function (value) {
  89749. this._midtonesExposure = value;
  89750. this._dirty = true;
  89751. },
  89752. enumerable: true,
  89753. configurable: true
  89754. });
  89755. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  89756. /**
  89757. * Gets the shadows Hue value.
  89758. * 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).
  89759. */
  89760. get: function () {
  89761. return this._shadowsHue;
  89762. },
  89763. /**
  89764. * Sets the shadows Hue value.
  89765. * 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).
  89766. */
  89767. set: function (value) {
  89768. this._shadowsHue = value;
  89769. this._dirty = true;
  89770. },
  89771. enumerable: true,
  89772. configurable: true
  89773. });
  89774. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  89775. /**
  89776. * Gets the shadows Density value.
  89777. * 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.
  89778. * Values less than zero provide a filter of opposite hue.
  89779. */
  89780. get: function () {
  89781. return this._shadowsDensity;
  89782. },
  89783. /**
  89784. * Sets the shadows Density value.
  89785. * 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.
  89786. * Values less than zero provide a filter of opposite hue.
  89787. */
  89788. set: function (value) {
  89789. this._shadowsDensity = value;
  89790. this._dirty = true;
  89791. },
  89792. enumerable: true,
  89793. configurable: true
  89794. });
  89795. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  89796. /**
  89797. * Gets the shadows Saturation value.
  89798. * 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.
  89799. */
  89800. get: function () {
  89801. return this._shadowsSaturation;
  89802. },
  89803. /**
  89804. * Sets the shadows Saturation value.
  89805. * 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.
  89806. */
  89807. set: function (value) {
  89808. this._shadowsSaturation = value;
  89809. this._dirty = true;
  89810. },
  89811. enumerable: true,
  89812. configurable: true
  89813. });
  89814. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  89815. /**
  89816. * Gets the shadows Exposure value.
  89817. * 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.
  89818. */
  89819. get: function () {
  89820. return this._shadowsExposure;
  89821. },
  89822. /**
  89823. * Sets the shadows Exposure value.
  89824. * 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.
  89825. */
  89826. set: function (value) {
  89827. this._shadowsExposure = value;
  89828. this._dirty = true;
  89829. },
  89830. enumerable: true,
  89831. configurable: true
  89832. });
  89833. /**
  89834. * Returns the class name
  89835. * @returns The class name
  89836. */
  89837. ColorCurves.prototype.getClassName = function () {
  89838. return "ColorCurves";
  89839. };
  89840. /**
  89841. * Binds the color curves to the shader.
  89842. * @param colorCurves The color curve to bind
  89843. * @param effect The effect to bind to
  89844. * @param positiveUniform The positive uniform shader parameter
  89845. * @param neutralUniform The neutral uniform shader parameter
  89846. * @param negativeUniform The negative uniform shader parameter
  89847. */
  89848. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  89849. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  89850. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  89851. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  89852. if (colorCurves._dirty) {
  89853. colorCurves._dirty = false;
  89854. // Fill in global info.
  89855. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  89856. // Compute highlights info.
  89857. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  89858. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  89859. // Compute midtones info.
  89860. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  89861. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  89862. // Compute shadows info.
  89863. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  89864. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  89865. // Compute deltas (neutral is midtones).
  89866. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  89867. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  89868. }
  89869. if (effect) {
  89870. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  89871. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  89872. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  89873. }
  89874. };
  89875. /**
  89876. * Prepare the list of uniforms associated with the ColorCurves effects.
  89877. * @param uniformsList The list of uniforms used in the effect
  89878. */
  89879. ColorCurves.PrepareUniforms = function (uniformsList) {
  89880. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  89881. };
  89882. /**
  89883. * Returns color grading data based on a hue, density, saturation and exposure value.
  89884. * @param filterHue The hue of the color filter.
  89885. * @param filterDensity The density of the color filter.
  89886. * @param saturation The saturation.
  89887. * @param exposure The exposure.
  89888. * @param result The result data container.
  89889. */
  89890. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  89891. if (hue == null) {
  89892. return;
  89893. }
  89894. hue = ColorCurves.clamp(hue, 0, 360);
  89895. density = ColorCurves.clamp(density, -100, 100);
  89896. saturation = ColorCurves.clamp(saturation, -100, 100);
  89897. exposure = ColorCurves.clamp(exposure, -100, 100);
  89898. // Remap the slider/config filter density with non-linear mapping and also scale by half
  89899. // so that the maximum filter density is only 50% control. This provides fine control
  89900. // for small values and reasonable range.
  89901. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  89902. density *= 0.5;
  89903. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  89904. if (density < 0) {
  89905. density *= -1;
  89906. hue = (hue + 180) % 360;
  89907. }
  89908. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  89909. result.scaleToRef(2, result);
  89910. result.a = 1 + 0.01 * saturation;
  89911. };
  89912. /**
  89913. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  89914. * @param value The input slider value in range [-100,100].
  89915. * @returns Adjusted value.
  89916. */
  89917. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  89918. value /= 100;
  89919. var x = Math.abs(value);
  89920. x = Math.pow(x, 2);
  89921. if (value < 0) {
  89922. x *= -1;
  89923. }
  89924. x *= 100;
  89925. return x;
  89926. };
  89927. /**
  89928. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  89929. * @param hue The hue (H) input.
  89930. * @param saturation The saturation (S) input.
  89931. * @param brightness The brightness (B) input.
  89932. * @result An RGBA color represented as Vector4.
  89933. */
  89934. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  89935. var h = ColorCurves.clamp(hue, 0, 360);
  89936. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  89937. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  89938. if (s === 0) {
  89939. result.r = v;
  89940. result.g = v;
  89941. result.b = v;
  89942. }
  89943. else {
  89944. // sector 0 to 5
  89945. h /= 60;
  89946. var i = Math.floor(h);
  89947. // fractional part of h
  89948. var f = h - i;
  89949. var p = v * (1 - s);
  89950. var q = v * (1 - s * f);
  89951. var t = v * (1 - s * (1 - f));
  89952. switch (i) {
  89953. case 0:
  89954. result.r = v;
  89955. result.g = t;
  89956. result.b = p;
  89957. break;
  89958. case 1:
  89959. result.r = q;
  89960. result.g = v;
  89961. result.b = p;
  89962. break;
  89963. case 2:
  89964. result.r = p;
  89965. result.g = v;
  89966. result.b = t;
  89967. break;
  89968. case 3:
  89969. result.r = p;
  89970. result.g = q;
  89971. result.b = v;
  89972. break;
  89973. case 4:
  89974. result.r = t;
  89975. result.g = p;
  89976. result.b = v;
  89977. break;
  89978. default: // case 5:
  89979. result.r = v;
  89980. result.g = p;
  89981. result.b = q;
  89982. break;
  89983. }
  89984. }
  89985. result.a = 1;
  89986. };
  89987. /**
  89988. * Returns a value clamped between min and max
  89989. * @param value The value to clamp
  89990. * @param min The minimum of value
  89991. * @param max The maximum of value
  89992. * @returns The clamped value.
  89993. */
  89994. ColorCurves.clamp = function (value, min, max) {
  89995. return Math.min(Math.max(value, min), max);
  89996. };
  89997. /**
  89998. * Clones the current color curve instance.
  89999. * @return The cloned curves
  90000. */
  90001. ColorCurves.prototype.clone = function () {
  90002. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  90003. };
  90004. /**
  90005. * Serializes the current color curve instance to a json representation.
  90006. * @return a JSON representation
  90007. */
  90008. ColorCurves.prototype.serialize = function () {
  90009. return BABYLON.SerializationHelper.Serialize(this);
  90010. };
  90011. /**
  90012. * Parses the color curve from a json representation.
  90013. * @param source the JSON source to parse
  90014. * @return The parsed curves
  90015. */
  90016. ColorCurves.Parse = function (source) {
  90017. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  90018. };
  90019. __decorate([
  90020. BABYLON.serialize()
  90021. ], ColorCurves.prototype, "_globalHue", void 0);
  90022. __decorate([
  90023. BABYLON.serialize()
  90024. ], ColorCurves.prototype, "_globalDensity", void 0);
  90025. __decorate([
  90026. BABYLON.serialize()
  90027. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90028. __decorate([
  90029. BABYLON.serialize()
  90030. ], ColorCurves.prototype, "_globalExposure", void 0);
  90031. __decorate([
  90032. BABYLON.serialize()
  90033. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90034. __decorate([
  90035. BABYLON.serialize()
  90036. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90037. __decorate([
  90038. BABYLON.serialize()
  90039. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90040. __decorate([
  90041. BABYLON.serialize()
  90042. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90043. __decorate([
  90044. BABYLON.serialize()
  90045. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90046. __decorate([
  90047. BABYLON.serialize()
  90048. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90049. __decorate([
  90050. BABYLON.serialize()
  90051. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90052. __decorate([
  90053. BABYLON.serialize()
  90054. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90055. return ColorCurves;
  90056. }());
  90057. BABYLON.ColorCurves = ColorCurves;
  90058. })(BABYLON || (BABYLON = {}));
  90059. //# sourceMappingURL=babylon.colorCurves.js.map
  90060. var BABYLON;
  90061. (function (BABYLON) {
  90062. /**
  90063. * Post process which applies a refractin texture
  90064. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90065. */
  90066. var RefractionPostProcess = /** @class */ (function (_super) {
  90067. __extends(RefractionPostProcess, _super);
  90068. /**
  90069. * Initializes the RefractionPostProcess
  90070. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90071. * @param name The name of the effect.
  90072. * @param refractionTextureUrl Url of the refraction texture to use
  90073. * @param color the base color of the refraction (used to taint the rendering)
  90074. * @param depth simulated refraction depth
  90075. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90076. * @param camera The camera to apply the render pass to.
  90077. * @param options The required width/height ratio to downsize to before computing the render pass.
  90078. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90079. * @param engine The engine which the post process will be applied. (default: current engine)
  90080. * @param reusable If the post process can be reused on the same frame. (default: false)
  90081. */
  90082. function RefractionPostProcess(name, refractionTextureUrl,
  90083. /** the base color of the refraction (used to taint the rendering) */
  90084. color,
  90085. /** simulated refraction depth */
  90086. depth,
  90087. /** the coefficient of the base color (0 to remove base color tainting) */
  90088. colorLevel, options, camera, samplingMode, engine, reusable) {
  90089. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90090. _this.color = color;
  90091. _this.depth = depth;
  90092. _this.colorLevel = colorLevel;
  90093. _this._ownRefractionTexture = true;
  90094. _this.onActivateObservable.add(function (cam) {
  90095. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90096. });
  90097. _this.onApplyObservable.add(function (effect) {
  90098. effect.setColor3("baseColor", _this.color);
  90099. effect.setFloat("depth", _this.depth);
  90100. effect.setFloat("colorLevel", _this.colorLevel);
  90101. effect.setTexture("refractionSampler", _this._refTexture);
  90102. });
  90103. return _this;
  90104. }
  90105. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90106. /**
  90107. * Gets or sets the refraction texture
  90108. * Please note that you are responsible for disposing the texture if you set it manually
  90109. */
  90110. get: function () {
  90111. return this._refTexture;
  90112. },
  90113. set: function (value) {
  90114. if (this._refTexture && this._ownRefractionTexture) {
  90115. this._refTexture.dispose();
  90116. }
  90117. this._refTexture = value;
  90118. this._ownRefractionTexture = false;
  90119. },
  90120. enumerable: true,
  90121. configurable: true
  90122. });
  90123. // Methods
  90124. /**
  90125. * Disposes of the post process
  90126. * @param camera Camera to dispose post process on
  90127. */
  90128. RefractionPostProcess.prototype.dispose = function (camera) {
  90129. if (this._refTexture && this._ownRefractionTexture) {
  90130. this._refTexture.dispose();
  90131. this._refTexture = null;
  90132. }
  90133. _super.prototype.dispose.call(this, camera);
  90134. };
  90135. return RefractionPostProcess;
  90136. }(BABYLON.PostProcess));
  90137. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90138. })(BABYLON || (BABYLON = {}));
  90139. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  90140. var BABYLON;
  90141. (function (BABYLON) {
  90142. /**
  90143. * Post process used to render in black and white
  90144. */
  90145. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90146. __extends(BlackAndWhitePostProcess, _super);
  90147. /**
  90148. * Creates a black and white post process
  90149. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90150. * @param name The name of the effect.
  90151. * @param options The required width/height ratio to downsize to before computing the render pass.
  90152. * @param camera The camera to apply the render pass to.
  90153. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90154. * @param engine The engine which the post process will be applied. (default: current engine)
  90155. * @param reusable If the post process can be reused on the same frame. (default: false)
  90156. */
  90157. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90158. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90159. /**
  90160. * Linear about to convert he result to black and white (default: 1)
  90161. */
  90162. _this.degree = 1;
  90163. _this.onApplyObservable.add(function (effect) {
  90164. effect.setFloat("degree", _this.degree);
  90165. });
  90166. return _this;
  90167. }
  90168. return BlackAndWhitePostProcess;
  90169. }(BABYLON.PostProcess));
  90170. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90171. })(BABYLON || (BABYLON = {}));
  90172. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  90173. var BABYLON;
  90174. (function (BABYLON) {
  90175. /**
  90176. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90177. * input texture to perform effects such as edge detection or sharpening
  90178. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90179. */
  90180. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90181. __extends(ConvolutionPostProcess, _super);
  90182. /**
  90183. * Creates a new instance ConvolutionPostProcess
  90184. * @param name The name of the effect.
  90185. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90186. * @param options The required width/height ratio to downsize to before computing the render pass.
  90187. * @param camera The camera to apply the render pass to.
  90188. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90189. * @param engine The engine which the post process will be applied. (default: current engine)
  90190. * @param reusable If the post process can be reused on the same frame. (default: false)
  90191. * @param textureType Type of textures used when performing the post process. (default: 0)
  90192. */
  90193. function ConvolutionPostProcess(name,
  90194. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90195. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90196. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90197. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90198. _this.kernel = kernel;
  90199. _this.onApply = function (effect) {
  90200. effect.setFloat2("screenSize", _this.width, _this.height);
  90201. effect.setArray("kernel", _this.kernel);
  90202. };
  90203. return _this;
  90204. }
  90205. // Statics
  90206. /**
  90207. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90208. */
  90209. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90210. /**
  90211. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90212. */
  90213. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90214. /**
  90215. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90216. */
  90217. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90218. /**
  90219. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90220. */
  90221. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90222. /**
  90223. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90224. */
  90225. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90226. /**
  90227. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90228. */
  90229. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90230. return ConvolutionPostProcess;
  90231. }(BABYLON.PostProcess));
  90232. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90233. })(BABYLON || (BABYLON = {}));
  90234. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  90235. var BABYLON;
  90236. (function (BABYLON) {
  90237. /**
  90238. * Applies a kernel filter to the image
  90239. */
  90240. var FilterPostProcess = /** @class */ (function (_super) {
  90241. __extends(FilterPostProcess, _super);
  90242. /**
  90243. *
  90244. * @param name The name of the effect.
  90245. * @param kernelMatrix The matrix to be applied to the image
  90246. * @param options The required width/height ratio to downsize to before computing the render pass.
  90247. * @param camera The camera to apply the render pass to.
  90248. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90249. * @param engine The engine which the post process will be applied. (default: current engine)
  90250. * @param reusable If the post process can be reused on the same frame. (default: false)
  90251. */
  90252. function FilterPostProcess(name,
  90253. /** The matrix to be applied to the image */
  90254. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90255. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90256. _this.kernelMatrix = kernelMatrix;
  90257. _this.onApply = function (effect) {
  90258. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90259. };
  90260. return _this;
  90261. }
  90262. return FilterPostProcess;
  90263. }(BABYLON.PostProcess));
  90264. BABYLON.FilterPostProcess = FilterPostProcess;
  90265. })(BABYLON || (BABYLON = {}));
  90266. //# sourceMappingURL=babylon.filterPostProcess.js.map
  90267. var BABYLON;
  90268. (function (BABYLON) {
  90269. /**
  90270. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90271. */
  90272. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90273. __extends(VolumetricLightScatteringPostProcess, _super);
  90274. /**
  90275. * @constructor
  90276. * @param name The post-process name
  90277. * @param 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)
  90278. * @param camera The camera that the post-process will be attached to
  90279. * @param mesh The mesh used to create the light scattering
  90280. * @param samples The post-process quality, default 100
  90281. * @param samplingModeThe post-process filtering mode
  90282. * @param engine The babylon engine
  90283. * @param reusable If the post-process is reusable
  90284. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90285. */
  90286. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90287. if (samples === void 0) { samples = 100; }
  90288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90289. 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;
  90290. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90291. /**
  90292. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90293. */
  90294. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90295. /**
  90296. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90297. */
  90298. _this.useCustomMeshPosition = false;
  90299. /**
  90300. * If the post-process should inverse the light scattering direction
  90301. */
  90302. _this.invert = true;
  90303. /**
  90304. * Array containing the excluded meshes not rendered in the internal pass
  90305. */
  90306. _this.excludedMeshes = new Array();
  90307. /**
  90308. * Controls the overall intensity of the post-process
  90309. */
  90310. _this.exposure = 0.3;
  90311. /**
  90312. * Dissipates each sample's contribution in range [0, 1]
  90313. */
  90314. _this.decay = 0.96815;
  90315. /**
  90316. * Controls the overall intensity of each sample
  90317. */
  90318. _this.weight = 0.58767;
  90319. /**
  90320. * Controls the density of each sample
  90321. */
  90322. _this.density = 0.926;
  90323. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90324. engine = scene.getEngine();
  90325. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90326. // Configure mesh
  90327. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90328. // Configure
  90329. _this._createPass(scene, ratio.passRatio || ratio);
  90330. _this.onActivate = function (camera) {
  90331. if (!_this.isSupported) {
  90332. _this.dispose(camera);
  90333. }
  90334. _this.onActivate = null;
  90335. };
  90336. _this.onApplyObservable.add(function (effect) {
  90337. _this._updateMeshScreenCoordinates(scene);
  90338. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90339. effect.setFloat("exposure", _this.exposure);
  90340. effect.setFloat("decay", _this.decay);
  90341. effect.setFloat("weight", _this.weight);
  90342. effect.setFloat("density", _this.density);
  90343. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90344. });
  90345. return _this;
  90346. }
  90347. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90348. /**
  90349. * @hidden
  90350. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90351. */
  90352. get: function () {
  90353. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90354. return false;
  90355. },
  90356. set: function (useDiffuseColor) {
  90357. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90358. },
  90359. enumerable: true,
  90360. configurable: true
  90361. });
  90362. /**
  90363. * Returns the string "VolumetricLightScatteringPostProcess"
  90364. * @returns "VolumetricLightScatteringPostProcess"
  90365. */
  90366. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90367. return "VolumetricLightScatteringPostProcess";
  90368. };
  90369. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90370. var mesh = subMesh.getMesh();
  90371. // Render this.mesh as default
  90372. if (mesh === this.mesh && mesh.material) {
  90373. return mesh.material.isReady(mesh);
  90374. }
  90375. var defines = [];
  90376. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90377. var material = subMesh.getMaterial();
  90378. // Alpha test
  90379. if (material) {
  90380. if (material.needAlphaTesting()) {
  90381. defines.push("#define ALPHATEST");
  90382. }
  90383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90384. attribs.push(BABYLON.VertexBuffer.UVKind);
  90385. defines.push("#define UV1");
  90386. }
  90387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90389. defines.push("#define UV2");
  90390. }
  90391. }
  90392. // Bones
  90393. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90396. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90397. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90398. }
  90399. else {
  90400. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90401. }
  90402. // Instances
  90403. if (useInstances) {
  90404. defines.push("#define INSTANCES");
  90405. attribs.push("world0");
  90406. attribs.push("world1");
  90407. attribs.push("world2");
  90408. attribs.push("world3");
  90409. }
  90410. // Get correct effect
  90411. var join = defines.join("\n");
  90412. if (this._cachedDefines !== join) {
  90413. this._cachedDefines = join;
  90414. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90415. }
  90416. return this._volumetricLightScatteringPass.isReady();
  90417. };
  90418. /**
  90419. * Sets the new light position for light scattering effect
  90420. * @param position The new custom light position
  90421. */
  90422. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90423. this.customMeshPosition = position;
  90424. };
  90425. /**
  90426. * Returns the light position for light scattering effect
  90427. * @return Vector3 The custom light position
  90428. */
  90429. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  90430. return this.customMeshPosition;
  90431. };
  90432. /**
  90433. * Disposes the internal assets and detaches the post-process from the camera
  90434. */
  90435. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  90436. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  90437. if (rttIndex !== -1) {
  90438. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  90439. }
  90440. this._volumetricLightScatteringRTT.dispose();
  90441. _super.prototype.dispose.call(this, camera);
  90442. };
  90443. /**
  90444. * Returns the render target texture used by the post-process
  90445. * @return the render target texture used by the post-process
  90446. */
  90447. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  90448. return this._volumetricLightScatteringRTT;
  90449. };
  90450. // Private methods
  90451. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  90452. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  90453. return true;
  90454. }
  90455. return false;
  90456. };
  90457. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  90458. var _this = this;
  90459. var engine = scene.getEngine();
  90460. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90461. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90462. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90463. this._volumetricLightScatteringRTT.renderList = null;
  90464. this._volumetricLightScatteringRTT.renderParticles = false;
  90465. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  90466. var camera = this.getCamera();
  90467. if (camera) {
  90468. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90469. }
  90470. else {
  90471. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90472. }
  90473. // Custom render function for submeshes
  90474. var renderSubMesh = function (subMesh) {
  90475. var mesh = subMesh.getRenderingMesh();
  90476. if (_this._meshExcluded(mesh)) {
  90477. return;
  90478. }
  90479. var material = subMesh.getMaterial();
  90480. if (!material) {
  90481. return;
  90482. }
  90483. var scene = mesh.getScene();
  90484. var engine = scene.getEngine();
  90485. // Culling
  90486. engine.setState(material.backFaceCulling);
  90487. // Managing instances
  90488. var batch = mesh._getInstancesRenderList(subMesh._id);
  90489. if (batch.mustReturn) {
  90490. return;
  90491. }
  90492. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  90493. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  90494. var effect = _this._volumetricLightScatteringPass;
  90495. if (mesh === _this.mesh) {
  90496. if (subMesh.effect) {
  90497. effect = subMesh.effect;
  90498. }
  90499. else {
  90500. effect = material.getEffect();
  90501. }
  90502. }
  90503. engine.enableEffect(effect);
  90504. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  90505. if (mesh === _this.mesh) {
  90506. material.bind(mesh.getWorldMatrix(), mesh);
  90507. }
  90508. else {
  90509. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  90510. // Alpha test
  90511. if (material && material.needAlphaTesting()) {
  90512. var alphaTexture = material.getAlphaTestTexture();
  90513. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  90514. if (alphaTexture) {
  90515. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90516. }
  90517. }
  90518. // Bones
  90519. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90520. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90521. }
  90522. }
  90523. // Draw
  90524. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  90525. }
  90526. };
  90527. // Render target texture callbacks
  90528. var savedSceneClearColor;
  90529. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  90530. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  90531. savedSceneClearColor = scene.clearColor;
  90532. scene.clearColor = sceneClearColor;
  90533. });
  90534. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  90535. scene.clearColor = savedSceneClearColor;
  90536. });
  90537. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90538. var engine = scene.getEngine();
  90539. var index;
  90540. if (depthOnlySubMeshes.length) {
  90541. engine.setColorWrite(false);
  90542. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90543. renderSubMesh(depthOnlySubMeshes.data[index]);
  90544. }
  90545. engine.setColorWrite(true);
  90546. }
  90547. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90548. renderSubMesh(opaqueSubMeshes.data[index]);
  90549. }
  90550. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90551. renderSubMesh(alphaTestSubMeshes.data[index]);
  90552. }
  90553. if (transparentSubMeshes.length) {
  90554. // Sort sub meshes
  90555. for (index = 0; index < transparentSubMeshes.length; index++) {
  90556. var submesh = transparentSubMeshes.data[index];
  90557. var boundingInfo = submesh.getBoundingInfo();
  90558. if (boundingInfo && scene.activeCamera) {
  90559. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  90560. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  90561. }
  90562. }
  90563. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  90564. sortedArray.sort(function (a, b) {
  90565. // Alpha index first
  90566. if (a._alphaIndex > b._alphaIndex) {
  90567. return 1;
  90568. }
  90569. if (a._alphaIndex < b._alphaIndex) {
  90570. return -1;
  90571. }
  90572. // Then distance to camera
  90573. if (a._distanceToCamera < b._distanceToCamera) {
  90574. return 1;
  90575. }
  90576. if (a._distanceToCamera > b._distanceToCamera) {
  90577. return -1;
  90578. }
  90579. return 0;
  90580. });
  90581. // Render sub meshes
  90582. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  90583. for (index = 0; index < sortedArray.length; index++) {
  90584. renderSubMesh(sortedArray[index]);
  90585. }
  90586. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90587. }
  90588. };
  90589. };
  90590. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  90591. var transform = scene.getTransformMatrix();
  90592. var meshPosition;
  90593. if (this.useCustomMeshPosition) {
  90594. meshPosition = this.customMeshPosition;
  90595. }
  90596. else if (this.attachedNode) {
  90597. meshPosition = this.attachedNode.position;
  90598. }
  90599. else {
  90600. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  90601. }
  90602. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  90603. this._screenCoordinates.x = pos.x / this._viewPort.width;
  90604. this._screenCoordinates.y = pos.y / this._viewPort.height;
  90605. if (this.invert) {
  90606. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  90607. }
  90608. };
  90609. // Static methods
  90610. /**
  90611. * Creates a default mesh for the Volumeric Light Scattering post-process
  90612. * @param name The mesh name
  90613. * @param scene The scene where to create the mesh
  90614. * @return the default mesh
  90615. */
  90616. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  90617. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  90618. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  90619. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  90620. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  90621. mesh.material = material;
  90622. return mesh;
  90623. };
  90624. __decorate([
  90625. BABYLON.serializeAsVector3()
  90626. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  90627. __decorate([
  90628. BABYLON.serialize()
  90629. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  90630. __decorate([
  90631. BABYLON.serialize()
  90632. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  90633. __decorate([
  90634. BABYLON.serializeAsMeshReference()
  90635. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  90636. __decorate([
  90637. BABYLON.serialize()
  90638. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  90639. __decorate([
  90640. BABYLON.serialize()
  90641. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  90642. __decorate([
  90643. BABYLON.serialize()
  90644. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  90645. __decorate([
  90646. BABYLON.serialize()
  90647. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  90648. __decorate([
  90649. BABYLON.serialize()
  90650. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  90651. return VolumetricLightScatteringPostProcess;
  90652. }(BABYLON.PostProcess));
  90653. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  90654. })(BABYLON || (BABYLON = {}));
  90655. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  90656. var BABYLON;
  90657. (function (BABYLON) {
  90658. /**
  90659. *
  90660. * This post-process allows the modification of rendered colors by using
  90661. * a 'look-up table' (LUT). This effect is also called Color Grading.
  90662. *
  90663. * The object needs to be provided an url to a texture containing the color
  90664. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  90665. * Use an image editing software to tweak the LUT to match your needs.
  90666. *
  90667. * For an example of a color LUT, see here:
  90668. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  90669. * For explanations on color grading, see here:
  90670. * @see http://udn.epicgames.com/Three/ColorGrading.html
  90671. *
  90672. */
  90673. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  90674. __extends(ColorCorrectionPostProcess, _super);
  90675. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  90676. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  90677. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90678. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  90679. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90680. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90681. _this.onApply = function (effect) {
  90682. effect.setTexture("colorTable", _this._colorTableTexture);
  90683. };
  90684. return _this;
  90685. }
  90686. return ColorCorrectionPostProcess;
  90687. }(BABYLON.PostProcess));
  90688. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  90689. })(BABYLON || (BABYLON = {}));
  90690. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  90691. var BABYLON;
  90692. (function (BABYLON) {
  90693. /** Defines operator used for tonemapping */
  90694. var TonemappingOperator;
  90695. (function (TonemappingOperator) {
  90696. /** Hable */
  90697. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  90698. /** Reinhard */
  90699. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  90700. /** HejiDawson */
  90701. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  90702. /** Photographic */
  90703. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  90704. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  90705. /**
  90706. * Defines a post process to apply tone mapping
  90707. */
  90708. var TonemapPostProcess = /** @class */ (function (_super) {
  90709. __extends(TonemapPostProcess, _super);
  90710. /**
  90711. * Creates a new TonemapPostProcess
  90712. * @param name defines the name of the postprocess
  90713. * @param _operator defines the operator to use
  90714. * @param exposureAdjustment defines the required exposure adjustement
  90715. * @param camera defines the camera to use (can be null)
  90716. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  90717. * @param engine defines the hosting engine (can be ignore if camera is set)
  90718. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  90719. */
  90720. function TonemapPostProcess(name, _operator,
  90721. /** Defines the required exposure adjustement */
  90722. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  90723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90724. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90725. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  90726. _this._operator = _operator;
  90727. _this.exposureAdjustment = exposureAdjustment;
  90728. var defines = "#define ";
  90729. if (_this._operator === TonemappingOperator.Hable) {
  90730. defines += "HABLE_TONEMAPPING";
  90731. }
  90732. else if (_this._operator === TonemappingOperator.Reinhard) {
  90733. defines += "REINHARD_TONEMAPPING";
  90734. }
  90735. else if (_this._operator === TonemappingOperator.HejiDawson) {
  90736. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  90737. }
  90738. else if (_this._operator === TonemappingOperator.Photographic) {
  90739. defines += "PHOTOGRAPHIC_TONEMAPPING";
  90740. }
  90741. //sadly a second call to create the effect.
  90742. _this.updateEffect(defines);
  90743. _this.onApply = function (effect) {
  90744. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  90745. };
  90746. return _this;
  90747. }
  90748. return TonemapPostProcess;
  90749. }(BABYLON.PostProcess));
  90750. BABYLON.TonemapPostProcess = TonemapPostProcess;
  90751. })(BABYLON || (BABYLON = {}));
  90752. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  90753. var BABYLON;
  90754. (function (BABYLON) {
  90755. /**
  90756. * DisplayPassPostProcess which produces an output the same as it's input
  90757. */
  90758. var DisplayPassPostProcess = /** @class */ (function (_super) {
  90759. __extends(DisplayPassPostProcess, _super);
  90760. /**
  90761. * Creates the DisplayPassPostProcess
  90762. * @param name The name of the effect.
  90763. * @param options The required width/height ratio to downsize to before computing the render pass.
  90764. * @param camera The camera to apply the render pass to.
  90765. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90766. * @param engine The engine which the post process will be applied. (default: current engine)
  90767. * @param reusable If the post process can be reused on the same frame. (default: false)
  90768. */
  90769. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  90770. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  90771. }
  90772. return DisplayPassPostProcess;
  90773. }(BABYLON.PostProcess));
  90774. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  90775. })(BABYLON || (BABYLON = {}));
  90776. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  90777. var BABYLON;
  90778. (function (BABYLON) {
  90779. /**
  90780. * Extracts highlights from the image
  90781. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90782. */
  90783. var HighlightsPostProcess = /** @class */ (function (_super) {
  90784. __extends(HighlightsPostProcess, _super);
  90785. /**
  90786. * Extracts highlights from the image
  90787. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90788. * @param name The name of the effect.
  90789. * @param options The required width/height ratio to downsize to before computing the render pass.
  90790. * @param camera The camera to apply the render pass to.
  90791. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90792. * @param engine The engine which the post process will be applied. (default: current engine)
  90793. * @param reusable If the post process can be reused on the same frame. (default: false)
  90794. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  90795. */
  90796. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  90797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90798. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90799. }
  90800. return HighlightsPostProcess;
  90801. }(BABYLON.PostProcess));
  90802. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  90803. })(BABYLON || (BABYLON = {}));
  90804. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  90805. var BABYLON;
  90806. (function (BABYLON) {
  90807. /**
  90808. * ImageProcessingPostProcess
  90809. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  90810. */
  90811. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  90812. __extends(ImageProcessingPostProcess, _super);
  90813. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  90814. if (camera === void 0) { camera = null; }
  90815. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90816. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  90817. _this._fromLinearSpace = true;
  90818. /**
  90819. * Defines cache preventing GC.
  90820. */
  90821. _this._defines = {
  90822. IMAGEPROCESSING: false,
  90823. VIGNETTE: false,
  90824. VIGNETTEBLENDMODEMULTIPLY: false,
  90825. VIGNETTEBLENDMODEOPAQUE: false,
  90826. TONEMAPPING: false,
  90827. TONEMAPPING_ACES: false,
  90828. CONTRAST: false,
  90829. COLORCURVES: false,
  90830. COLORGRADING: false,
  90831. COLORGRADING3D: false,
  90832. FROMLINEARSPACE: false,
  90833. SAMPLER3DGREENDEPTH: false,
  90834. SAMPLER3DBGRMAP: false,
  90835. IMAGEPROCESSINGPOSTPROCESS: false,
  90836. EXPOSURE: false,
  90837. };
  90838. // Setup the configuration as forced by the constructor. This would then not force the
  90839. // scene materials output in linear space and let untouched the default forward pass.
  90840. if (imageProcessingConfiguration) {
  90841. imageProcessingConfiguration.applyByPostProcess = true;
  90842. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  90843. // This will cause the shader to be compiled
  90844. _this.fromLinearSpace = false;
  90845. }
  90846. // Setup the default processing configuration to the scene.
  90847. else {
  90848. _this._attachImageProcessingConfiguration(null, true);
  90849. _this.imageProcessingConfiguration.applyByPostProcess = true;
  90850. }
  90851. _this.onApply = function (effect) {
  90852. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  90853. };
  90854. return _this;
  90855. }
  90856. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  90857. /**
  90858. * Gets the image processing configuration used either in this material.
  90859. */
  90860. get: function () {
  90861. return this._imageProcessingConfiguration;
  90862. },
  90863. /**
  90864. * Sets the Default image processing configuration used either in the this material.
  90865. *
  90866. * If sets to null, the scene one is in use.
  90867. */
  90868. set: function (value) {
  90869. this._attachImageProcessingConfiguration(value);
  90870. },
  90871. enumerable: true,
  90872. configurable: true
  90873. });
  90874. /**
  90875. * Attaches a new image processing configuration to the PBR Material.
  90876. * @param configuration
  90877. */
  90878. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  90879. var _this = this;
  90880. if (doNotBuild === void 0) { doNotBuild = false; }
  90881. if (configuration === this._imageProcessingConfiguration) {
  90882. return;
  90883. }
  90884. // Detaches observer.
  90885. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90886. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90887. }
  90888. // Pick the scene configuration if needed.
  90889. if (!configuration) {
  90890. var scene = null;
  90891. var engine = this.getEngine();
  90892. var camera = this.getCamera();
  90893. if (camera) {
  90894. scene = camera.getScene();
  90895. }
  90896. else if (engine && engine.scenes) {
  90897. var scenes = engine.scenes;
  90898. scene = scenes[scenes.length - 1];
  90899. }
  90900. else {
  90901. scene = BABYLON.Engine.LastCreatedScene;
  90902. }
  90903. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  90904. }
  90905. else {
  90906. this._imageProcessingConfiguration = configuration;
  90907. }
  90908. // Attaches observer.
  90909. if (this._imageProcessingConfiguration) {
  90910. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90911. _this._updateParameters();
  90912. });
  90913. }
  90914. // Ensure the effect will be rebuilt.
  90915. if (!doNotBuild) {
  90916. this._updateParameters();
  90917. }
  90918. };
  90919. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  90920. /**
  90921. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90922. */
  90923. get: function () {
  90924. return this.imageProcessingConfiguration.colorCurves;
  90925. },
  90926. /**
  90927. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90928. */
  90929. set: function (value) {
  90930. this.imageProcessingConfiguration.colorCurves = value;
  90931. },
  90932. enumerable: true,
  90933. configurable: true
  90934. });
  90935. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  90936. /**
  90937. * Gets wether the color curves effect is enabled.
  90938. */
  90939. get: function () {
  90940. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90941. },
  90942. /**
  90943. * Sets wether the color curves effect is enabled.
  90944. */
  90945. set: function (value) {
  90946. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90947. },
  90948. enumerable: true,
  90949. configurable: true
  90950. });
  90951. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  90952. /**
  90953. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90954. */
  90955. get: function () {
  90956. return this.imageProcessingConfiguration.colorGradingTexture;
  90957. },
  90958. /**
  90959. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90960. */
  90961. set: function (value) {
  90962. this.imageProcessingConfiguration.colorGradingTexture = value;
  90963. },
  90964. enumerable: true,
  90965. configurable: true
  90966. });
  90967. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  90968. /**
  90969. * Gets wether the color grading effect is enabled.
  90970. */
  90971. get: function () {
  90972. return this.imageProcessingConfiguration.colorGradingEnabled;
  90973. },
  90974. /**
  90975. * Gets wether the color grading effect is enabled.
  90976. */
  90977. set: function (value) {
  90978. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90979. },
  90980. enumerable: true,
  90981. configurable: true
  90982. });
  90983. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  90984. /**
  90985. * Gets exposure used in the effect.
  90986. */
  90987. get: function () {
  90988. return this.imageProcessingConfiguration.exposure;
  90989. },
  90990. /**
  90991. * Sets exposure used in the effect.
  90992. */
  90993. set: function (value) {
  90994. this.imageProcessingConfiguration.exposure = value;
  90995. },
  90996. enumerable: true,
  90997. configurable: true
  90998. });
  90999. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  91000. /**
  91001. * Gets wether tonemapping is enabled or not.
  91002. */
  91003. get: function () {
  91004. return this._imageProcessingConfiguration.toneMappingEnabled;
  91005. },
  91006. /**
  91007. * Sets wether tonemapping is enabled or not
  91008. */
  91009. set: function (value) {
  91010. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91011. },
  91012. enumerable: true,
  91013. configurable: true
  91014. });
  91015. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  91016. /**
  91017. * Gets contrast used in the effect.
  91018. */
  91019. get: function () {
  91020. return this.imageProcessingConfiguration.contrast;
  91021. },
  91022. /**
  91023. * Sets contrast used in the effect.
  91024. */
  91025. set: function (value) {
  91026. this.imageProcessingConfiguration.contrast = value;
  91027. },
  91028. enumerable: true,
  91029. configurable: true
  91030. });
  91031. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91032. /**
  91033. * Gets Vignette stretch size.
  91034. */
  91035. get: function () {
  91036. return this.imageProcessingConfiguration.vignetteStretch;
  91037. },
  91038. /**
  91039. * Sets Vignette stretch size.
  91040. */
  91041. set: function (value) {
  91042. this.imageProcessingConfiguration.vignetteStretch = value;
  91043. },
  91044. enumerable: true,
  91045. configurable: true
  91046. });
  91047. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91048. /**
  91049. * Gets Vignette centre X Offset.
  91050. */
  91051. get: function () {
  91052. return this.imageProcessingConfiguration.vignetteCentreX;
  91053. },
  91054. /**
  91055. * Sets Vignette centre X Offset.
  91056. */
  91057. set: function (value) {
  91058. this.imageProcessingConfiguration.vignetteCentreX = value;
  91059. },
  91060. enumerable: true,
  91061. configurable: true
  91062. });
  91063. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91064. /**
  91065. * Gets Vignette centre Y Offset.
  91066. */
  91067. get: function () {
  91068. return this.imageProcessingConfiguration.vignetteCentreY;
  91069. },
  91070. /**
  91071. * Sets Vignette centre Y Offset.
  91072. */
  91073. set: function (value) {
  91074. this.imageProcessingConfiguration.vignetteCentreY = value;
  91075. },
  91076. enumerable: true,
  91077. configurable: true
  91078. });
  91079. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91080. /**
  91081. * Gets Vignette weight or intensity of the vignette effect.
  91082. */
  91083. get: function () {
  91084. return this.imageProcessingConfiguration.vignetteWeight;
  91085. },
  91086. /**
  91087. * Sets Vignette weight or intensity of the vignette effect.
  91088. */
  91089. set: function (value) {
  91090. this.imageProcessingConfiguration.vignetteWeight = value;
  91091. },
  91092. enumerable: true,
  91093. configurable: true
  91094. });
  91095. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91096. /**
  91097. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91098. * if vignetteEnabled is set to true.
  91099. */
  91100. get: function () {
  91101. return this.imageProcessingConfiguration.vignetteColor;
  91102. },
  91103. /**
  91104. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91105. * if vignetteEnabled is set to true.
  91106. */
  91107. set: function (value) {
  91108. this.imageProcessingConfiguration.vignetteColor = value;
  91109. },
  91110. enumerable: true,
  91111. configurable: true
  91112. });
  91113. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91114. /**
  91115. * Gets Camera field of view used by the Vignette effect.
  91116. */
  91117. get: function () {
  91118. return this.imageProcessingConfiguration.vignetteCameraFov;
  91119. },
  91120. /**
  91121. * Sets Camera field of view used by the Vignette effect.
  91122. */
  91123. set: function (value) {
  91124. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91125. },
  91126. enumerable: true,
  91127. configurable: true
  91128. });
  91129. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91130. /**
  91131. * Gets the vignette blend mode allowing different kind of effect.
  91132. */
  91133. get: function () {
  91134. return this.imageProcessingConfiguration.vignetteBlendMode;
  91135. },
  91136. /**
  91137. * Sets the vignette blend mode allowing different kind of effect.
  91138. */
  91139. set: function (value) {
  91140. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91141. },
  91142. enumerable: true,
  91143. configurable: true
  91144. });
  91145. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91146. /**
  91147. * Gets wether the vignette effect is enabled.
  91148. */
  91149. get: function () {
  91150. return this.imageProcessingConfiguration.vignetteEnabled;
  91151. },
  91152. /**
  91153. * Sets wether the vignette effect is enabled.
  91154. */
  91155. set: function (value) {
  91156. this.imageProcessingConfiguration.vignetteEnabled = value;
  91157. },
  91158. enumerable: true,
  91159. configurable: true
  91160. });
  91161. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91162. /**
  91163. * Gets wether the input of the processing is in Gamma or Linear Space.
  91164. */
  91165. get: function () {
  91166. return this._fromLinearSpace;
  91167. },
  91168. /**
  91169. * Sets wether the input of the processing is in Gamma or Linear Space.
  91170. */
  91171. set: function (value) {
  91172. if (this._fromLinearSpace === value) {
  91173. return;
  91174. }
  91175. this._fromLinearSpace = value;
  91176. this._updateParameters();
  91177. },
  91178. enumerable: true,
  91179. configurable: true
  91180. });
  91181. /**
  91182. * "ImageProcessingPostProcess"
  91183. * @returns "ImageProcessingPostProcess"
  91184. */
  91185. ImageProcessingPostProcess.prototype.getClassName = function () {
  91186. return "ImageProcessingPostProcess";
  91187. };
  91188. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91189. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91190. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91191. var defines = "";
  91192. for (var define in this._defines) {
  91193. if (this._defines[define]) {
  91194. defines += "#define " + define + ";\r\n";
  91195. }
  91196. }
  91197. var samplers = ["textureSampler"];
  91198. var uniforms = ["scale"];
  91199. if (BABYLON.ImageProcessingConfiguration) {
  91200. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91201. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91202. }
  91203. this.updateEffect(defines, uniforms, samplers);
  91204. };
  91205. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91206. _super.prototype.dispose.call(this, camera);
  91207. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91208. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91209. }
  91210. if (this._imageProcessingConfiguration) {
  91211. this.imageProcessingConfiguration.applyByPostProcess = false;
  91212. }
  91213. };
  91214. __decorate([
  91215. BABYLON.serialize()
  91216. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91217. return ImageProcessingPostProcess;
  91218. }(BABYLON.PostProcess));
  91219. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91220. })(BABYLON || (BABYLON = {}));
  91221. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  91222. var BABYLON;
  91223. (function (BABYLON) {
  91224. /**
  91225. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91226. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91227. * As an example, all you have to do is to create the post-process:
  91228. * var mb = new BABYLON.MotionBlurPostProcess(
  91229. * 'mb', // The name of the effect.
  91230. * scene, // The scene containing the objects to blur according to their velocity.
  91231. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91232. * camera // The camera to apply the render pass to.
  91233. * );
  91234. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91235. */
  91236. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91237. __extends(MotionBlurPostProcess, _super);
  91238. /**
  91239. * Creates a new instance MotionBlurPostProcess
  91240. * @param name The name of the effect.
  91241. * @param scene The scene containing the objects to blur according to their velocity.
  91242. * @param options The required width/height ratio to downsize to before computing the render pass.
  91243. * @param camera The camera to apply the render pass to.
  91244. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91245. * @param engine The engine which the post process will be applied. (default: current engine)
  91246. * @param reusable If the post process can be reused on the same frame. (default: false)
  91247. * @param textureType Type of textures used when performing the post process. (default: 0)
  91248. * @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)
  91249. */
  91250. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91252. if (blockCompilation === void 0) { blockCompilation = false; }
  91253. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  91254. /**
  91255. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91256. */
  91257. _this.motionStrength = 1;
  91258. _this._motionBlurSamples = 32;
  91259. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91260. if (_this._geometryBufferRenderer) {
  91261. if (!_this._geometryBufferRenderer.isSupported) {
  91262. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91263. _this.dispose();
  91264. return _this;
  91265. }
  91266. _this._geometryBufferRenderer.enableVelocity = true;
  91267. }
  91268. _this.onApply = function (effect) {
  91269. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91270. effect.setFloat("motionScale", scene.getAnimationRatio());
  91271. effect.setFloat("motionStrength", _this.motionStrength);
  91272. if (_this._geometryBufferRenderer) {
  91273. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91274. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91275. }
  91276. };
  91277. return _this;
  91278. }
  91279. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91280. /**
  91281. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91282. */
  91283. get: function () {
  91284. return this._motionBlurSamples;
  91285. },
  91286. /**
  91287. * Sets the number of iterations to be used for motion blur quality
  91288. */
  91289. set: function (samples) {
  91290. this._motionBlurSamples = samples;
  91291. this.updateEffect("#define SAMPLES " + samples.toFixed(1));
  91292. },
  91293. enumerable: true,
  91294. configurable: true
  91295. });
  91296. /**
  91297. * Disposes the post process.
  91298. * @param camera The camera to dispose the post process on.
  91299. */
  91300. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91301. if (this._geometryBufferRenderer) {
  91302. // Clear previous transformation matrices dictionary used to compute objects velocities
  91303. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91304. }
  91305. _super.prototype.dispose.call(this, camera);
  91306. };
  91307. return MotionBlurPostProcess;
  91308. }(BABYLON.PostProcess));
  91309. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91310. })(BABYLON || (BABYLON = {}));
  91311. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  91312. var BABYLON;
  91313. (function (BABYLON) {
  91314. /**
  91315. * Class used to store bone information
  91316. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91317. */
  91318. var Bone = /** @class */ (function (_super) {
  91319. __extends(Bone, _super);
  91320. /**
  91321. * Create a new bone
  91322. * @param name defines the bone name
  91323. * @param skeleton defines the parent skeleton
  91324. * @param parentBone defines the parent (can be null if the bone is the root)
  91325. * @param localMatrix defines the local matrix
  91326. * @param restPose defines the rest pose matrix
  91327. * @param baseMatrix defines the base matrix
  91328. * @param index defines index of the bone in the hiearchy
  91329. */
  91330. function Bone(
  91331. /**
  91332. * defines the bone name
  91333. */
  91334. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91335. if (parentBone === void 0) { parentBone = null; }
  91336. if (localMatrix === void 0) { localMatrix = null; }
  91337. if (restPose === void 0) { restPose = null; }
  91338. if (baseMatrix === void 0) { baseMatrix = null; }
  91339. if (index === void 0) { index = null; }
  91340. var _this = _super.call(this, name, skeleton.getScene()) || this;
  91341. _this.name = name;
  91342. /**
  91343. * Gets the list of child bones
  91344. */
  91345. _this.children = new Array();
  91346. /** Gets the animations associated with this bone */
  91347. _this.animations = new Array();
  91348. /**
  91349. * @hidden Internal only
  91350. * Set this value to map this bone to a different index in the transform matrices
  91351. * Set this value to -1 to exclude the bone from the transform matrices
  91352. */
  91353. _this._index = null;
  91354. _this._absoluteTransform = new BABYLON.Matrix();
  91355. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91356. _this._scalingDeterminant = 1;
  91357. _this._worldTransform = new BABYLON.Matrix();
  91358. _this._needToDecompose = true;
  91359. _this._needToCompose = false;
  91360. _this._skeleton = skeleton;
  91361. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91362. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91363. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91364. _this._index = index;
  91365. skeleton.bones.push(_this);
  91366. _this.setParent(parentBone, false);
  91367. if (baseMatrix || localMatrix) {
  91368. _this._updateDifferenceMatrix();
  91369. }
  91370. return _this;
  91371. }
  91372. Object.defineProperty(Bone.prototype, "_matrix", {
  91373. /** @hidden */
  91374. get: function () {
  91375. this._compose();
  91376. return this._localMatrix;
  91377. },
  91378. /** @hidden */
  91379. set: function (value) {
  91380. this._localMatrix.copyFrom(value);
  91381. this._needToDecompose = true;
  91382. },
  91383. enumerable: true,
  91384. configurable: true
  91385. });
  91386. // Members
  91387. /**
  91388. * Gets the parent skeleton
  91389. * @returns a skeleton
  91390. */
  91391. Bone.prototype.getSkeleton = function () {
  91392. return this._skeleton;
  91393. };
  91394. /**
  91395. * Gets parent bone
  91396. * @returns a bone or null if the bone is the root of the bone hierarchy
  91397. */
  91398. Bone.prototype.getParent = function () {
  91399. return this._parent;
  91400. };
  91401. /**
  91402. * Sets the parent bone
  91403. * @param parent defines the parent (can be null if the bone is the root)
  91404. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91405. */
  91406. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91407. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91408. if (this._parent === parent) {
  91409. return;
  91410. }
  91411. if (this._parent) {
  91412. var index = this._parent.children.indexOf(this);
  91413. if (index !== -1) {
  91414. this._parent.children.splice(index, 1);
  91415. }
  91416. }
  91417. this._parent = parent;
  91418. if (this._parent) {
  91419. this._parent.children.push(this);
  91420. }
  91421. if (updateDifferenceMatrix) {
  91422. this._updateDifferenceMatrix();
  91423. }
  91424. this.markAsDirty();
  91425. };
  91426. /**
  91427. * Gets the local matrix
  91428. * @returns a matrix
  91429. */
  91430. Bone.prototype.getLocalMatrix = function () {
  91431. this._compose();
  91432. return this._localMatrix;
  91433. };
  91434. /**
  91435. * Gets the base matrix (initial matrix which remains unchanged)
  91436. * @returns a matrix
  91437. */
  91438. Bone.prototype.getBaseMatrix = function () {
  91439. return this._baseMatrix;
  91440. };
  91441. /**
  91442. * Gets the rest pose matrix
  91443. * @returns a matrix
  91444. */
  91445. Bone.prototype.getRestPose = function () {
  91446. return this._restPose;
  91447. };
  91448. /**
  91449. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  91450. */
  91451. Bone.prototype.getWorldMatrix = function () {
  91452. return this._worldTransform;
  91453. };
  91454. /**
  91455. * Sets the local matrix to rest pose matrix
  91456. */
  91457. Bone.prototype.returnToRest = function () {
  91458. this.updateMatrix(this._restPose.clone());
  91459. };
  91460. /**
  91461. * Gets the inverse of the absolute transform matrix.
  91462. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  91463. * @returns a matrix
  91464. */
  91465. Bone.prototype.getInvertedAbsoluteTransform = function () {
  91466. return this._invertedAbsoluteTransform;
  91467. };
  91468. /**
  91469. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  91470. * @returns a matrix
  91471. */
  91472. Bone.prototype.getAbsoluteTransform = function () {
  91473. return this._absoluteTransform;
  91474. };
  91475. Object.defineProperty(Bone.prototype, "position", {
  91476. // Properties (matches AbstractMesh properties)
  91477. /** Gets or sets current position (in local space) */
  91478. get: function () {
  91479. this._decompose();
  91480. return this._localPosition;
  91481. },
  91482. set: function (newPosition) {
  91483. this._decompose();
  91484. this._localPosition.copyFrom(newPosition);
  91485. this._markAsDirtyAndCompose();
  91486. },
  91487. enumerable: true,
  91488. configurable: true
  91489. });
  91490. Object.defineProperty(Bone.prototype, "rotation", {
  91491. /** Gets or sets current rotation (in local space) */
  91492. get: function () {
  91493. return this.getRotation();
  91494. },
  91495. set: function (newRotation) {
  91496. this.setRotation(newRotation);
  91497. },
  91498. enumerable: true,
  91499. configurable: true
  91500. });
  91501. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  91502. /** Gets or sets current rotation quaternion (in local space) */
  91503. get: function () {
  91504. this._decompose();
  91505. return this._localRotation;
  91506. },
  91507. set: function (newRotation) {
  91508. this.setRotationQuaternion(newRotation);
  91509. },
  91510. enumerable: true,
  91511. configurable: true
  91512. });
  91513. Object.defineProperty(Bone.prototype, "scaling", {
  91514. /** Gets or sets current scaling (in local space) */
  91515. get: function () {
  91516. return this.getScale();
  91517. },
  91518. set: function (newScaling) {
  91519. this.setScale(newScaling);
  91520. },
  91521. enumerable: true,
  91522. configurable: true
  91523. });
  91524. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  91525. /**
  91526. * Gets the animation properties override
  91527. */
  91528. get: function () {
  91529. return this._skeleton.animationPropertiesOverride;
  91530. },
  91531. enumerable: true,
  91532. configurable: true
  91533. });
  91534. // Methods
  91535. Bone.prototype._decompose = function () {
  91536. if (!this._needToDecompose) {
  91537. return;
  91538. }
  91539. this._needToDecompose = false;
  91540. if (!this._localScaling) {
  91541. this._localScaling = BABYLON.Vector3.Zero();
  91542. this._localRotation = BABYLON.Quaternion.Zero();
  91543. this._localPosition = BABYLON.Vector3.Zero();
  91544. }
  91545. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  91546. };
  91547. Bone.prototype._compose = function () {
  91548. if (!this._needToCompose) {
  91549. return;
  91550. }
  91551. this._needToCompose = false;
  91552. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  91553. };
  91554. /**
  91555. * Update the base and local matrices
  91556. * @param matrix defines the new base or local matrix
  91557. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91558. * @param updateLocalMatrix defines if the local matrix should be updated
  91559. */
  91560. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  91561. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91562. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  91563. this._baseMatrix.copyFrom(matrix);
  91564. if (updateDifferenceMatrix) {
  91565. this._updateDifferenceMatrix();
  91566. }
  91567. if (updateLocalMatrix) {
  91568. this._localMatrix.copyFrom(matrix);
  91569. this._markAsDirtyAndDecompose();
  91570. }
  91571. else {
  91572. this.markAsDirty();
  91573. }
  91574. };
  91575. /** @hidden */
  91576. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  91577. if (updateChildren === void 0) { updateChildren = true; }
  91578. if (!rootMatrix) {
  91579. rootMatrix = this._baseMatrix;
  91580. }
  91581. if (this._parent) {
  91582. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  91583. }
  91584. else {
  91585. this._absoluteTransform.copyFrom(rootMatrix);
  91586. }
  91587. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  91588. if (updateChildren) {
  91589. for (var index = 0; index < this.children.length; index++) {
  91590. this.children[index]._updateDifferenceMatrix();
  91591. }
  91592. }
  91593. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  91594. };
  91595. /**
  91596. * Flag the bone as dirty (Forcing it to update everything)
  91597. */
  91598. Bone.prototype.markAsDirty = function () {
  91599. this._currentRenderId++;
  91600. this._childRenderId++;
  91601. this._skeleton._markAsDirty();
  91602. };
  91603. Bone.prototype._markAsDirtyAndCompose = function () {
  91604. this.markAsDirty();
  91605. this._needToCompose = true;
  91606. };
  91607. Bone.prototype._markAsDirtyAndDecompose = function () {
  91608. this.markAsDirty();
  91609. this._needToDecompose = true;
  91610. };
  91611. /**
  91612. * Copy an animation range from another bone
  91613. * @param source defines the source bone
  91614. * @param rangeName defines the range name to copy
  91615. * @param frameOffset defines the frame offset
  91616. * @param rescaleAsRequired defines if rescaling must be applied if required
  91617. * @param skelDimensionsRatio defines the scaling ratio
  91618. * @returns true if operation was successful
  91619. */
  91620. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  91621. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91622. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  91623. // all animation may be coming from a library skeleton, so may need to create animation
  91624. if (this.animations.length === 0) {
  91625. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  91626. this.animations[0].setKeys([]);
  91627. }
  91628. // get animation info / verify there is such a range from the source bone
  91629. var sourceRange = source.animations[0].getRange(rangeName);
  91630. if (!sourceRange) {
  91631. return false;
  91632. }
  91633. var from = sourceRange.from;
  91634. var to = sourceRange.to;
  91635. var sourceKeys = source.animations[0].getKeys();
  91636. // rescaling prep
  91637. var sourceBoneLength = source.length;
  91638. var sourceParent = source.getParent();
  91639. var parent = this.getParent();
  91640. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  91641. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  91642. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  91643. var destKeys = this.animations[0].getKeys();
  91644. // loop vars declaration
  91645. var orig;
  91646. var origTranslation;
  91647. var mat;
  91648. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  91649. orig = sourceKeys[key];
  91650. if (orig.frame >= from && orig.frame <= to) {
  91651. if (rescaleAsRequired) {
  91652. mat = orig.value.clone();
  91653. // scale based on parent ratio, when bone has parent
  91654. if (parentScalingReqd) {
  91655. origTranslation = mat.getTranslation();
  91656. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  91657. // scale based on skeleton dimension ratio when root bone, and value is passed
  91658. }
  91659. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  91660. origTranslation = mat.getTranslation();
  91661. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  91662. // use original when root bone, and no data for skelDimensionsRatio
  91663. }
  91664. else {
  91665. mat = orig.value;
  91666. }
  91667. }
  91668. else {
  91669. mat = orig.value;
  91670. }
  91671. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  91672. }
  91673. }
  91674. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  91675. return true;
  91676. };
  91677. /**
  91678. * Translate the bone in local or world space
  91679. * @param vec The amount to translate the bone
  91680. * @param space The space that the translation is in
  91681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91682. */
  91683. Bone.prototype.translate = function (vec, space, mesh) {
  91684. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91685. var lm = this.getLocalMatrix();
  91686. if (space == BABYLON.Space.LOCAL) {
  91687. lm.m[12] += vec.x;
  91688. lm.m[13] += vec.y;
  91689. lm.m[14] += vec.z;
  91690. }
  91691. else {
  91692. var wm = null;
  91693. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91694. if (mesh) {
  91695. wm = mesh.getWorldMatrix();
  91696. }
  91697. this._skeleton.computeAbsoluteTransforms();
  91698. var tmat = Bone._tmpMats[0];
  91699. var tvec = Bone._tmpVecs[0];
  91700. if (this._parent) {
  91701. if (mesh && wm) {
  91702. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91703. tmat.multiplyToRef(wm, tmat);
  91704. }
  91705. else {
  91706. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91707. }
  91708. }
  91709. tmat.m[12] = 0;
  91710. tmat.m[13] = 0;
  91711. tmat.m[14] = 0;
  91712. tmat.invert();
  91713. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  91714. lm.m[12] += tvec.x;
  91715. lm.m[13] += tvec.y;
  91716. lm.m[14] += tvec.z;
  91717. }
  91718. this._markAsDirtyAndDecompose();
  91719. };
  91720. /**
  91721. * Set the postion of the bone in local or world space
  91722. * @param position The position to set the bone
  91723. * @param space The space that the position is in
  91724. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91725. */
  91726. Bone.prototype.setPosition = function (position, space, mesh) {
  91727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91728. var lm = this.getLocalMatrix();
  91729. if (space == BABYLON.Space.LOCAL) {
  91730. lm.m[12] = position.x;
  91731. lm.m[13] = position.y;
  91732. lm.m[14] = position.z;
  91733. }
  91734. else {
  91735. var wm = null;
  91736. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91737. if (mesh) {
  91738. wm = mesh.getWorldMatrix();
  91739. }
  91740. this._skeleton.computeAbsoluteTransforms();
  91741. var tmat = Bone._tmpMats[0];
  91742. var vec = Bone._tmpVecs[0];
  91743. if (this._parent) {
  91744. if (mesh && wm) {
  91745. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91746. tmat.multiplyToRef(wm, tmat);
  91747. }
  91748. else {
  91749. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91750. }
  91751. }
  91752. tmat.invert();
  91753. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  91754. lm.m[12] = vec.x;
  91755. lm.m[13] = vec.y;
  91756. lm.m[14] = vec.z;
  91757. }
  91758. this._markAsDirtyAndDecompose();
  91759. };
  91760. /**
  91761. * Set the absolute position of the bone (world space)
  91762. * @param position The position to set the bone
  91763. * @param mesh The mesh that this bone is attached to
  91764. */
  91765. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  91766. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  91767. };
  91768. /**
  91769. * Scale the bone on the x, y and z axes (in local space)
  91770. * @param x The amount to scale the bone on the x axis
  91771. * @param y The amount to scale the bone on the y axis
  91772. * @param z The amount to scale the bone on the z axis
  91773. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  91774. */
  91775. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  91776. if (scaleChildren === void 0) { scaleChildren = false; }
  91777. var locMat = this.getLocalMatrix();
  91778. // Apply new scaling on top of current local matrix
  91779. var scaleMat = Bone._tmpMats[0];
  91780. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  91781. scaleMat.multiplyToRef(locMat, locMat);
  91782. // Invert scaling matrix and apply the inverse to all children
  91783. scaleMat.invert();
  91784. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  91785. var child = _a[_i];
  91786. var cm = child.getLocalMatrix();
  91787. cm.multiplyToRef(scaleMat, cm);
  91788. cm.m[12] *= x;
  91789. cm.m[13] *= y;
  91790. cm.m[14] *= z;
  91791. child._markAsDirtyAndDecompose();
  91792. }
  91793. this._markAsDirtyAndDecompose();
  91794. if (scaleChildren) {
  91795. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  91796. var child = _c[_b];
  91797. child.scale(x, y, z, scaleChildren);
  91798. }
  91799. }
  91800. };
  91801. /**
  91802. * Set the bone scaling in local space
  91803. * @param scale defines the scaling vector
  91804. */
  91805. Bone.prototype.setScale = function (scale) {
  91806. this._decompose();
  91807. this._localScaling.copyFrom(scale);
  91808. this._markAsDirtyAndCompose();
  91809. };
  91810. /**
  91811. * Gets the current scaling in local space
  91812. * @returns the current scaling vector
  91813. */
  91814. Bone.prototype.getScale = function () {
  91815. this._decompose();
  91816. return this._localScaling;
  91817. };
  91818. /**
  91819. * Gets the current scaling in local space and stores it in a target vector
  91820. * @param result defines the target vector
  91821. */
  91822. Bone.prototype.getScaleToRef = function (result) {
  91823. this._decompose();
  91824. result.copyFrom(this._localScaling);
  91825. };
  91826. /**
  91827. * Set the yaw, pitch, and roll of the bone in local or world space
  91828. * @param yaw The rotation of the bone on the y axis
  91829. * @param pitch The rotation of the bone on the x axis
  91830. * @param roll The rotation of the bone on the z axis
  91831. * @param space The space that the axes of rotation are in
  91832. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91833. */
  91834. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  91835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91836. if (space === BABYLON.Space.LOCAL) {
  91837. var quat = Bone._tmpQuat;
  91838. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  91839. this.setRotationQuaternion(quat, space, mesh);
  91840. return;
  91841. }
  91842. var rotMatInv = Bone._tmpMats[0];
  91843. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91844. return;
  91845. }
  91846. var rotMat = Bone._tmpMats[1];
  91847. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  91848. rotMatInv.multiplyToRef(rotMat, rotMat);
  91849. this._rotateWithMatrix(rotMat, space, mesh);
  91850. };
  91851. /**
  91852. * Add a rotation to the bone on an axis in local or world space
  91853. * @param axis The axis to rotate the bone on
  91854. * @param amount The amount to rotate the bone
  91855. * @param space The space that the axis is in
  91856. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91857. */
  91858. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  91859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91860. var rmat = Bone._tmpMats[0];
  91861. rmat.m[12] = 0;
  91862. rmat.m[13] = 0;
  91863. rmat.m[14] = 0;
  91864. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  91865. this._rotateWithMatrix(rmat, space, mesh);
  91866. };
  91867. /**
  91868. * Set the rotation of the bone to a particular axis angle in local or world space
  91869. * @param axis The axis to rotate the bone on
  91870. * @param angle The angle that the bone should be rotated to
  91871. * @param space The space that the axis is in
  91872. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91873. */
  91874. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  91875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91876. if (space === BABYLON.Space.LOCAL) {
  91877. var quat = Bone._tmpQuat;
  91878. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  91879. this.setRotationQuaternion(quat, space, mesh);
  91880. return;
  91881. }
  91882. var rotMatInv = Bone._tmpMats[0];
  91883. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91884. return;
  91885. }
  91886. var rotMat = Bone._tmpMats[1];
  91887. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  91888. rotMatInv.multiplyToRef(rotMat, rotMat);
  91889. this._rotateWithMatrix(rotMat, space, mesh);
  91890. };
  91891. /**
  91892. * Set the euler rotation of the bone in local of world space
  91893. * @param rotation The euler rotation that the bone should be set to
  91894. * @param space The space that the rotation is in
  91895. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91896. */
  91897. Bone.prototype.setRotation = function (rotation, space, mesh) {
  91898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91899. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  91900. };
  91901. /**
  91902. * Set the quaternion rotation of the bone in local of world space
  91903. * @param quat The quaternion rotation that the bone should be set to
  91904. * @param space The space that the rotation is in
  91905. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91906. */
  91907. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  91908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91909. if (space === BABYLON.Space.LOCAL) {
  91910. this._decompose();
  91911. this._localRotation.copyFrom(quat);
  91912. this._markAsDirtyAndCompose();
  91913. return;
  91914. }
  91915. var rotMatInv = Bone._tmpMats[0];
  91916. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91917. return;
  91918. }
  91919. var rotMat = Bone._tmpMats[1];
  91920. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  91921. rotMatInv.multiplyToRef(rotMat, rotMat);
  91922. this._rotateWithMatrix(rotMat, space, mesh);
  91923. };
  91924. /**
  91925. * Set the rotation matrix of the bone in local of world space
  91926. * @param rotMat The rotation matrix that the bone should be set to
  91927. * @param space The space that the rotation is in
  91928. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91929. */
  91930. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  91931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91932. if (space === BABYLON.Space.LOCAL) {
  91933. var quat = Bone._tmpQuat;
  91934. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  91935. this.setRotationQuaternion(quat, space, mesh);
  91936. return;
  91937. }
  91938. var rotMatInv = Bone._tmpMats[0];
  91939. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91940. return;
  91941. }
  91942. var rotMat2 = Bone._tmpMats[1];
  91943. rotMat2.copyFrom(rotMat);
  91944. rotMatInv.multiplyToRef(rotMat, rotMat2);
  91945. this._rotateWithMatrix(rotMat2, space, mesh);
  91946. };
  91947. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  91948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91949. var lmat = this.getLocalMatrix();
  91950. var lx = lmat.m[12];
  91951. var ly = lmat.m[13];
  91952. var lz = lmat.m[14];
  91953. var parent = this.getParent();
  91954. var parentScale = Bone._tmpMats[3];
  91955. var parentScaleInv = Bone._tmpMats[4];
  91956. if (parent && space == BABYLON.Space.WORLD) {
  91957. if (mesh) {
  91958. parentScale.copyFrom(mesh.getWorldMatrix());
  91959. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  91960. }
  91961. else {
  91962. parentScale.copyFrom(parent.getAbsoluteTransform());
  91963. }
  91964. parentScaleInv.copyFrom(parentScale);
  91965. parentScaleInv.invert();
  91966. lmat.multiplyToRef(parentScale, lmat);
  91967. lmat.multiplyToRef(rmat, lmat);
  91968. lmat.multiplyToRef(parentScaleInv, lmat);
  91969. }
  91970. else {
  91971. if (space == BABYLON.Space.WORLD && mesh) {
  91972. parentScale.copyFrom(mesh.getWorldMatrix());
  91973. parentScaleInv.copyFrom(parentScale);
  91974. parentScaleInv.invert();
  91975. lmat.multiplyToRef(parentScale, lmat);
  91976. lmat.multiplyToRef(rmat, lmat);
  91977. lmat.multiplyToRef(parentScaleInv, lmat);
  91978. }
  91979. else {
  91980. lmat.multiplyToRef(rmat, lmat);
  91981. }
  91982. }
  91983. lmat.m[12] = lx;
  91984. lmat.m[13] = ly;
  91985. lmat.m[14] = lz;
  91986. this.computeAbsoluteTransforms();
  91987. this._markAsDirtyAndDecompose();
  91988. };
  91989. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  91990. var scaleMatrix = Bone._tmpMats[2];
  91991. rotMatInv.copyFrom(this.getAbsoluteTransform());
  91992. if (mesh) {
  91993. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  91994. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  91995. }
  91996. rotMatInv.invert();
  91997. if (isNaN(rotMatInv.m[0])) {
  91998. // Matrix failed to invert.
  91999. // This can happen if scale is zero for example.
  92000. return false;
  92001. }
  92002. scaleMatrix.m[0] *= this._scalingDeterminant;
  92003. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  92004. return true;
  92005. };
  92006. /**
  92007. * Get the position of the bone in local or world space
  92008. * @param space The space that the returned position is in
  92009. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92010. * @returns The position of the bone
  92011. */
  92012. Bone.prototype.getPosition = function (space, mesh) {
  92013. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92014. if (mesh === void 0) { mesh = null; }
  92015. var pos = BABYLON.Vector3.Zero();
  92016. this.getPositionToRef(space, mesh, pos);
  92017. return pos;
  92018. };
  92019. /**
  92020. * Copy the position of the bone to a vector3 in local or world space
  92021. * @param space The space that the returned position is in
  92022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92023. * @param result The vector3 to copy the position to
  92024. */
  92025. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  92026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92027. if (space == BABYLON.Space.LOCAL) {
  92028. var lm = this.getLocalMatrix();
  92029. result.x = lm.m[12];
  92030. result.y = lm.m[13];
  92031. result.z = lm.m[14];
  92032. }
  92033. else {
  92034. var wm = null;
  92035. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92036. if (mesh) {
  92037. wm = mesh.getWorldMatrix();
  92038. }
  92039. this._skeleton.computeAbsoluteTransforms();
  92040. var tmat = Bone._tmpMats[0];
  92041. if (mesh && wm) {
  92042. tmat.copyFrom(this.getAbsoluteTransform());
  92043. tmat.multiplyToRef(wm, tmat);
  92044. }
  92045. else {
  92046. tmat = this.getAbsoluteTransform();
  92047. }
  92048. result.x = tmat.m[12];
  92049. result.y = tmat.m[13];
  92050. result.z = tmat.m[14];
  92051. }
  92052. };
  92053. /**
  92054. * Get the absolute position of the bone (world space)
  92055. * @param mesh The mesh that this bone is attached to
  92056. * @returns The absolute position of the bone
  92057. */
  92058. Bone.prototype.getAbsolutePosition = function (mesh) {
  92059. if (mesh === void 0) { mesh = null; }
  92060. var pos = BABYLON.Vector3.Zero();
  92061. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92062. return pos;
  92063. };
  92064. /**
  92065. * Copy the absolute position of the bone (world space) to the result param
  92066. * @param mesh The mesh that this bone is attached to
  92067. * @param result The vector3 to copy the absolute position to
  92068. */
  92069. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92070. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92071. };
  92072. /**
  92073. * Compute the absolute transforms of this bone and its children
  92074. */
  92075. Bone.prototype.computeAbsoluteTransforms = function () {
  92076. this._compose();
  92077. if (this._parent) {
  92078. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92079. }
  92080. else {
  92081. this._absoluteTransform.copyFrom(this._localMatrix);
  92082. var poseMatrix = this._skeleton.getPoseMatrix();
  92083. if (poseMatrix) {
  92084. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92085. }
  92086. }
  92087. var children = this.children;
  92088. var len = children.length;
  92089. for (var i = 0; i < len; i++) {
  92090. children[i].computeAbsoluteTransforms();
  92091. }
  92092. };
  92093. /**
  92094. * Get the world direction from an axis that is in the local space of the bone
  92095. * @param localAxis The local direction that is used to compute the world direction
  92096. * @param mesh The mesh that this bone is attached to
  92097. * @returns The world direction
  92098. */
  92099. Bone.prototype.getDirection = function (localAxis, mesh) {
  92100. if (mesh === void 0) { mesh = null; }
  92101. var result = BABYLON.Vector3.Zero();
  92102. this.getDirectionToRef(localAxis, mesh, result);
  92103. return result;
  92104. };
  92105. /**
  92106. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92107. * @param localAxis The local direction that is used to compute the world direction
  92108. * @param mesh The mesh that this bone is attached to
  92109. * @param result The vector3 that the world direction will be copied to
  92110. */
  92111. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92112. if (mesh === void 0) { mesh = null; }
  92113. var wm = null;
  92114. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92115. if (mesh) {
  92116. wm = mesh.getWorldMatrix();
  92117. }
  92118. this._skeleton.computeAbsoluteTransforms();
  92119. var mat = Bone._tmpMats[0];
  92120. mat.copyFrom(this.getAbsoluteTransform());
  92121. if (mesh && wm) {
  92122. mat.multiplyToRef(wm, mat);
  92123. }
  92124. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92125. result.normalize();
  92126. };
  92127. /**
  92128. * Get the euler rotation of the bone in local or world space
  92129. * @param space The space that the rotation should be in
  92130. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92131. * @returns The euler rotation
  92132. */
  92133. Bone.prototype.getRotation = function (space, mesh) {
  92134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92135. if (mesh === void 0) { mesh = null; }
  92136. var result = BABYLON.Vector3.Zero();
  92137. this.getRotationToRef(space, mesh, result);
  92138. return result;
  92139. };
  92140. /**
  92141. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92142. * @param space The space that the rotation should be in
  92143. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92144. * @param result The vector3 that the rotation should be copied to
  92145. */
  92146. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92148. if (mesh === void 0) { mesh = null; }
  92149. var quat = Bone._tmpQuat;
  92150. this.getRotationQuaternionToRef(space, mesh, quat);
  92151. quat.toEulerAnglesToRef(result);
  92152. };
  92153. /**
  92154. * Get the quaternion rotation of the bone in either local or world space
  92155. * @param space The space that the rotation should be in
  92156. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92157. * @returns The quaternion rotation
  92158. */
  92159. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92161. if (mesh === void 0) { mesh = null; }
  92162. var result = BABYLON.Quaternion.Identity();
  92163. this.getRotationQuaternionToRef(space, mesh, result);
  92164. return result;
  92165. };
  92166. /**
  92167. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92168. * @param space The space that the rotation should be in
  92169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92170. * @param result The quaternion that the rotation should be copied to
  92171. */
  92172. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92174. if (mesh === void 0) { mesh = null; }
  92175. if (space == BABYLON.Space.LOCAL) {
  92176. this._decompose();
  92177. result.copyFrom(this._localRotation);
  92178. }
  92179. else {
  92180. var mat = Bone._tmpMats[0];
  92181. var amat = this.getAbsoluteTransform();
  92182. if (mesh) {
  92183. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92184. }
  92185. else {
  92186. mat.copyFrom(amat);
  92187. }
  92188. mat.m[0] *= this._scalingDeterminant;
  92189. mat.m[1] *= this._scalingDeterminant;
  92190. mat.m[2] *= this._scalingDeterminant;
  92191. mat.decompose(undefined, result, undefined);
  92192. }
  92193. };
  92194. /**
  92195. * Get the rotation matrix of the bone in local or world space
  92196. * @param space The space that the rotation should be in
  92197. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92198. * @returns The rotation matrix
  92199. */
  92200. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92201. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92202. var result = BABYLON.Matrix.Identity();
  92203. this.getRotationMatrixToRef(space, mesh, result);
  92204. return result;
  92205. };
  92206. /**
  92207. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  92208. * @param space The space that the rotation should be in
  92209. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92210. * @param result The quaternion that the rotation should be copied to
  92211. */
  92212. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92214. if (space == BABYLON.Space.LOCAL) {
  92215. this.getLocalMatrix().getRotationMatrixToRef(result);
  92216. }
  92217. else {
  92218. var mat = Bone._tmpMats[0];
  92219. var amat = this.getAbsoluteTransform();
  92220. if (mesh) {
  92221. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92222. }
  92223. else {
  92224. mat.copyFrom(amat);
  92225. }
  92226. mat.m[0] *= this._scalingDeterminant;
  92227. mat.m[1] *= this._scalingDeterminant;
  92228. mat.m[2] *= this._scalingDeterminant;
  92229. mat.getRotationMatrixToRef(result);
  92230. }
  92231. };
  92232. /**
  92233. * Get the world position of a point that is in the local space of the bone
  92234. * @param position The local position
  92235. * @param mesh The mesh that this bone is attached to
  92236. * @returns The world position
  92237. */
  92238. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92239. if (mesh === void 0) { mesh = null; }
  92240. var result = BABYLON.Vector3.Zero();
  92241. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92242. return result;
  92243. };
  92244. /**
  92245. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92246. * @param position The local position
  92247. * @param mesh The mesh that this bone is attached to
  92248. * @param result The vector3 that the world position should be copied to
  92249. */
  92250. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92251. if (mesh === void 0) { mesh = null; }
  92252. var wm = null;
  92253. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92254. if (mesh) {
  92255. wm = mesh.getWorldMatrix();
  92256. }
  92257. this._skeleton.computeAbsoluteTransforms();
  92258. var tmat = Bone._tmpMats[0];
  92259. if (mesh && wm) {
  92260. tmat.copyFrom(this.getAbsoluteTransform());
  92261. tmat.multiplyToRef(wm, tmat);
  92262. }
  92263. else {
  92264. tmat = this.getAbsoluteTransform();
  92265. }
  92266. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92267. };
  92268. /**
  92269. * Get the local position of a point that is in world space
  92270. * @param position The world position
  92271. * @param mesh The mesh that this bone is attached to
  92272. * @returns The local position
  92273. */
  92274. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92275. if (mesh === void 0) { mesh = null; }
  92276. var result = BABYLON.Vector3.Zero();
  92277. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92278. return result;
  92279. };
  92280. /**
  92281. * Get the local position of a point that is in world space and copy it to the result param
  92282. * @param position The world position
  92283. * @param mesh The mesh that this bone is attached to
  92284. * @param result The vector3 that the local position should be copied to
  92285. */
  92286. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92287. if (mesh === void 0) { mesh = null; }
  92288. var wm = null;
  92289. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92290. if (mesh) {
  92291. wm = mesh.getWorldMatrix();
  92292. }
  92293. this._skeleton.computeAbsoluteTransforms();
  92294. var tmat = Bone._tmpMats[0];
  92295. tmat.copyFrom(this.getAbsoluteTransform());
  92296. if (mesh && wm) {
  92297. tmat.multiplyToRef(wm, tmat);
  92298. }
  92299. tmat.invert();
  92300. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92301. };
  92302. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92303. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92304. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92305. return Bone;
  92306. }(BABYLON.Node));
  92307. BABYLON.Bone = Bone;
  92308. })(BABYLON || (BABYLON = {}));
  92309. //# sourceMappingURL=babylon.bone.js.map
  92310. var BABYLON;
  92311. (function (BABYLON) {
  92312. /**
  92313. * Class used to apply inverse kinematics to bones
  92314. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92315. */
  92316. var BoneIKController = /** @class */ (function () {
  92317. /**
  92318. * Creates a new BoneIKController
  92319. * @param mesh defines the mesh to control
  92320. * @param bone defines the bone to control
  92321. * @param options defines options to set up the controller
  92322. */
  92323. function BoneIKController(mesh, bone, options) {
  92324. /**
  92325. * Gets or sets the target position
  92326. */
  92327. this.targetPosition = BABYLON.Vector3.Zero();
  92328. /**
  92329. * Gets or sets the pole target position
  92330. */
  92331. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92332. /**
  92333. * Gets or sets the pole target local offset
  92334. */
  92335. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92336. /**
  92337. * Gets or sets the pole angle
  92338. */
  92339. this.poleAngle = 0;
  92340. /**
  92341. * 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)
  92342. */
  92343. this.slerpAmount = 1;
  92344. this._bone1Quat = BABYLON.Quaternion.Identity();
  92345. this._bone1Mat = BABYLON.Matrix.Identity();
  92346. this._bone2Ang = Math.PI;
  92347. this._maxAngle = Math.PI;
  92348. this._rightHandedSystem = false;
  92349. this._bendAxis = BABYLON.Vector3.Right();
  92350. this._slerping = false;
  92351. this._adjustRoll = 0;
  92352. this._bone2 = bone;
  92353. this._bone1 = bone.getParent();
  92354. if (!this._bone1) {
  92355. return;
  92356. }
  92357. this.mesh = mesh;
  92358. var bonePos = bone.getPosition();
  92359. if (bone.getAbsoluteTransform().determinant() > 0) {
  92360. this._rightHandedSystem = true;
  92361. this._bendAxis.x = 0;
  92362. this._bendAxis.y = 0;
  92363. this._bendAxis.z = -1;
  92364. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92365. this._adjustRoll = Math.PI * .5;
  92366. this._bendAxis.z = 1;
  92367. }
  92368. }
  92369. if (this._bone1.length) {
  92370. var boneScale1 = this._bone1.getScale();
  92371. var boneScale2 = this._bone2.getScale();
  92372. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92373. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92374. }
  92375. else if (this._bone1.children[0]) {
  92376. mesh.computeWorldMatrix(true);
  92377. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92378. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92379. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92380. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92381. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92382. }
  92383. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92384. this.maxAngle = Math.PI;
  92385. if (options) {
  92386. if (options.targetMesh) {
  92387. this.targetMesh = options.targetMesh;
  92388. this.targetMesh.computeWorldMatrix(true);
  92389. }
  92390. if (options.poleTargetMesh) {
  92391. this.poleTargetMesh = options.poleTargetMesh;
  92392. this.poleTargetMesh.computeWorldMatrix(true);
  92393. }
  92394. else if (options.poleTargetBone) {
  92395. this.poleTargetBone = options.poleTargetBone;
  92396. }
  92397. else if (this._bone1.getParent()) {
  92398. this.poleTargetBone = this._bone1.getParent();
  92399. }
  92400. if (options.poleTargetLocalOffset) {
  92401. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92402. }
  92403. if (options.poleAngle) {
  92404. this.poleAngle = options.poleAngle;
  92405. }
  92406. if (options.bendAxis) {
  92407. this._bendAxis.copyFrom(options.bendAxis);
  92408. }
  92409. if (options.maxAngle) {
  92410. this.maxAngle = options.maxAngle;
  92411. }
  92412. if (options.slerpAmount) {
  92413. this.slerpAmount = options.slerpAmount;
  92414. }
  92415. }
  92416. }
  92417. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92418. /**
  92419. * Gets or sets maximum allowed angle
  92420. */
  92421. get: function () {
  92422. return this._maxAngle;
  92423. },
  92424. set: function (value) {
  92425. this._setMaxAngle(value);
  92426. },
  92427. enumerable: true,
  92428. configurable: true
  92429. });
  92430. BoneIKController.prototype._setMaxAngle = function (ang) {
  92431. if (ang < 0) {
  92432. ang = 0;
  92433. }
  92434. if (ang > Math.PI || ang == undefined) {
  92435. ang = Math.PI;
  92436. }
  92437. this._maxAngle = ang;
  92438. var a = this._bone1Length;
  92439. var b = this._bone2Length;
  92440. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  92441. };
  92442. /**
  92443. * Force the controller to update the bones
  92444. */
  92445. BoneIKController.prototype.update = function () {
  92446. var bone1 = this._bone1;
  92447. if (!bone1) {
  92448. return;
  92449. }
  92450. var target = this.targetPosition;
  92451. var poleTarget = this.poleTargetPosition;
  92452. var mat1 = BoneIKController._tmpMats[0];
  92453. var mat2 = BoneIKController._tmpMats[1];
  92454. if (this.targetMesh) {
  92455. target.copyFrom(this.targetMesh.getAbsolutePosition());
  92456. }
  92457. if (this.poleTargetBone) {
  92458. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  92459. }
  92460. else if (this.poleTargetMesh) {
  92461. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  92462. }
  92463. var bonePos = BoneIKController._tmpVecs[0];
  92464. var zaxis = BoneIKController._tmpVecs[1];
  92465. var xaxis = BoneIKController._tmpVecs[2];
  92466. var yaxis = BoneIKController._tmpVecs[3];
  92467. var upAxis = BoneIKController._tmpVecs[4];
  92468. var _tmpQuat = BoneIKController._tmpQuat;
  92469. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  92470. poleTarget.subtractToRef(bonePos, upAxis);
  92471. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  92472. upAxis.y = 1;
  92473. }
  92474. else {
  92475. upAxis.normalize();
  92476. }
  92477. target.subtractToRef(bonePos, yaxis);
  92478. yaxis.normalize();
  92479. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  92480. zaxis.normalize();
  92481. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  92482. xaxis.normalize();
  92483. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  92484. var a = this._bone1Length;
  92485. var b = this._bone2Length;
  92486. var c = BABYLON.Vector3.Distance(bonePos, target);
  92487. if (this._maxReach > 0) {
  92488. c = Math.min(this._maxReach, c);
  92489. }
  92490. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  92491. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  92492. if (acosa > 1) {
  92493. acosa = 1;
  92494. }
  92495. if (acosb > 1) {
  92496. acosb = 1;
  92497. }
  92498. if (acosa < -1) {
  92499. acosa = -1;
  92500. }
  92501. if (acosb < -1) {
  92502. acosb = -1;
  92503. }
  92504. var angA = Math.acos(acosa);
  92505. var angB = Math.acos(acosb);
  92506. var angC = -angA - angB;
  92507. if (this._rightHandedSystem) {
  92508. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  92509. mat2.multiplyToRef(mat1, mat1);
  92510. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  92511. mat2.multiplyToRef(mat1, mat1);
  92512. }
  92513. else {
  92514. var _tmpVec = BoneIKController._tmpVecs[5];
  92515. _tmpVec.copyFrom(this._bendAxis);
  92516. _tmpVec.x *= -1;
  92517. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  92518. mat2.multiplyToRef(mat1, mat1);
  92519. }
  92520. if (this.poleAngle) {
  92521. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  92522. mat1.multiplyToRef(mat2, mat1);
  92523. }
  92524. if (this._bone1) {
  92525. if (this.slerpAmount < 1) {
  92526. if (!this._slerping) {
  92527. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  92528. }
  92529. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  92530. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  92531. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  92532. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  92533. this._slerping = true;
  92534. }
  92535. else {
  92536. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  92537. this._bone1Mat.copyFrom(mat1);
  92538. this._slerping = false;
  92539. }
  92540. }
  92541. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  92542. this._bone2Ang = angC;
  92543. };
  92544. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92545. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  92546. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  92547. return BoneIKController;
  92548. }());
  92549. BABYLON.BoneIKController = BoneIKController;
  92550. })(BABYLON || (BABYLON = {}));
  92551. //# sourceMappingURL=babylon.boneIKController.js.map
  92552. var BABYLON;
  92553. (function (BABYLON) {
  92554. /**
  92555. * Class used to make a bone look toward a point in space
  92556. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  92557. */
  92558. var BoneLookController = /** @class */ (function () {
  92559. /**
  92560. * Create a BoneLookController
  92561. * @param mesh the mesh that the bone belongs to
  92562. * @param bone the bone that will be looking to the target
  92563. * @param target the target Vector3 to look at
  92564. * @param settings optional settings:
  92565. * * maxYaw: the maximum angle the bone will yaw to
  92566. * * minYaw: the minimum angle the bone will yaw to
  92567. * * maxPitch: the maximum angle the bone will pitch to
  92568. * * minPitch: the minimum angle the bone will yaw to
  92569. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  92570. * * upAxis: the up axis of the coordinate system
  92571. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  92572. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  92573. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  92574. * * adjustYaw: used to make an adjustment to the yaw of the bone
  92575. * * adjustPitch: used to make an adjustment to the pitch of the bone
  92576. * * adjustRoll: used to make an adjustment to the roll of the bone
  92577. **/
  92578. function BoneLookController(mesh, bone, target, options) {
  92579. /**
  92580. * The up axis of the coordinate system that is used when the bone is rotated
  92581. */
  92582. this.upAxis = BABYLON.Vector3.Up();
  92583. /**
  92584. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  92585. */
  92586. this.upAxisSpace = BABYLON.Space.LOCAL;
  92587. /**
  92588. * Used to make an adjustment to the yaw of the bone
  92589. */
  92590. this.adjustYaw = 0;
  92591. /**
  92592. * Used to make an adjustment to the pitch of the bone
  92593. */
  92594. this.adjustPitch = 0;
  92595. /**
  92596. * Used to make an adjustment to the roll of the bone
  92597. */
  92598. this.adjustRoll = 0;
  92599. /**
  92600. * 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)
  92601. */
  92602. this.slerpAmount = 1;
  92603. this._boneQuat = BABYLON.Quaternion.Identity();
  92604. this._slerping = false;
  92605. this._firstFrameSkipped = false;
  92606. this._fowardAxis = BABYLON.Vector3.Forward();
  92607. this.mesh = mesh;
  92608. this.bone = bone;
  92609. this.target = target;
  92610. if (options) {
  92611. if (options.adjustYaw) {
  92612. this.adjustYaw = options.adjustYaw;
  92613. }
  92614. if (options.adjustPitch) {
  92615. this.adjustPitch = options.adjustPitch;
  92616. }
  92617. if (options.adjustRoll) {
  92618. this.adjustRoll = options.adjustRoll;
  92619. }
  92620. if (options.maxYaw != null) {
  92621. this.maxYaw = options.maxYaw;
  92622. }
  92623. else {
  92624. this.maxYaw = Math.PI;
  92625. }
  92626. if (options.minYaw != null) {
  92627. this.minYaw = options.minYaw;
  92628. }
  92629. else {
  92630. this.minYaw = -Math.PI;
  92631. }
  92632. if (options.maxPitch != null) {
  92633. this.maxPitch = options.maxPitch;
  92634. }
  92635. else {
  92636. this.maxPitch = Math.PI;
  92637. }
  92638. if (options.minPitch != null) {
  92639. this.minPitch = options.minPitch;
  92640. }
  92641. else {
  92642. this.minPitch = -Math.PI;
  92643. }
  92644. if (options.slerpAmount != null) {
  92645. this.slerpAmount = options.slerpAmount;
  92646. }
  92647. if (options.upAxis != null) {
  92648. this.upAxis = options.upAxis;
  92649. }
  92650. if (options.upAxisSpace != null) {
  92651. this.upAxisSpace = options.upAxisSpace;
  92652. }
  92653. if (options.yawAxis != null || options.pitchAxis != null) {
  92654. var newYawAxis = BABYLON.Axis.Y;
  92655. var newPitchAxis = BABYLON.Axis.X;
  92656. if (options.yawAxis != null) {
  92657. newYawAxis = options.yawAxis.clone();
  92658. newYawAxis.normalize();
  92659. }
  92660. if (options.pitchAxis != null) {
  92661. newPitchAxis = options.pitchAxis.clone();
  92662. newPitchAxis.normalize();
  92663. }
  92664. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  92665. this._transformYawPitch = BABYLON.Matrix.Identity();
  92666. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  92667. this._transformYawPitchInv = this._transformYawPitch.clone();
  92668. this._transformYawPitch.invert();
  92669. }
  92670. }
  92671. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  92672. this.upAxisSpace = BABYLON.Space.LOCAL;
  92673. }
  92674. }
  92675. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  92676. /**
  92677. * Gets or sets the minimum yaw angle that the bone can look to
  92678. */
  92679. get: function () {
  92680. return this._minYaw;
  92681. },
  92682. set: function (value) {
  92683. this._minYaw = value;
  92684. this._minYawSin = Math.sin(value);
  92685. this._minYawCos = Math.cos(value);
  92686. if (this._maxYaw != null) {
  92687. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92688. this._yawRange = this._maxYaw - this._minYaw;
  92689. }
  92690. },
  92691. enumerable: true,
  92692. configurable: true
  92693. });
  92694. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  92695. /**
  92696. * Gets or sets the maximum yaw angle that the bone can look to
  92697. */
  92698. get: function () {
  92699. return this._maxYaw;
  92700. },
  92701. set: function (value) {
  92702. this._maxYaw = value;
  92703. this._maxYawSin = Math.sin(value);
  92704. this._maxYawCos = Math.cos(value);
  92705. if (this._minYaw != null) {
  92706. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92707. this._yawRange = this._maxYaw - this._minYaw;
  92708. }
  92709. },
  92710. enumerable: true,
  92711. configurable: true
  92712. });
  92713. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  92714. /**
  92715. * Gets or sets the minimum pitch angle that the bone can look to
  92716. */
  92717. get: function () {
  92718. return this._minPitch;
  92719. },
  92720. set: function (value) {
  92721. this._minPitch = value;
  92722. this._minPitchTan = Math.tan(value);
  92723. },
  92724. enumerable: true,
  92725. configurable: true
  92726. });
  92727. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  92728. /**
  92729. * Gets or sets the maximum pitch angle that the bone can look to
  92730. */
  92731. get: function () {
  92732. return this._maxPitch;
  92733. },
  92734. set: function (value) {
  92735. this._maxPitch = value;
  92736. this._maxPitchTan = Math.tan(value);
  92737. },
  92738. enumerable: true,
  92739. configurable: true
  92740. });
  92741. /**
  92742. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  92743. */
  92744. BoneLookController.prototype.update = function () {
  92745. //skip the first frame when slerping so that the mesh rotation is correct
  92746. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  92747. this._firstFrameSkipped = true;
  92748. return;
  92749. }
  92750. var bone = this.bone;
  92751. var bonePos = BoneLookController._tmpVecs[0];
  92752. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  92753. var target = this.target;
  92754. var _tmpMat1 = BoneLookController._tmpMats[0];
  92755. var _tmpMat2 = BoneLookController._tmpMats[1];
  92756. var mesh = this.mesh;
  92757. var parentBone = bone.getParent();
  92758. var upAxis = BoneLookController._tmpVecs[1];
  92759. upAxis.copyFrom(this.upAxis);
  92760. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  92761. if (this._transformYawPitch) {
  92762. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  92763. }
  92764. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  92765. }
  92766. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  92767. mesh.getDirectionToRef(upAxis, upAxis);
  92768. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  92769. upAxis.normalize();
  92770. }
  92771. }
  92772. var checkYaw = false;
  92773. var checkPitch = false;
  92774. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  92775. checkYaw = true;
  92776. }
  92777. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  92778. checkPitch = true;
  92779. }
  92780. if (checkYaw || checkPitch) {
  92781. var spaceMat = BoneLookController._tmpMats[2];
  92782. var spaceMatInv = BoneLookController._tmpMats[3];
  92783. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  92784. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  92785. }
  92786. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  92787. spaceMat.copyFrom(mesh.getWorldMatrix());
  92788. }
  92789. else {
  92790. var forwardAxis = BoneLookController._tmpVecs[2];
  92791. forwardAxis.copyFrom(this._fowardAxis);
  92792. if (this._transformYawPitch) {
  92793. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  92794. }
  92795. if (parentBone) {
  92796. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  92797. }
  92798. else {
  92799. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  92800. }
  92801. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  92802. rightAxis.normalize();
  92803. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  92804. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  92805. }
  92806. spaceMat.invertToRef(spaceMatInv);
  92807. var xzlen = null;
  92808. if (checkPitch) {
  92809. var localTarget = BoneLookController._tmpVecs[3];
  92810. target.subtractToRef(bonePos, localTarget);
  92811. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92812. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92813. var pitch = Math.atan2(localTarget.y, xzlen);
  92814. var newPitch = pitch;
  92815. if (pitch > this._maxPitch) {
  92816. localTarget.y = this._maxPitchTan * xzlen;
  92817. newPitch = this._maxPitch;
  92818. }
  92819. else if (pitch < this._minPitch) {
  92820. localTarget.y = this._minPitchTan * xzlen;
  92821. newPitch = this._minPitch;
  92822. }
  92823. if (pitch != newPitch) {
  92824. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92825. localTarget.addInPlace(bonePos);
  92826. target = localTarget;
  92827. }
  92828. }
  92829. if (checkYaw) {
  92830. var localTarget = BoneLookController._tmpVecs[4];
  92831. target.subtractToRef(bonePos, localTarget);
  92832. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92833. var yaw = Math.atan2(localTarget.x, localTarget.z);
  92834. var newYaw = yaw;
  92835. if (yaw > this._maxYaw || yaw < this._minYaw) {
  92836. if (xzlen == null) {
  92837. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92838. }
  92839. if (this._yawRange > Math.PI) {
  92840. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  92841. localTarget.z = this._maxYawCos * xzlen;
  92842. localTarget.x = this._maxYawSin * xzlen;
  92843. newYaw = this._maxYaw;
  92844. }
  92845. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  92846. localTarget.z = this._minYawCos * xzlen;
  92847. localTarget.x = this._minYawSin * xzlen;
  92848. newYaw = this._minYaw;
  92849. }
  92850. }
  92851. else {
  92852. if (yaw > this._maxYaw) {
  92853. localTarget.z = this._maxYawCos * xzlen;
  92854. localTarget.x = this._maxYawSin * xzlen;
  92855. newYaw = this._maxYaw;
  92856. }
  92857. else if (yaw < this._minYaw) {
  92858. localTarget.z = this._minYawCos * xzlen;
  92859. localTarget.x = this._minYawSin * xzlen;
  92860. newYaw = this._minYaw;
  92861. }
  92862. }
  92863. }
  92864. if (this._slerping && this._yawRange > Math.PI) {
  92865. //are we going to be crossing into the min/max region?
  92866. var boneFwd = BoneLookController._tmpVecs[8];
  92867. boneFwd.copyFrom(BABYLON.Axis.Z);
  92868. if (this._transformYawPitch) {
  92869. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  92870. }
  92871. var boneRotMat = BoneLookController._tmpMats[4];
  92872. this._boneQuat.toRotationMatrix(boneRotMat);
  92873. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  92874. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  92875. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  92876. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  92877. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  92878. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  92879. if (angBtwTar > angBtwMidYaw) {
  92880. if (xzlen == null) {
  92881. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92882. }
  92883. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  92884. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  92885. if (angBtwMin < angBtwMax) {
  92886. newYaw = boneYaw + Math.PI * .75;
  92887. localTarget.z = Math.cos(newYaw) * xzlen;
  92888. localTarget.x = Math.sin(newYaw) * xzlen;
  92889. }
  92890. else {
  92891. newYaw = boneYaw - Math.PI * .75;
  92892. localTarget.z = Math.cos(newYaw) * xzlen;
  92893. localTarget.x = Math.sin(newYaw) * xzlen;
  92894. }
  92895. }
  92896. }
  92897. if (yaw != newYaw) {
  92898. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92899. localTarget.addInPlace(bonePos);
  92900. target = localTarget;
  92901. }
  92902. }
  92903. }
  92904. var zaxis = BoneLookController._tmpVecs[5];
  92905. var xaxis = BoneLookController._tmpVecs[6];
  92906. var yaxis = BoneLookController._tmpVecs[7];
  92907. var _tmpQuat = BoneLookController._tmpQuat;
  92908. target.subtractToRef(bonePos, zaxis);
  92909. zaxis.normalize();
  92910. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  92911. xaxis.normalize();
  92912. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  92913. yaxis.normalize();
  92914. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  92915. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  92916. return;
  92917. }
  92918. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  92919. return;
  92920. }
  92921. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  92922. return;
  92923. }
  92924. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  92925. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  92926. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  92927. }
  92928. if (this.slerpAmount < 1) {
  92929. if (!this._slerping) {
  92930. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  92931. }
  92932. if (this._transformYawPitch) {
  92933. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92934. }
  92935. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  92936. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  92937. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  92938. this._slerping = true;
  92939. }
  92940. else {
  92941. if (this._transformYawPitch) {
  92942. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92943. }
  92944. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  92945. this._slerping = false;
  92946. }
  92947. };
  92948. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  92949. var angDiff = ang2 - ang1;
  92950. angDiff %= Math.PI * 2;
  92951. if (angDiff > Math.PI) {
  92952. angDiff -= Math.PI * 2;
  92953. }
  92954. else if (angDiff < -Math.PI) {
  92955. angDiff += Math.PI * 2;
  92956. }
  92957. return angDiff;
  92958. };
  92959. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  92960. ang1 %= (2 * Math.PI);
  92961. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  92962. ang2 %= (2 * Math.PI);
  92963. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  92964. var ab = 0;
  92965. if (ang1 < ang2) {
  92966. ab = ang2 - ang1;
  92967. }
  92968. else {
  92969. ab = ang1 - ang2;
  92970. }
  92971. if (ab > Math.PI) {
  92972. ab = Math.PI * 2 - ab;
  92973. }
  92974. return ab;
  92975. };
  92976. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  92977. ang %= (2 * Math.PI);
  92978. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  92979. ang1 %= (2 * Math.PI);
  92980. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  92981. ang2 %= (2 * Math.PI);
  92982. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  92983. if (ang1 < ang2) {
  92984. if (ang > ang1 && ang < ang2) {
  92985. return true;
  92986. }
  92987. }
  92988. else {
  92989. if (ang > ang2 && ang < ang1) {
  92990. return true;
  92991. }
  92992. }
  92993. return false;
  92994. };
  92995. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  92996. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  92997. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92998. return BoneLookController;
  92999. }());
  93000. BABYLON.BoneLookController = BoneLookController;
  93001. })(BABYLON || (BABYLON = {}));
  93002. //# sourceMappingURL=babylon.boneLookController.js.map
  93003. var BABYLON;
  93004. (function (BABYLON) {
  93005. /**
  93006. * Class used to handle skinning animations
  93007. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  93008. */
  93009. var Skeleton = /** @class */ (function () {
  93010. /**
  93011. * Creates a new skeleton
  93012. * @param name defines the skeleton name
  93013. * @param id defines the skeleton Id
  93014. * @param scene defines the hosting scene
  93015. */
  93016. function Skeleton(
  93017. /** defines the skeleton name */
  93018. name,
  93019. /** defines the skeleton Id */
  93020. id, scene) {
  93021. this.name = name;
  93022. this.id = id;
  93023. /**
  93024. * Gets the list of child bones
  93025. */
  93026. this.bones = new Array();
  93027. /**
  93028. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  93029. */
  93030. this.needInitialSkinMatrix = false;
  93031. this._isDirty = true;
  93032. this._meshesWithPoseMatrix = new Array();
  93033. this._identity = BABYLON.Matrix.Identity();
  93034. this._ranges = {};
  93035. this._lastAbsoluteTransformsUpdateId = -1;
  93036. /**
  93037. * Specifies if the skeleton should be serialized
  93038. */
  93039. this.doNotSerialize = false;
  93040. this._animationPropertiesOverride = null;
  93041. // Events
  93042. /**
  93043. * An observable triggered before computing the skeleton's matrices
  93044. */
  93045. this.onBeforeComputeObservable = new BABYLON.Observable();
  93046. this.bones = [];
  93047. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93048. scene.skeletons.push(this);
  93049. //make sure it will recalculate the matrix next time prepare is called.
  93050. this._isDirty = true;
  93051. }
  93052. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93053. /**
  93054. * Gets or sets the animation properties override
  93055. */
  93056. get: function () {
  93057. if (!this._animationPropertiesOverride) {
  93058. return this._scene.animationPropertiesOverride;
  93059. }
  93060. return this._animationPropertiesOverride;
  93061. },
  93062. set: function (value) {
  93063. this._animationPropertiesOverride = value;
  93064. },
  93065. enumerable: true,
  93066. configurable: true
  93067. });
  93068. // Members
  93069. /**
  93070. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93071. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93072. * @returns a Float32Array containing matrices data
  93073. */
  93074. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93075. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93076. return mesh._bonesTransformMatrices;
  93077. }
  93078. if (!this._transformMatrices) {
  93079. this.prepare();
  93080. }
  93081. return this._transformMatrices;
  93082. };
  93083. /**
  93084. * Gets the current hosting scene
  93085. * @returns a scene object
  93086. */
  93087. Skeleton.prototype.getScene = function () {
  93088. return this._scene;
  93089. };
  93090. // Methods
  93091. /**
  93092. * Gets a string representing the current skeleton data
  93093. * @param fullDetails defines a boolean indicating if we want a verbose version
  93094. * @returns a string representing the current skeleton data
  93095. */
  93096. Skeleton.prototype.toString = function (fullDetails) {
  93097. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93098. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93099. if (fullDetails) {
  93100. ret += ", Ranges: {";
  93101. var first = true;
  93102. for (var name_1 in this._ranges) {
  93103. if (first) {
  93104. ret += ", ";
  93105. first = false;
  93106. }
  93107. ret += name_1;
  93108. }
  93109. ret += "}";
  93110. }
  93111. return ret;
  93112. };
  93113. /**
  93114. * Get bone's index searching by name
  93115. * @param name defines bone's name to search for
  93116. * @return the indice of the bone. Returns -1 if not found
  93117. */
  93118. Skeleton.prototype.getBoneIndexByName = function (name) {
  93119. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93120. if (this.bones[boneIndex].name === name) {
  93121. return boneIndex;
  93122. }
  93123. }
  93124. return -1;
  93125. };
  93126. /**
  93127. * Creater a new animation range
  93128. * @param name defines the name of the range
  93129. * @param from defines the start key
  93130. * @param to defines the end key
  93131. */
  93132. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93133. // check name not already in use
  93134. if (!this._ranges[name]) {
  93135. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93136. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93137. if (this.bones[i].animations[0]) {
  93138. this.bones[i].animations[0].createRange(name, from, to);
  93139. }
  93140. }
  93141. }
  93142. };
  93143. /**
  93144. * Delete a specific animation range
  93145. * @param name defines the name of the range
  93146. * @param deleteFrames defines if frames must be removed as well
  93147. */
  93148. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93149. if (deleteFrames === void 0) { deleteFrames = true; }
  93150. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93151. if (this.bones[i].animations[0]) {
  93152. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93153. }
  93154. }
  93155. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93156. };
  93157. /**
  93158. * Gets a specific animation range
  93159. * @param name defines the name of the range to look for
  93160. * @returns the requested animation range or null if not found
  93161. */
  93162. Skeleton.prototype.getAnimationRange = function (name) {
  93163. return this._ranges[name];
  93164. };
  93165. /**
  93166. * Gets the list of all animation ranges defined on this skeleton
  93167. * @returns an array
  93168. */
  93169. Skeleton.prototype.getAnimationRanges = function () {
  93170. var animationRanges = [];
  93171. var name;
  93172. var i = 0;
  93173. for (name in this._ranges) {
  93174. animationRanges[i] = this._ranges[name];
  93175. i++;
  93176. }
  93177. return animationRanges;
  93178. };
  93179. /**
  93180. * Copy animation range from a source skeleton.
  93181. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93182. * @param source defines the source skeleton
  93183. * @param name defines the name of the range to copy
  93184. * @param rescaleAsRequired defines if rescaling must be applied if required
  93185. * @returns true if operation was successful
  93186. */
  93187. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93188. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93189. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93190. return false;
  93191. }
  93192. var ret = true;
  93193. var frameOffset = this._getHighestAnimationFrame() + 1;
  93194. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93195. var boneDict = {};
  93196. var sourceBones = source.bones;
  93197. var nBones;
  93198. var i;
  93199. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93200. boneDict[sourceBones[i].name] = sourceBones[i];
  93201. }
  93202. if (this.bones.length !== sourceBones.length) {
  93203. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93204. ret = false;
  93205. }
  93206. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93207. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93208. var boneName = this.bones[i].name;
  93209. var sourceBone = boneDict[boneName];
  93210. if (sourceBone) {
  93211. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93212. }
  93213. else {
  93214. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93215. ret = false;
  93216. }
  93217. }
  93218. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93219. var range = source.getAnimationRange(name);
  93220. if (range) {
  93221. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93222. }
  93223. return ret;
  93224. };
  93225. /**
  93226. * Forces the skeleton to go to rest pose
  93227. */
  93228. Skeleton.prototype.returnToRest = function () {
  93229. for (var index = 0; index < this.bones.length; index++) {
  93230. this.bones[index].returnToRest();
  93231. }
  93232. };
  93233. Skeleton.prototype._getHighestAnimationFrame = function () {
  93234. var ret = 0;
  93235. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93236. if (this.bones[i].animations[0]) {
  93237. var highest = this.bones[i].animations[0].getHighestFrame();
  93238. if (ret < highest) {
  93239. ret = highest;
  93240. }
  93241. }
  93242. }
  93243. return ret;
  93244. };
  93245. /**
  93246. * Begin a specific animation range
  93247. * @param name defines the name of the range to start
  93248. * @param loop defines if looping must be turned on (false by default)
  93249. * @param speedRatio defines the speed ratio to apply (1 by default)
  93250. * @param onAnimationEnd defines a callback which will be called when animation will end
  93251. * @returns a new animatable
  93252. */
  93253. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93254. var range = this.getAnimationRange(name);
  93255. if (!range) {
  93256. return null;
  93257. }
  93258. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93259. };
  93260. /** @hidden */
  93261. Skeleton.prototype._markAsDirty = function () {
  93262. this._isDirty = true;
  93263. };
  93264. /** @hidden */
  93265. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93266. this._meshesWithPoseMatrix.push(mesh);
  93267. };
  93268. /** @hidden */
  93269. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93270. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93271. if (index > -1) {
  93272. this._meshesWithPoseMatrix.splice(index, 1);
  93273. }
  93274. };
  93275. /** @hidden */
  93276. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93277. this.onBeforeComputeObservable.notifyObservers(this);
  93278. for (var index = 0; index < this.bones.length; index++) {
  93279. var bone = this.bones[index];
  93280. var parentBone = bone.getParent();
  93281. if (parentBone) {
  93282. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93283. }
  93284. else {
  93285. if (initialSkinMatrix) {
  93286. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93287. }
  93288. else {
  93289. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93290. }
  93291. }
  93292. if (bone._index !== -1) {
  93293. var mappedIndex = bone._index === null ? index : bone._index;
  93294. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93295. }
  93296. }
  93297. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93298. };
  93299. /**
  93300. * Build all resources required to render a skeleton
  93301. */
  93302. Skeleton.prototype.prepare = function () {
  93303. if (!this._isDirty) {
  93304. return;
  93305. }
  93306. if (this.needInitialSkinMatrix) {
  93307. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93308. var mesh = this._meshesWithPoseMatrix[index];
  93309. var poseMatrix = mesh.getPoseMatrix();
  93310. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93311. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93312. }
  93313. if (this._synchronizedWithMesh !== mesh) {
  93314. this._synchronizedWithMesh = mesh;
  93315. // Prepare bones
  93316. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93317. var bone = this.bones[boneIndex];
  93318. if (!bone.getParent()) {
  93319. var matrix = bone.getBaseMatrix();
  93320. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93321. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93322. }
  93323. }
  93324. }
  93325. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93326. }
  93327. }
  93328. else {
  93329. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93330. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93331. }
  93332. this._computeTransformMatrices(this._transformMatrices, null);
  93333. }
  93334. this._isDirty = false;
  93335. this._scene._activeBones.addCount(this.bones.length, false);
  93336. };
  93337. /**
  93338. * Gets the list of animatables currently running for this skeleton
  93339. * @returns an array of animatables
  93340. */
  93341. Skeleton.prototype.getAnimatables = function () {
  93342. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93343. this._animatables = [];
  93344. for (var index = 0; index < this.bones.length; index++) {
  93345. this._animatables.push(this.bones[index]);
  93346. }
  93347. }
  93348. return this._animatables;
  93349. };
  93350. /**
  93351. * Clone the current skeleton
  93352. * @param name defines the name of the new skeleton
  93353. * @param id defines the id of the enw skeleton
  93354. * @returns the new skeleton
  93355. */
  93356. Skeleton.prototype.clone = function (name, id) {
  93357. var result = new Skeleton(name, id || name, this._scene);
  93358. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93359. for (var index = 0; index < this.bones.length; index++) {
  93360. var source = this.bones[index];
  93361. var parentBone = null;
  93362. var parent_1 = source.getParent();
  93363. if (parent_1) {
  93364. var parentIndex = this.bones.indexOf(parent_1);
  93365. parentBone = result.bones[parentIndex];
  93366. }
  93367. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93368. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93369. }
  93370. if (this._ranges) {
  93371. result._ranges = {};
  93372. for (var rangeName in this._ranges) {
  93373. var range = this._ranges[rangeName];
  93374. if (range) {
  93375. result._ranges[rangeName] = range.clone();
  93376. }
  93377. }
  93378. }
  93379. this._isDirty = true;
  93380. return result;
  93381. };
  93382. /**
  93383. * Enable animation blending for this skeleton
  93384. * @param blendingSpeed defines the blending speed to apply
  93385. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93386. */
  93387. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93388. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93389. this.bones.forEach(function (bone) {
  93390. bone.animations.forEach(function (animation) {
  93391. animation.enableBlending = true;
  93392. animation.blendingSpeed = blendingSpeed;
  93393. });
  93394. });
  93395. };
  93396. /**
  93397. * Releases all resources associated with the current skeleton
  93398. */
  93399. Skeleton.prototype.dispose = function () {
  93400. this._meshesWithPoseMatrix = [];
  93401. // Animations
  93402. this.getScene().stopAnimation(this);
  93403. // Remove from scene
  93404. this.getScene().removeSkeleton(this);
  93405. };
  93406. /**
  93407. * Serialize the skeleton in a JSON object
  93408. * @returns a JSON object
  93409. */
  93410. Skeleton.prototype.serialize = function () {
  93411. var serializationObject = {};
  93412. serializationObject.name = this.name;
  93413. serializationObject.id = this.id;
  93414. if (this.dimensionsAtRest) {
  93415. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  93416. }
  93417. serializationObject.bones = [];
  93418. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93419. for (var index = 0; index < this.bones.length; index++) {
  93420. var bone = this.bones[index];
  93421. var parent_2 = bone.getParent();
  93422. var serializedBone = {
  93423. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  93424. name: bone.name,
  93425. matrix: bone.getBaseMatrix().toArray(),
  93426. rest: bone.getRestPose().toArray()
  93427. };
  93428. serializationObject.bones.push(serializedBone);
  93429. if (bone.length) {
  93430. serializedBone.length = bone.length;
  93431. }
  93432. if (bone.metadata) {
  93433. serializedBone.metadata = bone.metadata;
  93434. }
  93435. if (bone.animations && bone.animations.length > 0) {
  93436. serializedBone.animation = bone.animations[0].serialize();
  93437. }
  93438. serializationObject.ranges = [];
  93439. for (var name in this._ranges) {
  93440. var source = this._ranges[name];
  93441. if (!source) {
  93442. continue;
  93443. }
  93444. var range = {};
  93445. range.name = name;
  93446. range.from = source.from;
  93447. range.to = source.to;
  93448. serializationObject.ranges.push(range);
  93449. }
  93450. }
  93451. return serializationObject;
  93452. };
  93453. /**
  93454. * Creates a new skeleton from serialized data
  93455. * @param parsedSkeleton defines the serialized data
  93456. * @param scene defines the hosting scene
  93457. * @returns a new skeleton
  93458. */
  93459. Skeleton.Parse = function (parsedSkeleton, scene) {
  93460. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  93461. if (parsedSkeleton.dimensionsAtRest) {
  93462. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  93463. }
  93464. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  93465. var index;
  93466. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  93467. var parsedBone = parsedSkeleton.bones[index];
  93468. var parentBone = null;
  93469. if (parsedBone.parentBoneIndex > -1) {
  93470. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  93471. }
  93472. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  93473. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  93474. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  93475. bone.id = parsedBone.id;
  93476. }
  93477. if (parsedBone.length) {
  93478. bone.length = parsedBone.length;
  93479. }
  93480. if (parsedBone.metadata) {
  93481. bone.metadata = parsedBone.metadata;
  93482. }
  93483. if (parsedBone.animation) {
  93484. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  93485. }
  93486. }
  93487. // placed after bones, so createAnimationRange can cascade down
  93488. if (parsedSkeleton.ranges) {
  93489. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  93490. var data = parsedSkeleton.ranges[index];
  93491. skeleton.createAnimationRange(data.name, data.from, data.to);
  93492. }
  93493. }
  93494. return skeleton;
  93495. };
  93496. /**
  93497. * Compute all node absolute transforms
  93498. * @param forceUpdate defines if computation must be done even if cache is up to date
  93499. */
  93500. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  93501. if (forceUpdate === void 0) { forceUpdate = false; }
  93502. var renderId = this._scene.getRenderId();
  93503. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  93504. this.bones[0].computeAbsoluteTransforms();
  93505. this._lastAbsoluteTransformsUpdateId = renderId;
  93506. }
  93507. };
  93508. /**
  93509. * Gets the root pose matrix
  93510. * @returns a matrix
  93511. */
  93512. Skeleton.prototype.getPoseMatrix = function () {
  93513. var poseMatrix = null;
  93514. if (this._meshesWithPoseMatrix.length > 0) {
  93515. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  93516. }
  93517. return poseMatrix;
  93518. };
  93519. /**
  93520. * Sorts bones per internal index
  93521. */
  93522. Skeleton.prototype.sortBones = function () {
  93523. var bones = new Array();
  93524. var visited = new Array(this.bones.length);
  93525. for (var index = 0; index < this.bones.length; index++) {
  93526. this._sortBones(index, bones, visited);
  93527. }
  93528. this.bones = bones;
  93529. };
  93530. Skeleton.prototype._sortBones = function (index, bones, visited) {
  93531. if (visited[index]) {
  93532. return;
  93533. }
  93534. visited[index] = true;
  93535. var bone = this.bones[index];
  93536. if (bone._index === undefined) {
  93537. bone._index = index;
  93538. }
  93539. var parentBone = bone.getParent();
  93540. if (parentBone) {
  93541. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  93542. }
  93543. bones.push(bone);
  93544. };
  93545. return Skeleton;
  93546. }());
  93547. BABYLON.Skeleton = Skeleton;
  93548. })(BABYLON || (BABYLON = {}));
  93549. //# sourceMappingURL=babylon.skeleton.js.map
  93550. var BABYLON;
  93551. (function (BABYLON) {
  93552. /**
  93553. * This groups tools to convert HDR texture to native colors array.
  93554. */
  93555. var HDRTools = /** @class */ (function () {
  93556. function HDRTools() {
  93557. }
  93558. HDRTools.Ldexp = function (mantissa, exponent) {
  93559. if (exponent > 1023) {
  93560. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  93561. }
  93562. if (exponent < -1074) {
  93563. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  93564. }
  93565. return mantissa * Math.pow(2, exponent);
  93566. };
  93567. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  93568. if (exponent > 0) { /*nonzero pixel*/
  93569. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  93570. float32array[index + 0] = red * exponent;
  93571. float32array[index + 1] = green * exponent;
  93572. float32array[index + 2] = blue * exponent;
  93573. }
  93574. else {
  93575. float32array[index + 0] = 0;
  93576. float32array[index + 1] = 0;
  93577. float32array[index + 2] = 0;
  93578. }
  93579. };
  93580. HDRTools.readStringLine = function (uint8array, startIndex) {
  93581. var line = "";
  93582. var character = "";
  93583. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  93584. character = String.fromCharCode(uint8array[i]);
  93585. if (character == "\n") {
  93586. break;
  93587. }
  93588. line += character;
  93589. }
  93590. return line;
  93591. };
  93592. /**
  93593. * Reads header information from an RGBE texture stored in a native array.
  93594. * More information on this format are available here:
  93595. * https://en.wikipedia.org/wiki/RGBE_image_format
  93596. *
  93597. * @param uint8array The binary file stored in native array.
  93598. * @return The header information.
  93599. */
  93600. HDRTools.RGBE_ReadHeader = function (uint8array) {
  93601. var height = 0;
  93602. var width = 0;
  93603. var line = this.readStringLine(uint8array, 0);
  93604. if (line[0] != '#' || line[1] != '?') {
  93605. throw "Bad HDR Format.";
  93606. }
  93607. var endOfHeader = false;
  93608. var findFormat = false;
  93609. var lineIndex = 0;
  93610. do {
  93611. lineIndex += (line.length + 1);
  93612. line = this.readStringLine(uint8array, lineIndex);
  93613. if (line == "FORMAT=32-bit_rle_rgbe") {
  93614. findFormat = true;
  93615. }
  93616. else if (line.length == 0) {
  93617. endOfHeader = true;
  93618. }
  93619. } while (!endOfHeader);
  93620. if (!findFormat) {
  93621. throw "HDR Bad header format, unsupported FORMAT";
  93622. }
  93623. lineIndex += (line.length + 1);
  93624. line = this.readStringLine(uint8array, lineIndex);
  93625. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  93626. var match = sizeRegexp.exec(line);
  93627. // TODO. Support +Y and -X if needed.
  93628. if (!match || match.length < 3) {
  93629. throw "HDR Bad header format, no size";
  93630. }
  93631. width = parseInt(match[2]);
  93632. height = parseInt(match[1]);
  93633. if (width < 8 || width > 0x7fff) {
  93634. throw "HDR Bad header format, unsupported size";
  93635. }
  93636. lineIndex += (line.length + 1);
  93637. return {
  93638. height: height,
  93639. width: width,
  93640. dataPosition: lineIndex
  93641. };
  93642. };
  93643. /**
  93644. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  93645. * This RGBE texture needs to store the information as a panorama.
  93646. *
  93647. * More information on this format are available here:
  93648. * https://en.wikipedia.org/wiki/RGBE_image_format
  93649. *
  93650. * @param buffer The binary file stored in an array buffer.
  93651. * @param size The expected size of the extracted cubemap.
  93652. * @return The Cube Map information.
  93653. */
  93654. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  93655. var uint8array = new Uint8Array(buffer);
  93656. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  93657. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93658. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  93659. return cubeMapData;
  93660. };
  93661. /**
  93662. * Returns the pixels data extracted from an RGBE texture.
  93663. * This pixels will be stored left to right up to down in the R G B order in one array.
  93664. *
  93665. * More information on this format are available here:
  93666. * https://en.wikipedia.org/wiki/RGBE_image_format
  93667. *
  93668. * @param uint8array The binary file stored in an array buffer.
  93669. * @param hdrInfo The header information of the file.
  93670. * @return The pixels data in RGB right to left up to down order.
  93671. */
  93672. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  93673. // Keep for multi format supports.
  93674. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93675. };
  93676. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  93677. var num_scanlines = hdrInfo.height;
  93678. var scanline_width = hdrInfo.width;
  93679. var a, b, c, d, count;
  93680. var dataIndex = hdrInfo.dataPosition;
  93681. var index = 0, endIndex = 0, i = 0;
  93682. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  93683. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  93684. // 3 channels of 4 bytes per pixel in float.
  93685. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  93686. var resultArray = new Float32Array(resultBuffer);
  93687. // read in each successive scanline
  93688. while (num_scanlines > 0) {
  93689. a = uint8array[dataIndex++];
  93690. b = uint8array[dataIndex++];
  93691. c = uint8array[dataIndex++];
  93692. d = uint8array[dataIndex++];
  93693. if (a != 2 || b != 2 || (c & 0x80)) {
  93694. // this file is not run length encoded
  93695. throw "HDR Bad header format, not RLE";
  93696. }
  93697. if (((c << 8) | d) != scanline_width) {
  93698. throw "HDR Bad header format, wrong scan line width";
  93699. }
  93700. index = 0;
  93701. // read each of the four channels for the scanline into the buffer
  93702. for (i = 0; i < 4; i++) {
  93703. endIndex = (i + 1) * scanline_width;
  93704. while (index < endIndex) {
  93705. a = uint8array[dataIndex++];
  93706. b = uint8array[dataIndex++];
  93707. if (a > 128) {
  93708. // a run of the same value
  93709. count = a - 128;
  93710. if ((count == 0) || (count > endIndex - index)) {
  93711. throw "HDR Bad Format, bad scanline data (run)";
  93712. }
  93713. while (count-- > 0) {
  93714. scanLineArray[index++] = b;
  93715. }
  93716. }
  93717. else {
  93718. // a non-run
  93719. count = a;
  93720. if ((count == 0) || (count > endIndex - index)) {
  93721. throw "HDR Bad Format, bad scanline data (non-run)";
  93722. }
  93723. scanLineArray[index++] = b;
  93724. if (--count > 0) {
  93725. for (var j = 0; j < count; j++) {
  93726. scanLineArray[index++] = uint8array[dataIndex++];
  93727. }
  93728. }
  93729. }
  93730. }
  93731. }
  93732. // now convert data from buffer into floats
  93733. for (i = 0; i < scanline_width; i++) {
  93734. a = scanLineArray[i];
  93735. b = scanLineArray[i + scanline_width];
  93736. c = scanLineArray[i + 2 * scanline_width];
  93737. d = scanLineArray[i + 3 * scanline_width];
  93738. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  93739. }
  93740. num_scanlines--;
  93741. }
  93742. return resultArray;
  93743. };
  93744. return HDRTools;
  93745. }());
  93746. BABYLON.HDRTools = HDRTools;
  93747. })(BABYLON || (BABYLON = {}));
  93748. //# sourceMappingURL=babylon.hdr.js.map
  93749. var BABYLON;
  93750. (function (BABYLON) {
  93751. /**
  93752. * This represents a texture coming from an HDR input.
  93753. *
  93754. * The only supported format is currently panorama picture stored in RGBE format.
  93755. * Example of such files can be found on HDRLib: http://hdrlib.com/
  93756. */
  93757. var HDRCubeTexture = /** @class */ (function (_super) {
  93758. __extends(HDRCubeTexture, _super);
  93759. /**
  93760. * Instantiates an HDRTexture from the following parameters.
  93761. *
  93762. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  93763. * @param scene The scene the texture will be used in
  93764. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  93765. * @param noMipmap Forces to not generate the mipmap if true
  93766. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  93767. * @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)
  93768. * @param reserved Reserved flag for internal use.
  93769. */
  93770. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  93771. if (noMipmap === void 0) { noMipmap = false; }
  93772. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93773. if (gammaSpace === void 0) { gammaSpace = false; }
  93774. if (reserved === void 0) { reserved = false; }
  93775. if (onLoad === void 0) { onLoad = null; }
  93776. if (onError === void 0) { onError = null; }
  93777. var _this = _super.call(this, scene) || this;
  93778. _this._generateHarmonics = true;
  93779. _this._onLoad = null;
  93780. _this._onError = null;
  93781. /**
  93782. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  93783. */
  93784. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  93785. _this._isBlocking = true;
  93786. _this._rotationY = 0;
  93787. /**
  93788. * Gets or sets the center of the bounding box associated with the cube texture
  93789. * It must define where the camera used to render the texture was set
  93790. */
  93791. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  93792. if (!url) {
  93793. return _this;
  93794. }
  93795. _this.name = url;
  93796. _this.url = url;
  93797. _this.hasAlpha = false;
  93798. _this.isCube = true;
  93799. _this._textureMatrix = BABYLON.Matrix.Identity();
  93800. _this._onLoad = onLoad;
  93801. _this._onError = onError;
  93802. _this.gammaSpace = gammaSpace;
  93803. _this._noMipmap = noMipmap;
  93804. _this._size = size;
  93805. _this._texture = _this._getFromCache(url, _this._noMipmap);
  93806. if (!_this._texture) {
  93807. if (!scene.useDelayedTextureLoading) {
  93808. _this.loadTexture();
  93809. }
  93810. else {
  93811. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  93812. }
  93813. }
  93814. return _this;
  93815. }
  93816. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  93817. /**
  93818. * Gets wether or not the texture is blocking during loading.
  93819. */
  93820. get: function () {
  93821. return this._isBlocking;
  93822. },
  93823. /**
  93824. * Sets wether or not the texture is blocking during loading.
  93825. */
  93826. set: function (value) {
  93827. this._isBlocking = value;
  93828. },
  93829. enumerable: true,
  93830. configurable: true
  93831. });
  93832. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  93833. /**
  93834. * Gets texture matrix rotation angle around Y axis radians.
  93835. */
  93836. get: function () {
  93837. return this._rotationY;
  93838. },
  93839. /**
  93840. * Sets texture matrix rotation angle around Y axis in radians.
  93841. */
  93842. set: function (value) {
  93843. this._rotationY = value;
  93844. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  93845. },
  93846. enumerable: true,
  93847. configurable: true
  93848. });
  93849. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  93850. get: function () {
  93851. return this._boundingBoxSize;
  93852. },
  93853. /**
  93854. * Gets or sets the size of the bounding box associated with the cube texture
  93855. * When defined, the cubemap will switch to local mode
  93856. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  93857. * @example https://www.babylonjs-playground.com/#RNASML
  93858. */
  93859. set: function (value) {
  93860. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  93861. return;
  93862. }
  93863. this._boundingBoxSize = value;
  93864. var scene = this.getScene();
  93865. if (scene) {
  93866. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  93867. }
  93868. },
  93869. enumerable: true,
  93870. configurable: true
  93871. });
  93872. /**
  93873. * Occurs when the file is raw .hdr file.
  93874. */
  93875. HDRCubeTexture.prototype.loadTexture = function () {
  93876. var _this = this;
  93877. var callback = function (buffer) {
  93878. _this.lodGenerationOffset = 0.0;
  93879. _this.lodGenerationScale = 0.8;
  93880. var scene = _this.getScene();
  93881. if (!scene) {
  93882. return null;
  93883. }
  93884. // Extract the raw linear data.
  93885. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  93886. // Generate harmonics if needed.
  93887. if (_this._generateHarmonics) {
  93888. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  93889. _this.sphericalPolynomial = sphericalPolynomial;
  93890. }
  93891. var results = [];
  93892. var byteArray = null;
  93893. // Push each faces.
  93894. for (var j = 0; j < 6; j++) {
  93895. // Create uintarray fallback.
  93896. if (!scene.getEngine().getCaps().textureFloat) {
  93897. // 3 channels of 1 bytes per pixel in bytes.
  93898. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  93899. byteArray = new Uint8Array(byteBuffer);
  93900. }
  93901. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  93902. // If special cases.
  93903. if (_this.gammaSpace || byteArray) {
  93904. for (var i = 0; i < _this._size * _this._size; i++) {
  93905. // Put in gamma space if requested.
  93906. if (_this.gammaSpace) {
  93907. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  93908. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  93909. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  93910. }
  93911. // Convert to int texture for fallback.
  93912. if (byteArray) {
  93913. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  93914. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  93915. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  93916. // May use luminance instead if the result is not accurate.
  93917. var max = Math.max(Math.max(r, g), b);
  93918. if (max > 255) {
  93919. var scale = 255 / max;
  93920. r *= scale;
  93921. g *= scale;
  93922. b *= scale;
  93923. }
  93924. byteArray[(i * 3) + 0] = r;
  93925. byteArray[(i * 3) + 1] = g;
  93926. byteArray[(i * 3) + 2] = b;
  93927. }
  93928. }
  93929. }
  93930. if (byteArray) {
  93931. results.push(byteArray);
  93932. }
  93933. else {
  93934. results.push(dataFace);
  93935. }
  93936. }
  93937. return results;
  93938. };
  93939. var scene = this.getScene();
  93940. if (scene) {
  93941. 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);
  93942. }
  93943. };
  93944. HDRCubeTexture.prototype.clone = function () {
  93945. var scene = this.getScene();
  93946. if (!scene) {
  93947. return this;
  93948. }
  93949. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  93950. // Base texture
  93951. newTexture.level = this.level;
  93952. newTexture.wrapU = this.wrapU;
  93953. newTexture.wrapV = this.wrapV;
  93954. newTexture.coordinatesIndex = this.coordinatesIndex;
  93955. newTexture.coordinatesMode = this.coordinatesMode;
  93956. return newTexture;
  93957. };
  93958. // Methods
  93959. HDRCubeTexture.prototype.delayLoad = function () {
  93960. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  93961. return;
  93962. }
  93963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  93964. this._texture = this._getFromCache(this.url, this._noMipmap);
  93965. if (!this._texture) {
  93966. this.loadTexture();
  93967. }
  93968. };
  93969. /**
  93970. * Get the texture reflection matrix used to rotate/transform the reflection.
  93971. * @returns the reflection matrix
  93972. */
  93973. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  93974. return this._textureMatrix;
  93975. };
  93976. /**
  93977. * Set the texture reflection matrix used to rotate/transform the reflection.
  93978. * @param value Define the reflection matrix to set
  93979. */
  93980. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  93981. this._textureMatrix = value;
  93982. };
  93983. /**
  93984. * Parses a JSON representation of an HDR Texture in order to create the texture
  93985. * @param parsedTexture Define the JSON representation
  93986. * @param scene Define the scene the texture should be created in
  93987. * @param rootUrl Define the root url in case we need to load relative dependencies
  93988. * @returns the newly created texture after parsing
  93989. */
  93990. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  93991. var texture = null;
  93992. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  93993. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  93994. texture.name = parsedTexture.name;
  93995. texture.hasAlpha = parsedTexture.hasAlpha;
  93996. texture.level = parsedTexture.level;
  93997. texture.coordinatesMode = parsedTexture.coordinatesMode;
  93998. texture.isBlocking = parsedTexture.isBlocking;
  93999. }
  94000. if (texture) {
  94001. if (parsedTexture.boundingBoxPosition) {
  94002. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94003. }
  94004. if (parsedTexture.boundingBoxSize) {
  94005. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94006. }
  94007. if (parsedTexture.rotationY) {
  94008. texture.rotationY = parsedTexture.rotationY;
  94009. }
  94010. }
  94011. return texture;
  94012. };
  94013. HDRCubeTexture.prototype.serialize = function () {
  94014. if (!this.name) {
  94015. return null;
  94016. }
  94017. var serializationObject = {};
  94018. serializationObject.name = this.name;
  94019. serializationObject.hasAlpha = this.hasAlpha;
  94020. serializationObject.isCube = true;
  94021. serializationObject.level = this.level;
  94022. serializationObject.size = this._size;
  94023. serializationObject.coordinatesMode = this.coordinatesMode;
  94024. serializationObject.useInGammaSpace = this.gammaSpace;
  94025. serializationObject.generateHarmonics = this._generateHarmonics;
  94026. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94027. serializationObject.noMipmap = this._noMipmap;
  94028. serializationObject.isBlocking = this._isBlocking;
  94029. serializationObject.rotationY = this._rotationY;
  94030. return serializationObject;
  94031. };
  94032. HDRCubeTexture._facesMapping = [
  94033. "right",
  94034. "left",
  94035. "up",
  94036. "down",
  94037. "front",
  94038. "back"
  94039. ];
  94040. return HDRCubeTexture;
  94041. }(BABYLON.BaseTexture));
  94042. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94043. })(BABYLON || (BABYLON = {}));
  94044. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  94045. var BABYLON;
  94046. (function (BABYLON) {
  94047. /**
  94048. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94049. */
  94050. var PanoramaToCubeMapTools = /** @class */ (function () {
  94051. function PanoramaToCubeMapTools() {
  94052. }
  94053. /**
  94054. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94055. *
  94056. * @param float32Array The source data.
  94057. * @param inputWidth The width of the input panorama.
  94058. * @param inputHeight The height of the input panorama.
  94059. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94060. * @return The cubemap data
  94061. */
  94062. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94063. if (!float32Array) {
  94064. throw "ConvertPanoramaToCubemap: input cannot be null";
  94065. }
  94066. if (float32Array.length != inputWidth * inputHeight * 3) {
  94067. throw "ConvertPanoramaToCubemap: input size is wrong";
  94068. }
  94069. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94070. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94071. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94072. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94073. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94074. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94075. return {
  94076. front: textureFront,
  94077. back: textureBack,
  94078. left: textureLeft,
  94079. right: textureRight,
  94080. up: textureUp,
  94081. down: textureDown,
  94082. size: size,
  94083. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94084. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94085. gammaSpace: false,
  94086. };
  94087. };
  94088. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94089. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94090. var textureArray = new Float32Array(buffer);
  94091. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94092. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94093. var dy = 1 / texSize;
  94094. var fy = 0;
  94095. for (var y = 0; y < texSize; y++) {
  94096. var xv1 = faceData[0];
  94097. var xv2 = faceData[2];
  94098. for (var x = 0; x < texSize; x++) {
  94099. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94100. v.normalize();
  94101. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94102. // 3 channels per pixels
  94103. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94104. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94105. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94106. xv1 = xv1.add(rotDX1);
  94107. xv2 = xv2.add(rotDX2);
  94108. }
  94109. fy += dy;
  94110. }
  94111. return textureArray;
  94112. };
  94113. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94114. var theta = Math.atan2(vDir.z, vDir.x);
  94115. var phi = Math.acos(vDir.y);
  94116. while (theta < -Math.PI) {
  94117. theta += 2 * Math.PI;
  94118. }
  94119. while (theta > Math.PI) {
  94120. theta -= 2 * Math.PI;
  94121. }
  94122. var dx = theta / Math.PI;
  94123. var dy = phi / Math.PI;
  94124. // recenter.
  94125. dx = dx * 0.5 + 0.5;
  94126. var px = Math.round(dx * inputWidth);
  94127. if (px < 0) {
  94128. px = 0;
  94129. }
  94130. else if (px >= inputWidth) {
  94131. px = inputWidth - 1;
  94132. }
  94133. var py = Math.round(dy * inputHeight);
  94134. if (py < 0) {
  94135. py = 0;
  94136. }
  94137. else if (py >= inputHeight) {
  94138. py = inputHeight - 1;
  94139. }
  94140. var inputY = (inputHeight - py - 1);
  94141. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94142. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94143. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94144. return {
  94145. r: r,
  94146. g: g,
  94147. b: b
  94148. };
  94149. };
  94150. PanoramaToCubeMapTools.FACE_FRONT = [
  94151. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94152. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94153. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94154. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94155. ];
  94156. PanoramaToCubeMapTools.FACE_BACK = [
  94157. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94158. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94159. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94160. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94161. ];
  94162. PanoramaToCubeMapTools.FACE_RIGHT = [
  94163. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94164. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94165. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94166. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94167. ];
  94168. PanoramaToCubeMapTools.FACE_LEFT = [
  94169. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94170. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94171. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94172. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94173. ];
  94174. PanoramaToCubeMapTools.FACE_DOWN = [
  94175. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94176. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94177. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94178. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94179. ];
  94180. PanoramaToCubeMapTools.FACE_UP = [
  94181. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94182. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94183. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94184. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94185. ];
  94186. return PanoramaToCubeMapTools;
  94187. }());
  94188. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94189. })(BABYLON || (BABYLON = {}));
  94190. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  94191. var BABYLON;
  94192. (function (BABYLON) {
  94193. /**
  94194. * Vector2 wth index property
  94195. */
  94196. var IndexedVector2 = /** @class */ (function (_super) {
  94197. __extends(IndexedVector2, _super);
  94198. function IndexedVector2(original,
  94199. /** Index of the vector2 */
  94200. index) {
  94201. var _this = _super.call(this, original.x, original.y) || this;
  94202. _this.index = index;
  94203. return _this;
  94204. }
  94205. return IndexedVector2;
  94206. }(BABYLON.Vector2));
  94207. /**
  94208. * Defines points to create a polygon
  94209. */
  94210. var PolygonPoints = /** @class */ (function () {
  94211. function PolygonPoints() {
  94212. this.elements = new Array();
  94213. }
  94214. PolygonPoints.prototype.add = function (originalPoints) {
  94215. var _this = this;
  94216. var result = new Array();
  94217. originalPoints.forEach(function (point) {
  94218. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94219. var newPoint = new IndexedVector2(point, _this.elements.length);
  94220. result.push(newPoint);
  94221. _this.elements.push(newPoint);
  94222. }
  94223. });
  94224. return result;
  94225. };
  94226. PolygonPoints.prototype.computeBounds = function () {
  94227. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94228. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94229. this.elements.forEach(function (point) {
  94230. // x
  94231. if (point.x < lmin.x) {
  94232. lmin.x = point.x;
  94233. }
  94234. else if (point.x > lmax.x) {
  94235. lmax.x = point.x;
  94236. }
  94237. // y
  94238. if (point.y < lmin.y) {
  94239. lmin.y = point.y;
  94240. }
  94241. else if (point.y > lmax.y) {
  94242. lmax.y = point.y;
  94243. }
  94244. });
  94245. return {
  94246. min: lmin,
  94247. max: lmax,
  94248. width: lmax.x - lmin.x,
  94249. height: lmax.y - lmin.y
  94250. };
  94251. };
  94252. return PolygonPoints;
  94253. }());
  94254. /**
  94255. * Polygon
  94256. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94257. */
  94258. var Polygon = /** @class */ (function () {
  94259. function Polygon() {
  94260. }
  94261. /**
  94262. * Creates a rectangle
  94263. * @param xmin bottom X coord
  94264. * @param ymin bottom Y coord
  94265. * @param xmax top X coord
  94266. * @param ymax top Y coord
  94267. * @returns points that make the resulting rectation
  94268. */
  94269. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94270. return [
  94271. new BABYLON.Vector2(xmin, ymin),
  94272. new BABYLON.Vector2(xmax, ymin),
  94273. new BABYLON.Vector2(xmax, ymax),
  94274. new BABYLON.Vector2(xmin, ymax)
  94275. ];
  94276. };
  94277. /**
  94278. * Creates a circle
  94279. * @param radius radius of circle
  94280. * @param cx scale in x
  94281. * @param cy scale in y
  94282. * @param numberOfSides number of sides that make up the circle
  94283. * @returns points that make the resulting circle
  94284. */
  94285. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94286. if (cx === void 0) { cx = 0; }
  94287. if (cy === void 0) { cy = 0; }
  94288. if (numberOfSides === void 0) { numberOfSides = 32; }
  94289. var result = new Array();
  94290. var angle = 0;
  94291. var increment = (Math.PI * 2) / numberOfSides;
  94292. for (var i = 0; i < numberOfSides; i++) {
  94293. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94294. angle -= increment;
  94295. }
  94296. return result;
  94297. };
  94298. /**
  94299. * Creates a polygon from input string
  94300. * @param input Input polygon data
  94301. * @returns the parsed points
  94302. */
  94303. Polygon.Parse = function (input) {
  94304. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94305. var i, result = [];
  94306. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94307. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94308. }
  94309. return result;
  94310. };
  94311. /**
  94312. * Starts building a polygon from x and y coordinates
  94313. * @param x x coordinate
  94314. * @param y y coordinate
  94315. * @returns the started path2
  94316. */
  94317. Polygon.StartingAt = function (x, y) {
  94318. return BABYLON.Path2.StartingAt(x, y);
  94319. };
  94320. return Polygon;
  94321. }());
  94322. BABYLON.Polygon = Polygon;
  94323. /**
  94324. * Builds a polygon
  94325. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94326. */
  94327. var PolygonMeshBuilder = /** @class */ (function () {
  94328. /**
  94329. * Creates a PolygonMeshBuilder
  94330. * @param name name of the builder
  94331. * @param contours Path of the polygon
  94332. * @param scene scene to add to
  94333. */
  94334. function PolygonMeshBuilder(name, contours, scene) {
  94335. this._points = new PolygonPoints();
  94336. this._outlinepoints = new PolygonPoints();
  94337. this._holes = new Array();
  94338. this._epoints = new Array();
  94339. this._eholes = new Array();
  94340. this._name = name;
  94341. this._scene = scene;
  94342. var points;
  94343. if (contours instanceof BABYLON.Path2) {
  94344. points = contours.getPoints();
  94345. }
  94346. else {
  94347. points = contours;
  94348. }
  94349. this._addToepoint(points);
  94350. this._points.add(points);
  94351. this._outlinepoints.add(points);
  94352. if (typeof earcut === 'undefined') {
  94353. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94354. }
  94355. }
  94356. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94357. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94358. var p = points_1[_i];
  94359. this._epoints.push(p.x, p.y);
  94360. }
  94361. };
  94362. /**
  94363. * Adds a whole within the polygon
  94364. * @param hole Array of points defining the hole
  94365. * @returns this
  94366. */
  94367. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94368. this._points.add(hole);
  94369. var holepoints = new PolygonPoints();
  94370. holepoints.add(hole);
  94371. this._holes.push(holepoints);
  94372. this._eholes.push(this._epoints.length / 2);
  94373. this._addToepoint(hole);
  94374. return this;
  94375. };
  94376. /**
  94377. * Creates the polygon
  94378. * @param updatable If the mesh should be updatable
  94379. * @param depth The depth of the mesh created
  94380. * @returns the created mesh
  94381. */
  94382. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94383. var _this = this;
  94384. if (updatable === void 0) { updatable = false; }
  94385. if (depth === void 0) { depth = 0; }
  94386. var result = new BABYLON.Mesh(this._name, this._scene);
  94387. var normals = new Array();
  94388. var positions = new Array();
  94389. var uvs = new Array();
  94390. var bounds = this._points.computeBounds();
  94391. this._points.elements.forEach(function (p) {
  94392. normals.push(0, 1.0, 0);
  94393. positions.push(p.x, 0, p.y);
  94394. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  94395. });
  94396. var indices = new Array();
  94397. var res = earcut(this._epoints, this._eholes, 2);
  94398. for (var i = 0; i < res.length; i++) {
  94399. indices.push(res[i]);
  94400. }
  94401. if (depth > 0) {
  94402. var positionscount = (positions.length / 3); //get the current pointcount
  94403. this._points.elements.forEach(function (p) {
  94404. normals.push(0, -1.0, 0);
  94405. positions.push(p.x, -depth, p.y);
  94406. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  94407. });
  94408. var totalCount = indices.length;
  94409. for (var i = 0; i < totalCount; i += 3) {
  94410. var i0 = indices[i + 0];
  94411. var i1 = indices[i + 1];
  94412. var i2 = indices[i + 2];
  94413. indices.push(i2 + positionscount);
  94414. indices.push(i1 + positionscount);
  94415. indices.push(i0 + positionscount);
  94416. }
  94417. //Add the sides
  94418. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  94419. this._holes.forEach(function (hole) {
  94420. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  94421. });
  94422. }
  94423. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  94424. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  94425. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  94426. result.setIndices(indices);
  94427. return result;
  94428. };
  94429. /**
  94430. * Adds a side to the polygon
  94431. * @param positions points that make the polygon
  94432. * @param normals normals of the polygon
  94433. * @param uvs uvs of the polygon
  94434. * @param indices indices of the polygon
  94435. * @param bounds bounds of the polygon
  94436. * @param points points of the polygon
  94437. * @param depth depth of the polygon
  94438. * @param flip flip of the polygon
  94439. */
  94440. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  94441. var StartIndex = positions.length / 3;
  94442. var ulength = 0;
  94443. for (var i = 0; i < points.elements.length; i++) {
  94444. var p = points.elements[i];
  94445. var p1;
  94446. if ((i + 1) > points.elements.length - 1) {
  94447. p1 = points.elements[0];
  94448. }
  94449. else {
  94450. p1 = points.elements[i + 1];
  94451. }
  94452. positions.push(p.x, 0, p.y);
  94453. positions.push(p.x, -depth, p.y);
  94454. positions.push(p1.x, 0, p1.y);
  94455. positions.push(p1.x, -depth, p1.y);
  94456. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  94457. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  94458. var v3 = v2.subtract(v1);
  94459. var v4 = new BABYLON.Vector3(0, 1, 0);
  94460. var vn = BABYLON.Vector3.Cross(v3, v4);
  94461. vn = vn.normalize();
  94462. uvs.push(ulength / bounds.width, 0);
  94463. uvs.push(ulength / bounds.width, 1);
  94464. ulength += v3.length();
  94465. uvs.push((ulength / bounds.width), 0);
  94466. uvs.push((ulength / bounds.width), 1);
  94467. if (!flip) {
  94468. normals.push(-vn.x, -vn.y, -vn.z);
  94469. normals.push(-vn.x, -vn.y, -vn.z);
  94470. normals.push(-vn.x, -vn.y, -vn.z);
  94471. normals.push(-vn.x, -vn.y, -vn.z);
  94472. indices.push(StartIndex);
  94473. indices.push(StartIndex + 1);
  94474. indices.push(StartIndex + 2);
  94475. indices.push(StartIndex + 1);
  94476. indices.push(StartIndex + 3);
  94477. indices.push(StartIndex + 2);
  94478. }
  94479. else {
  94480. normals.push(vn.x, vn.y, vn.z);
  94481. normals.push(vn.x, vn.y, vn.z);
  94482. normals.push(vn.x, vn.y, vn.z);
  94483. normals.push(vn.x, vn.y, vn.z);
  94484. indices.push(StartIndex);
  94485. indices.push(StartIndex + 2);
  94486. indices.push(StartIndex + 1);
  94487. indices.push(StartIndex + 1);
  94488. indices.push(StartIndex + 2);
  94489. indices.push(StartIndex + 3);
  94490. }
  94491. StartIndex += 4;
  94492. }
  94493. };
  94494. return PolygonMeshBuilder;
  94495. }());
  94496. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  94497. })(BABYLON || (BABYLON = {}));
  94498. //# sourceMappingURL=babylon.polygonMesh.js.map
  94499. var BABYLON;
  94500. (function (BABYLON) {
  94501. /**
  94502. * Unique ID when we import meshes from Babylon to CSG
  94503. */
  94504. var currentCSGMeshId = 0;
  94505. /**
  94506. * Represents a vertex of a polygon. Use your own vertex class instead of this
  94507. * one to provide additional features like texture coordinates and vertex
  94508. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  94509. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  94510. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  94511. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  94512. * is not used anywhere else.
  94513. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  94514. */
  94515. var Vertex = /** @class */ (function () {
  94516. /**
  94517. * Initializes the vertex
  94518. * @param pos The position of the vertex
  94519. * @param normal The normal of the vertex
  94520. * @param uv The texture coordinate of the vertex
  94521. */
  94522. function Vertex(
  94523. /**
  94524. * The position of the vertex
  94525. */
  94526. pos,
  94527. /**
  94528. * The normal of the vertex
  94529. */
  94530. normal,
  94531. /**
  94532. * The texture coordinate of the vertex
  94533. */
  94534. uv) {
  94535. this.pos = pos;
  94536. this.normal = normal;
  94537. this.uv = uv;
  94538. }
  94539. /**
  94540. * Make a clone, or deep copy, of the vertex
  94541. * @returns A new Vertex
  94542. */
  94543. Vertex.prototype.clone = function () {
  94544. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  94545. };
  94546. /**
  94547. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  94548. * orientation of a polygon is flipped.
  94549. */
  94550. Vertex.prototype.flip = function () {
  94551. this.normal = this.normal.scale(-1);
  94552. };
  94553. /**
  94554. * Create a new vertex between this vertex and `other` by linearly
  94555. * interpolating all properties using a parameter of `t`. Subclasses should
  94556. * override this to interpolate additional properties.
  94557. * @param other the vertex to interpolate against
  94558. * @param t The factor used to linearly interpolate between the vertices
  94559. */
  94560. Vertex.prototype.interpolate = function (other, t) {
  94561. 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));
  94562. };
  94563. return Vertex;
  94564. }());
  94565. /**
  94566. * Represents a plane in 3D space.
  94567. */
  94568. var Plane = /** @class */ (function () {
  94569. /**
  94570. * Initializes the plane
  94571. * @param normal The normal for the plane
  94572. * @param w
  94573. */
  94574. function Plane(normal, w) {
  94575. this.normal = normal;
  94576. this.w = w;
  94577. }
  94578. /**
  94579. * Construct a plane from three points
  94580. * @param a Point a
  94581. * @param b Point b
  94582. * @param c Point c
  94583. */
  94584. Plane.FromPoints = function (a, b, c) {
  94585. var v0 = c.subtract(a);
  94586. var v1 = b.subtract(a);
  94587. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  94588. return null;
  94589. }
  94590. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  94591. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  94592. };
  94593. /**
  94594. * Clone, or make a deep copy of the plane
  94595. * @returns a new Plane
  94596. */
  94597. Plane.prototype.clone = function () {
  94598. return new Plane(this.normal.clone(), this.w);
  94599. };
  94600. /**
  94601. * Flip the face of the plane
  94602. */
  94603. Plane.prototype.flip = function () {
  94604. this.normal.scaleInPlace(-1);
  94605. this.w = -this.w;
  94606. };
  94607. /**
  94608. * Split `polygon` by this plane if needed, then put the polygon or polygon
  94609. * fragments in the appropriate lists. Coplanar polygons go into either
  94610. `* coplanarFront` or `coplanarBack` depending on their orientation with
  94611. * respect to this plane. Polygons in front or in back of this plane go into
  94612. * either `front` or `back`
  94613. * @param polygon The polygon to be split
  94614. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  94615. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  94616. * @param front Will contain the polygons in front of the plane
  94617. * @param back Will contain the polygons begind the plane
  94618. */
  94619. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  94620. var COPLANAR = 0;
  94621. var FRONT = 1;
  94622. var BACK = 2;
  94623. var SPANNING = 3;
  94624. // Classify each point as well as the entire polygon into one of the above
  94625. // four classes.
  94626. var polygonType = 0;
  94627. var types = [];
  94628. var i;
  94629. var t;
  94630. for (i = 0; i < polygon.vertices.length; i++) {
  94631. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  94632. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  94633. polygonType |= type;
  94634. types.push(type);
  94635. }
  94636. // Put the polygon in the correct list, splitting it when necessary
  94637. switch (polygonType) {
  94638. case COPLANAR:
  94639. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  94640. break;
  94641. case FRONT:
  94642. front.push(polygon);
  94643. break;
  94644. case BACK:
  94645. back.push(polygon);
  94646. break;
  94647. case SPANNING:
  94648. var f = [], b = [];
  94649. for (i = 0; i < polygon.vertices.length; i++) {
  94650. var j = (i + 1) % polygon.vertices.length;
  94651. var ti = types[i], tj = types[j];
  94652. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  94653. if (ti !== BACK) {
  94654. f.push(vi);
  94655. }
  94656. if (ti !== FRONT) {
  94657. b.push(ti !== BACK ? vi.clone() : vi);
  94658. }
  94659. if ((ti | tj) === SPANNING) {
  94660. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  94661. var v = vi.interpolate(vj, t);
  94662. f.push(v);
  94663. b.push(v.clone());
  94664. }
  94665. }
  94666. var poly;
  94667. if (f.length >= 3) {
  94668. poly = new Polygon(f, polygon.shared);
  94669. if (poly.plane) {
  94670. front.push(poly);
  94671. }
  94672. }
  94673. if (b.length >= 3) {
  94674. poly = new Polygon(b, polygon.shared);
  94675. if (poly.plane) {
  94676. back.push(poly);
  94677. }
  94678. }
  94679. break;
  94680. }
  94681. };
  94682. /**
  94683. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  94684. * point is on the plane
  94685. */
  94686. Plane.EPSILON = 1e-5;
  94687. return Plane;
  94688. }());
  94689. /**
  94690. * Represents a convex polygon. The vertices used to initialize a polygon must
  94691. * be coplanar and form a convex loop.
  94692. *
  94693. * Each convex polygon has a `shared` property, which is shared between all
  94694. * polygons that are clones of each other or were split from the same polygon.
  94695. * This can be used to define per-polygon properties (such as surface color)
  94696. */
  94697. var Polygon = /** @class */ (function () {
  94698. /**
  94699. * Initializes the polygon
  94700. * @param vertices The vertices of the polygon
  94701. * @param shared The properties shared across all polygons
  94702. */
  94703. function Polygon(vertices, shared) {
  94704. this.vertices = vertices;
  94705. this.shared = shared;
  94706. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  94707. }
  94708. /**
  94709. * Clones, or makes a deep copy, or the polygon
  94710. */
  94711. Polygon.prototype.clone = function () {
  94712. var vertices = this.vertices.map(function (v) { return v.clone(); });
  94713. return new Polygon(vertices, this.shared);
  94714. };
  94715. /**
  94716. * Flips the faces of the polygon
  94717. */
  94718. Polygon.prototype.flip = function () {
  94719. this.vertices.reverse().map(function (v) { v.flip(); });
  94720. this.plane.flip();
  94721. };
  94722. return Polygon;
  94723. }());
  94724. /**
  94725. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  94726. * by picking a polygon to split along. That polygon (and all other coplanar
  94727. * polygons) are added directly to that node and the other polygons are added to
  94728. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  94729. * no distinction between internal and leaf nodes
  94730. */
  94731. var Node = /** @class */ (function () {
  94732. /**
  94733. * Initializes the node
  94734. * @param polygons A collection of polygons held in the node
  94735. */
  94736. function Node(polygons) {
  94737. this.plane = null;
  94738. this.front = null;
  94739. this.back = null;
  94740. this.polygons = new Array();
  94741. if (polygons) {
  94742. this.build(polygons);
  94743. }
  94744. }
  94745. /**
  94746. * Clones, or makes a deep copy, of the node
  94747. * @returns The cloned node
  94748. */
  94749. Node.prototype.clone = function () {
  94750. var node = new Node();
  94751. node.plane = this.plane && this.plane.clone();
  94752. node.front = this.front && this.front.clone();
  94753. node.back = this.back && this.back.clone();
  94754. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  94755. return node;
  94756. };
  94757. /**
  94758. * Convert solid space to empty space and empty space to solid space
  94759. */
  94760. Node.prototype.invert = function () {
  94761. for (var i = 0; i < this.polygons.length; i++) {
  94762. this.polygons[i].flip();
  94763. }
  94764. if (this.plane) {
  94765. this.plane.flip();
  94766. }
  94767. if (this.front) {
  94768. this.front.invert();
  94769. }
  94770. if (this.back) {
  94771. this.back.invert();
  94772. }
  94773. var temp = this.front;
  94774. this.front = this.back;
  94775. this.back = temp;
  94776. };
  94777. /**
  94778. * Recursively remove all polygons in `polygons` that are inside this BSP
  94779. * tree.
  94780. * @param polygons Polygons to remove from the BSP
  94781. * @returns Polygons clipped from the BSP
  94782. */
  94783. Node.prototype.clipPolygons = function (polygons) {
  94784. if (!this.plane) {
  94785. return polygons.slice();
  94786. }
  94787. var front = new Array(), back = new Array();
  94788. for (var i = 0; i < polygons.length; i++) {
  94789. this.plane.splitPolygon(polygons[i], front, back, front, back);
  94790. }
  94791. if (this.front) {
  94792. front = this.front.clipPolygons(front);
  94793. }
  94794. if (this.back) {
  94795. back = this.back.clipPolygons(back);
  94796. }
  94797. else {
  94798. back = [];
  94799. }
  94800. return front.concat(back);
  94801. };
  94802. /**
  94803. * Remove all polygons in this BSP tree that are inside the other BSP tree
  94804. * `bsp`.
  94805. * @param bsp BSP containing polygons to remove from this BSP
  94806. */
  94807. Node.prototype.clipTo = function (bsp) {
  94808. this.polygons = bsp.clipPolygons(this.polygons);
  94809. if (this.front) {
  94810. this.front.clipTo(bsp);
  94811. }
  94812. if (this.back) {
  94813. this.back.clipTo(bsp);
  94814. }
  94815. };
  94816. /**
  94817. * Return a list of all polygons in this BSP tree
  94818. * @returns List of all polygons in this BSP tree
  94819. */
  94820. Node.prototype.allPolygons = function () {
  94821. var polygons = this.polygons.slice();
  94822. if (this.front) {
  94823. polygons = polygons.concat(this.front.allPolygons());
  94824. }
  94825. if (this.back) {
  94826. polygons = polygons.concat(this.back.allPolygons());
  94827. }
  94828. return polygons;
  94829. };
  94830. /**
  94831. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  94832. * new polygons are filtered down to the bottom of the tree and become new
  94833. * nodes there. Each set of polygons is partitioned using the first polygon
  94834. * (no heuristic is used to pick a good split)
  94835. * @param polygons Polygons used to construct the BSP tree
  94836. */
  94837. Node.prototype.build = function (polygons) {
  94838. if (!polygons.length) {
  94839. return;
  94840. }
  94841. if (!this.plane) {
  94842. this.plane = polygons[0].plane.clone();
  94843. }
  94844. var front = new Array(), back = new Array();
  94845. for (var i = 0; i < polygons.length; i++) {
  94846. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  94847. }
  94848. if (front.length) {
  94849. if (!this.front) {
  94850. this.front = new Node();
  94851. }
  94852. this.front.build(front);
  94853. }
  94854. if (back.length) {
  94855. if (!this.back) {
  94856. this.back = new Node();
  94857. }
  94858. this.back.build(back);
  94859. }
  94860. };
  94861. return Node;
  94862. }());
  94863. /**
  94864. * Class for building Constructive Solid Geometry
  94865. */
  94866. var CSG = /** @class */ (function () {
  94867. function CSG() {
  94868. this.polygons = new Array();
  94869. }
  94870. /**
  94871. * Convert the BABYLON.Mesh to BABYLON.CSG
  94872. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  94873. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  94874. */
  94875. CSG.FromMesh = function (mesh) {
  94876. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  94877. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  94878. if (mesh instanceof BABYLON.Mesh) {
  94879. mesh.computeWorldMatrix(true);
  94880. matrix = mesh.getWorldMatrix();
  94881. meshPosition = mesh.position.clone();
  94882. meshRotation = mesh.rotation.clone();
  94883. if (mesh.rotationQuaternion) {
  94884. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  94885. }
  94886. meshScaling = mesh.scaling.clone();
  94887. }
  94888. else {
  94889. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  94890. }
  94891. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94892. var subMeshes = mesh.subMeshes;
  94893. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  94894. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  94895. vertices = [];
  94896. for (var j = 0; j < 3; j++) {
  94897. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  94898. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  94899. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  94900. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  94901. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  94902. vertex = new Vertex(position, normal, uv);
  94903. vertices.push(vertex);
  94904. }
  94905. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  94906. // To handle the case of degenerated triangle
  94907. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  94908. if (polygon.plane) {
  94909. polygons.push(polygon);
  94910. }
  94911. }
  94912. }
  94913. var csg = CSG.FromPolygons(polygons);
  94914. csg.matrix = matrix;
  94915. csg.position = meshPosition;
  94916. csg.rotation = meshRotation;
  94917. csg.scaling = meshScaling;
  94918. csg.rotationQuaternion = meshRotationQuaternion;
  94919. currentCSGMeshId++;
  94920. return csg;
  94921. };
  94922. /**
  94923. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  94924. * @param polygons Polygons used to construct a BABYLON.CSG solid
  94925. */
  94926. CSG.FromPolygons = function (polygons) {
  94927. var csg = new CSG();
  94928. csg.polygons = polygons;
  94929. return csg;
  94930. };
  94931. /**
  94932. * Clones, or makes a deep copy, of the BABYLON.CSG
  94933. * @returns A new BABYLON.CSG
  94934. */
  94935. CSG.prototype.clone = function () {
  94936. var csg = new CSG();
  94937. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  94938. csg.copyTransformAttributes(this);
  94939. return csg;
  94940. };
  94941. /**
  94942. * Unions this CSG with another CSG
  94943. * @param csg The CSG to union against this CSG
  94944. * @returns The unioned CSG
  94945. */
  94946. CSG.prototype.union = function (csg) {
  94947. var a = new Node(this.clone().polygons);
  94948. var b = new Node(csg.clone().polygons);
  94949. a.clipTo(b);
  94950. b.clipTo(a);
  94951. b.invert();
  94952. b.clipTo(a);
  94953. b.invert();
  94954. a.build(b.allPolygons());
  94955. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  94956. };
  94957. /**
  94958. * Unions this CSG with another CSG in place
  94959. * @param csg The CSG to union against this CSG
  94960. */
  94961. CSG.prototype.unionInPlace = function (csg) {
  94962. var a = new Node(this.polygons);
  94963. var b = new Node(csg.polygons);
  94964. a.clipTo(b);
  94965. b.clipTo(a);
  94966. b.invert();
  94967. b.clipTo(a);
  94968. b.invert();
  94969. a.build(b.allPolygons());
  94970. this.polygons = a.allPolygons();
  94971. };
  94972. /**
  94973. * Subtracts this CSG with another CSG
  94974. * @param csg The CSG to subtract against this CSG
  94975. * @returns A new BABYLON.CSG
  94976. */
  94977. CSG.prototype.subtract = function (csg) {
  94978. var a = new Node(this.clone().polygons);
  94979. var b = new Node(csg.clone().polygons);
  94980. a.invert();
  94981. a.clipTo(b);
  94982. b.clipTo(a);
  94983. b.invert();
  94984. b.clipTo(a);
  94985. b.invert();
  94986. a.build(b.allPolygons());
  94987. a.invert();
  94988. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  94989. };
  94990. /**
  94991. * Subtracts this CSG with another CSG in place
  94992. * @param csg The CSG to subtact against this CSG
  94993. */
  94994. CSG.prototype.subtractInPlace = function (csg) {
  94995. var a = new Node(this.polygons);
  94996. var b = new Node(csg.polygons);
  94997. a.invert();
  94998. a.clipTo(b);
  94999. b.clipTo(a);
  95000. b.invert();
  95001. b.clipTo(a);
  95002. b.invert();
  95003. a.build(b.allPolygons());
  95004. a.invert();
  95005. this.polygons = a.allPolygons();
  95006. };
  95007. /**
  95008. * Intersect this CSG with another CSG
  95009. * @param csg The CSG to intersect against this CSG
  95010. * @returns A new BABYLON.CSG
  95011. */
  95012. CSG.prototype.intersect = function (csg) {
  95013. var a = new Node(this.clone().polygons);
  95014. var b = new Node(csg.clone().polygons);
  95015. a.invert();
  95016. b.clipTo(a);
  95017. b.invert();
  95018. a.clipTo(b);
  95019. b.clipTo(a);
  95020. a.build(b.allPolygons());
  95021. a.invert();
  95022. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95023. };
  95024. /**
  95025. * Intersects this CSG with another CSG in place
  95026. * @param csg The CSG to intersect against this CSG
  95027. */
  95028. CSG.prototype.intersectInPlace = function (csg) {
  95029. var a = new Node(this.polygons);
  95030. var b = new Node(csg.polygons);
  95031. a.invert();
  95032. b.clipTo(a);
  95033. b.invert();
  95034. a.clipTo(b);
  95035. b.clipTo(a);
  95036. a.build(b.allPolygons());
  95037. a.invert();
  95038. this.polygons = a.allPolygons();
  95039. };
  95040. /**
  95041. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95042. * not modified.
  95043. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95044. */
  95045. CSG.prototype.inverse = function () {
  95046. var csg = this.clone();
  95047. csg.inverseInPlace();
  95048. return csg;
  95049. };
  95050. /**
  95051. * Inverses the BABYLON.CSG in place
  95052. */
  95053. CSG.prototype.inverseInPlace = function () {
  95054. this.polygons.map(function (p) { p.flip(); });
  95055. };
  95056. /**
  95057. * This is used to keep meshes transformations so they can be restored
  95058. * when we build back a Babylon Mesh
  95059. * NB : All CSG operations are performed in world coordinates
  95060. * @param csg The BABYLON.CSG to copy the transform attributes from
  95061. * @returns This BABYLON.CSG
  95062. */
  95063. CSG.prototype.copyTransformAttributes = function (csg) {
  95064. this.matrix = csg.matrix;
  95065. this.position = csg.position;
  95066. this.rotation = csg.rotation;
  95067. this.scaling = csg.scaling;
  95068. this.rotationQuaternion = csg.rotationQuaternion;
  95069. return this;
  95070. };
  95071. /**
  95072. * Build Raw mesh from CSG
  95073. * Coordinates here are in world space
  95074. * @param name The name of the mesh geometry
  95075. * @param scene The BABYLON.Scene
  95076. * @param keepSubMeshes Specifies if the submeshes should be kept
  95077. * @returns A new BABYLON.Mesh
  95078. */
  95079. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95080. var matrix = this.matrix.clone();
  95081. matrix.invert();
  95082. 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;
  95083. if (keepSubMeshes) {
  95084. // Sort Polygons, since subMeshes are indices range
  95085. polygons.sort(function (a, b) {
  95086. if (a.shared.meshId === b.shared.meshId) {
  95087. return a.shared.subMeshId - b.shared.subMeshId;
  95088. }
  95089. else {
  95090. return a.shared.meshId - b.shared.meshId;
  95091. }
  95092. });
  95093. }
  95094. for (var i = 0, il = polygons.length; i < il; i++) {
  95095. polygon = polygons[i];
  95096. // Building SubMeshes
  95097. if (!subMesh_dict[polygon.shared.meshId]) {
  95098. subMesh_dict[polygon.shared.meshId] = {};
  95099. }
  95100. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95101. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95102. indexStart: +Infinity,
  95103. indexEnd: -Infinity,
  95104. materialIndex: polygon.shared.materialIndex
  95105. };
  95106. }
  95107. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95108. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95109. polygonIndices[0] = 0;
  95110. polygonIndices[1] = j - 1;
  95111. polygonIndices[2] = j;
  95112. for (var k = 0; k < 3; k++) {
  95113. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95114. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95115. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95116. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95117. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95118. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95119. // Check if 2 points can be merged
  95120. if (!(typeof vertex_idx !== 'undefined' &&
  95121. normals[vertex_idx * 3] === localNormal.x &&
  95122. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95123. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95124. uvs[vertex_idx * 2] === uv.x &&
  95125. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95126. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95127. uvs.push(uv.x, uv.y);
  95128. normals.push(normal.x, normal.y, normal.z);
  95129. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95130. }
  95131. indices.push(vertex_idx);
  95132. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95133. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95134. currentIndex++;
  95135. }
  95136. }
  95137. }
  95138. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95139. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95140. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95141. mesh.setIndices(indices, null);
  95142. if (keepSubMeshes) {
  95143. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95144. var materialIndexOffset = 0, materialMaxIndex;
  95145. mesh.subMeshes = new Array();
  95146. for (var m in subMesh_dict) {
  95147. materialMaxIndex = -1;
  95148. for (var sm in subMesh_dict[m]) {
  95149. subMesh_obj = subMesh_dict[m][sm];
  95150. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95151. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95152. }
  95153. materialIndexOffset += ++materialMaxIndex;
  95154. }
  95155. }
  95156. return mesh;
  95157. };
  95158. /**
  95159. * Build Mesh from CSG taking material and transforms into account
  95160. * @param name The name of the BABYLON.Mesh
  95161. * @param material The material of the BABYLON.Mesh
  95162. * @param scene The BABYLON.Scene
  95163. * @param keepSubMeshes Specifies if submeshes should be kept
  95164. * @returns The new BABYLON.Mesh
  95165. */
  95166. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95167. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95168. mesh.material = material;
  95169. mesh.position.copyFrom(this.position);
  95170. mesh.rotation.copyFrom(this.rotation);
  95171. if (this.rotationQuaternion) {
  95172. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95173. }
  95174. mesh.scaling.copyFrom(this.scaling);
  95175. mesh.computeWorldMatrix(true);
  95176. return mesh;
  95177. };
  95178. return CSG;
  95179. }());
  95180. BABYLON.CSG = CSG;
  95181. })(BABYLON || (BABYLON = {}));
  95182. //# sourceMappingURL=babylon.csg.js.map
  95183. var BABYLON;
  95184. (function (BABYLON) {
  95185. /**
  95186. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95187. * It controls one of the indiviual texture used in the effect.
  95188. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95189. */
  95190. var LensFlare = /** @class */ (function () {
  95191. /**
  95192. * Instantiates a new Lens Flare.
  95193. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95194. * It controls one of the indiviual texture used in the effect.
  95195. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95196. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95197. * @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.
  95198. * @param color Define the lens color
  95199. * @param imgUrl Define the lens texture url
  95200. * @param system Define the `lensFlareSystem` this flare is part of
  95201. */
  95202. function LensFlare(
  95203. /**
  95204. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95205. */
  95206. size,
  95207. /**
  95208. * 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.
  95209. */
  95210. position, color, imgUrl, system) {
  95211. this.size = size;
  95212. this.position = position;
  95213. /**
  95214. * Define the alpha mode to render this particular lens.
  95215. */
  95216. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95217. this.color = color || new BABYLON.Color3(1, 1, 1);
  95218. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95219. this._system = system;
  95220. system.lensFlares.push(this);
  95221. }
  95222. /**
  95223. * Creates a new Lens Flare.
  95224. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95225. * It controls one of the indiviual texture used in the effect.
  95226. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95227. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95228. * @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.
  95229. * @param color Define the lens color
  95230. * @param imgUrl Define the lens texture url
  95231. * @param system Define the `lensFlareSystem` this flare is part of
  95232. * @returns The newly created Lens Flare
  95233. */
  95234. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95235. return new LensFlare(size, position, color, imgUrl, system);
  95236. };
  95237. /**
  95238. * Dispose and release the lens flare with its associated resources.
  95239. */
  95240. LensFlare.prototype.dispose = function () {
  95241. if (this.texture) {
  95242. this.texture.dispose();
  95243. }
  95244. // Remove from scene
  95245. var index = this._system.lensFlares.indexOf(this);
  95246. this._system.lensFlares.splice(index, 1);
  95247. };
  95248. return LensFlare;
  95249. }());
  95250. BABYLON.LensFlare = LensFlare;
  95251. })(BABYLON || (BABYLON = {}));
  95252. //# sourceMappingURL=babylon.lensFlare.js.map
  95253. var BABYLON;
  95254. (function (BABYLON) {
  95255. // Adds the parser to the scene parsers.
  95256. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95257. // Lens flares
  95258. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95259. if (!container.lensFlareSystems) {
  95260. container.lensFlareSystems = new Array();
  95261. }
  95262. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95263. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95264. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95265. container.lensFlareSystems.push(lf);
  95266. }
  95267. }
  95268. });
  95269. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95270. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95271. if (this.lensFlareSystems[index].name === name) {
  95272. return this.lensFlareSystems[index];
  95273. }
  95274. }
  95275. return null;
  95276. };
  95277. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95278. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95279. if (this.lensFlareSystems[index].id === id) {
  95280. return this.lensFlareSystems[index];
  95281. }
  95282. }
  95283. return null;
  95284. };
  95285. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95286. var index = this.lensFlareSystems.indexOf(toRemove);
  95287. if (index !== -1) {
  95288. this.lensFlareSystems.splice(index, 1);
  95289. }
  95290. return index;
  95291. };
  95292. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95293. this.lensFlareSystems.push(newLensFlareSystem);
  95294. };
  95295. /**
  95296. * Defines the lens flare scene component responsible to manage any lens flares
  95297. * in a given scene.
  95298. */
  95299. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95300. /**
  95301. * Creates a new instance of the component for the given scene
  95302. * @param scene Defines the scene to register the component in
  95303. */
  95304. function LensFlareSystemSceneComponent(scene) {
  95305. /**
  95306. * The component name helpfull to identify the component in the list of scene components.
  95307. */
  95308. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95309. this.scene = scene;
  95310. scene.lensFlareSystems = new Array();
  95311. }
  95312. /**
  95313. * Registers the component in a given scene
  95314. */
  95315. LensFlareSystemSceneComponent.prototype.register = function () {
  95316. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95317. };
  95318. /**
  95319. * Rebuilds the elements related to this component in case of
  95320. * context lost for instance.
  95321. */
  95322. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95323. // Nothing to do for lens flare
  95324. };
  95325. /**
  95326. * Adds all the element from the container to the scene
  95327. * @param container the container holding the elements
  95328. */
  95329. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95330. var _this = this;
  95331. if (!container.lensFlareSystems) {
  95332. return;
  95333. }
  95334. container.lensFlareSystems.forEach(function (o) {
  95335. _this.scene.addLensFlareSystem(o);
  95336. });
  95337. };
  95338. /**
  95339. * Removes all the elements in the container from the scene
  95340. * @param container contains the elements to remove
  95341. */
  95342. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95343. var _this = this;
  95344. if (!container.lensFlareSystems) {
  95345. return;
  95346. }
  95347. container.lensFlareSystems.forEach(function (o) {
  95348. _this.scene.removeLensFlareSystem(o);
  95349. });
  95350. };
  95351. /**
  95352. * Serializes the component data to the specified json object
  95353. * @param serializationObject The object to serialize to
  95354. */
  95355. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95356. // Lens flares
  95357. serializationObject.lensFlareSystems = [];
  95358. var lensFlareSystems = this.scene.lensFlareSystems;
  95359. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95360. var lensFlareSystem = lensFlareSystems_1[_i];
  95361. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95362. }
  95363. };
  95364. /**
  95365. * Disposes the component and the associated ressources.
  95366. */
  95367. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95368. var lensFlareSystems = this.scene.lensFlareSystems;
  95369. while (lensFlareSystems.length) {
  95370. lensFlareSystems[0].dispose();
  95371. }
  95372. };
  95373. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95374. // Lens flares
  95375. if (this.scene.lensFlaresEnabled) {
  95376. var lensFlareSystems = this.scene.lensFlareSystems;
  95377. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95378. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95379. var lensFlareSystem = lensFlareSystems_2[_i];
  95380. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95381. lensFlareSystem.render();
  95382. }
  95383. }
  95384. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95385. }
  95386. };
  95387. return LensFlareSystemSceneComponent;
  95388. }());
  95389. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95390. })(BABYLON || (BABYLON = {}));
  95391. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  95392. var BABYLON;
  95393. (function (BABYLON) {
  95394. /**
  95395. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95396. * It is usually composed of several `BABYLON.lensFlare`.
  95397. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95398. */
  95399. var LensFlareSystem = /** @class */ (function () {
  95400. /**
  95401. * Instantiates a lens flare system.
  95402. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95403. * It is usually composed of several `BABYLON.lensFlare`.
  95404. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95405. * @param name Define the name of the lens flare system in the scene
  95406. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  95407. * @param scene Define the scene the lens flare system belongs to
  95408. */
  95409. function LensFlareSystem(
  95410. /**
  95411. * Define the name of the lens flare system
  95412. */
  95413. name, emitter, scene) {
  95414. this.name = name;
  95415. /**
  95416. * List of lens flares used in this system.
  95417. */
  95418. this.lensFlares = new Array();
  95419. /**
  95420. * Define a limit from the border the lens flare can be visible.
  95421. */
  95422. this.borderLimit = 300;
  95423. /**
  95424. * Define a viewport border we do not want to see the lens flare in.
  95425. */
  95426. this.viewportBorder = 0;
  95427. /**
  95428. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  95429. */
  95430. this.layerMask = 0x0FFFFFFF;
  95431. this._vertexBuffers = {};
  95432. this._isEnabled = true;
  95433. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95434. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  95435. if (!component) {
  95436. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  95437. scene._addComponent(component);
  95438. }
  95439. this._emitter = emitter;
  95440. this.id = name;
  95441. scene.lensFlareSystems.push(this);
  95442. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  95443. var engine = scene.getEngine();
  95444. // VBO
  95445. var vertices = [];
  95446. vertices.push(1, 1);
  95447. vertices.push(-1, 1);
  95448. vertices.push(-1, -1);
  95449. vertices.push(1, -1);
  95450. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95451. // Indices
  95452. var indices = [];
  95453. indices.push(0);
  95454. indices.push(1);
  95455. indices.push(2);
  95456. indices.push(0);
  95457. indices.push(2);
  95458. indices.push(3);
  95459. this._indexBuffer = engine.createIndexBuffer(indices);
  95460. // Effects
  95461. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  95462. }
  95463. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  95464. /**
  95465. * Define if the lens flare system is enabled.
  95466. */
  95467. get: function () {
  95468. return this._isEnabled;
  95469. },
  95470. set: function (value) {
  95471. this._isEnabled = value;
  95472. },
  95473. enumerable: true,
  95474. configurable: true
  95475. });
  95476. /**
  95477. * Get the scene the effects belongs to.
  95478. * @returns the scene holding the lens flare system
  95479. */
  95480. LensFlareSystem.prototype.getScene = function () {
  95481. return this._scene;
  95482. };
  95483. /**
  95484. * Get the emitter of the lens flare system.
  95485. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95486. * @returns the emitter of the lens flare system
  95487. */
  95488. LensFlareSystem.prototype.getEmitter = function () {
  95489. return this._emitter;
  95490. };
  95491. /**
  95492. * Set the emitter of the lens flare system.
  95493. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95494. * @param newEmitter Define the new emitter of the system
  95495. */
  95496. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  95497. this._emitter = newEmitter;
  95498. };
  95499. /**
  95500. * Get the lens flare system emitter position.
  95501. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  95502. * @returns the position
  95503. */
  95504. LensFlareSystem.prototype.getEmitterPosition = function () {
  95505. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  95506. };
  95507. /**
  95508. * @hidden
  95509. */
  95510. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  95511. var position = this.getEmitterPosition();
  95512. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  95513. this._positionX = position.x;
  95514. this._positionY = position.y;
  95515. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  95516. if (this.viewportBorder > 0) {
  95517. globalViewport.x -= this.viewportBorder;
  95518. globalViewport.y -= this.viewportBorder;
  95519. globalViewport.width += this.viewportBorder * 2;
  95520. globalViewport.height += this.viewportBorder * 2;
  95521. position.x += this.viewportBorder;
  95522. position.y += this.viewportBorder;
  95523. this._positionX += this.viewportBorder;
  95524. this._positionY += this.viewportBorder;
  95525. }
  95526. if (position.z > 0) {
  95527. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  95528. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  95529. return true;
  95530. }
  95531. }
  95532. return true;
  95533. }
  95534. return false;
  95535. };
  95536. /** @hidden */
  95537. LensFlareSystem.prototype._isVisible = function () {
  95538. if (!this._isEnabled || !this._scene.activeCamera) {
  95539. return false;
  95540. }
  95541. var emitterPosition = this.getEmitterPosition();
  95542. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  95543. var distance = direction.length();
  95544. direction.normalize();
  95545. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  95546. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  95547. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  95548. };
  95549. /**
  95550. * @hidden
  95551. */
  95552. LensFlareSystem.prototype.render = function () {
  95553. if (!this._effect.isReady() || !this._scene.activeCamera) {
  95554. return false;
  95555. }
  95556. var engine = this._scene.getEngine();
  95557. var viewport = this._scene.activeCamera.viewport;
  95558. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  95559. // Position
  95560. if (!this.computeEffectivePosition(globalViewport)) {
  95561. return false;
  95562. }
  95563. // Visibility
  95564. if (!this._isVisible()) {
  95565. return false;
  95566. }
  95567. // Intensity
  95568. var awayX;
  95569. var awayY;
  95570. if (this._positionX < this.borderLimit + globalViewport.x) {
  95571. awayX = this.borderLimit + globalViewport.x - this._positionX;
  95572. }
  95573. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  95574. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  95575. }
  95576. else {
  95577. awayX = 0;
  95578. }
  95579. if (this._positionY < this.borderLimit + globalViewport.y) {
  95580. awayY = this.borderLimit + globalViewport.y - this._positionY;
  95581. }
  95582. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  95583. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  95584. }
  95585. else {
  95586. awayY = 0;
  95587. }
  95588. var away = (awayX > awayY) ? awayX : awayY;
  95589. away -= this.viewportBorder;
  95590. if (away > this.borderLimit) {
  95591. away = this.borderLimit;
  95592. }
  95593. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  95594. if (intensity < 0) {
  95595. return false;
  95596. }
  95597. if (intensity > 1.0) {
  95598. intensity = 1.0;
  95599. }
  95600. if (this.viewportBorder > 0) {
  95601. globalViewport.x += this.viewportBorder;
  95602. globalViewport.y += this.viewportBorder;
  95603. globalViewport.width -= this.viewportBorder * 2;
  95604. globalViewport.height -= this.viewportBorder * 2;
  95605. this._positionX -= this.viewportBorder;
  95606. this._positionY -= this.viewportBorder;
  95607. }
  95608. // Position
  95609. var centerX = globalViewport.x + globalViewport.width / 2;
  95610. var centerY = globalViewport.y + globalViewport.height / 2;
  95611. var distX = centerX - this._positionX;
  95612. var distY = centerY - this._positionY;
  95613. // Effects
  95614. engine.enableEffect(this._effect);
  95615. engine.setState(false);
  95616. engine.setDepthBuffer(false);
  95617. // VBOs
  95618. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  95619. // Flares
  95620. for (var index = 0; index < this.lensFlares.length; index++) {
  95621. var flare = this.lensFlares[index];
  95622. engine.setAlphaMode(flare.alphaMode);
  95623. var x = centerX - (distX * flare.position);
  95624. var y = centerY - (distY * flare.position);
  95625. var cw = flare.size;
  95626. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  95627. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  95628. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  95629. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  95630. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  95631. // Texture
  95632. this._effect.setTexture("textureSampler", flare.texture);
  95633. // Color
  95634. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  95635. // Draw order
  95636. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95637. }
  95638. engine.setDepthBuffer(true);
  95639. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95640. return true;
  95641. };
  95642. /**
  95643. * Dispose and release the lens flare with its associated resources.
  95644. */
  95645. LensFlareSystem.prototype.dispose = function () {
  95646. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95647. if (vertexBuffer) {
  95648. vertexBuffer.dispose();
  95649. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95650. }
  95651. if (this._indexBuffer) {
  95652. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95653. this._indexBuffer = null;
  95654. }
  95655. while (this.lensFlares.length) {
  95656. this.lensFlares[0].dispose();
  95657. }
  95658. // Remove from scene
  95659. var index = this._scene.lensFlareSystems.indexOf(this);
  95660. this._scene.lensFlareSystems.splice(index, 1);
  95661. };
  95662. /**
  95663. * Parse a lens flare system from a JSON repressentation
  95664. * @param parsedLensFlareSystem Define the JSON to parse
  95665. * @param scene Define the scene the parsed system should be instantiated in
  95666. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  95667. * @returns the parsed system
  95668. */
  95669. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  95670. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  95671. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  95672. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  95673. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  95674. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  95675. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  95676. var parsedFlare = parsedLensFlareSystem.flares[index];
  95677. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  95678. }
  95679. return lensFlareSystem;
  95680. };
  95681. /**
  95682. * Serialize the current Lens Flare System into a JSON representation.
  95683. * @returns the serialized JSON
  95684. */
  95685. LensFlareSystem.prototype.serialize = function () {
  95686. var serializationObject = {};
  95687. serializationObject.id = this.id;
  95688. serializationObject.name = this.name;
  95689. serializationObject.emitterId = this.getEmitter().id;
  95690. serializationObject.borderLimit = this.borderLimit;
  95691. serializationObject.flares = [];
  95692. for (var index = 0; index < this.lensFlares.length; index++) {
  95693. var flare = this.lensFlares[index];
  95694. serializationObject.flares.push({
  95695. size: flare.size,
  95696. position: flare.position,
  95697. color: flare.color.asArray(),
  95698. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  95699. });
  95700. }
  95701. return serializationObject;
  95702. };
  95703. return LensFlareSystem;
  95704. }());
  95705. BABYLON.LensFlareSystem = LensFlareSystem;
  95706. })(BABYLON || (BABYLON = {}));
  95707. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  95708. var BABYLON;
  95709. (function (BABYLON) {
  95710. /**
  95711. * This is a holder class for the physics joint created by the physics plugin
  95712. * It holds a set of functions to control the underlying joint
  95713. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95714. */
  95715. var PhysicsJoint = /** @class */ (function () {
  95716. /**
  95717. * Initializes the physics joint
  95718. * @param type The type of the physics joint
  95719. * @param jointData The data for the physics joint
  95720. */
  95721. function PhysicsJoint(
  95722. /**
  95723. * The type of the physics joint
  95724. */
  95725. type,
  95726. /**
  95727. * The data for the physics joint
  95728. */
  95729. jointData) {
  95730. this.type = type;
  95731. this.jointData = jointData;
  95732. jointData.nativeParams = jointData.nativeParams || {};
  95733. }
  95734. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  95735. /**
  95736. * Gets the physics joint
  95737. */
  95738. get: function () {
  95739. return this._physicsJoint;
  95740. },
  95741. /**
  95742. * Sets the physics joint
  95743. */
  95744. set: function (newJoint) {
  95745. if (this._physicsJoint) {
  95746. //remove from the wolrd
  95747. }
  95748. this._physicsJoint = newJoint;
  95749. },
  95750. enumerable: true,
  95751. configurable: true
  95752. });
  95753. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  95754. /**
  95755. * Sets the physics plugin
  95756. */
  95757. set: function (physicsPlugin) {
  95758. this._physicsPlugin = physicsPlugin;
  95759. },
  95760. enumerable: true,
  95761. configurable: true
  95762. });
  95763. /**
  95764. * Execute a function that is physics-plugin specific.
  95765. * @param {Function} func the function that will be executed.
  95766. * It accepts two parameters: the physics world and the physics joint
  95767. */
  95768. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  95769. func(this._physicsPlugin.world, this._physicsJoint);
  95770. };
  95771. //TODO check if the native joints are the same
  95772. //Joint Types
  95773. /**
  95774. * Distance-Joint type
  95775. */
  95776. PhysicsJoint.DistanceJoint = 0;
  95777. /**
  95778. * Hinge-Joint type
  95779. */
  95780. PhysicsJoint.HingeJoint = 1;
  95781. /**
  95782. * Ball-and-Socket joint type
  95783. */
  95784. PhysicsJoint.BallAndSocketJoint = 2;
  95785. /**
  95786. * Wheel-Joint type
  95787. */
  95788. PhysicsJoint.WheelJoint = 3;
  95789. /**
  95790. * Slider-Joint type
  95791. */
  95792. PhysicsJoint.SliderJoint = 4;
  95793. //OIMO
  95794. /**
  95795. * Prismatic-Joint type
  95796. */
  95797. PhysicsJoint.PrismaticJoint = 5;
  95798. //
  95799. /**
  95800. * Universal-Joint type
  95801. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  95802. */
  95803. PhysicsJoint.UniversalJoint = 6;
  95804. /**
  95805. * Hinge-Joint 2 type
  95806. */
  95807. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  95808. //Cannon
  95809. /**
  95810. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  95811. */
  95812. PhysicsJoint.PointToPointJoint = 8;
  95813. //Cannon only at the moment
  95814. /**
  95815. * Spring-Joint type
  95816. */
  95817. PhysicsJoint.SpringJoint = 9;
  95818. /**
  95819. * Lock-Joint type
  95820. */
  95821. PhysicsJoint.LockJoint = 10;
  95822. return PhysicsJoint;
  95823. }());
  95824. BABYLON.PhysicsJoint = PhysicsJoint;
  95825. /**
  95826. * A class representing a physics distance joint
  95827. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95828. */
  95829. var DistanceJoint = /** @class */ (function (_super) {
  95830. __extends(DistanceJoint, _super);
  95831. /**
  95832. *
  95833. * @param jointData The data for the Distance-Joint
  95834. */
  95835. function DistanceJoint(jointData) {
  95836. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  95837. }
  95838. /**
  95839. * Update the predefined distance.
  95840. * @param maxDistance The maximum preferred distance
  95841. * @param minDistance The minimum preferred distance
  95842. */
  95843. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  95844. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  95845. };
  95846. return DistanceJoint;
  95847. }(PhysicsJoint));
  95848. BABYLON.DistanceJoint = DistanceJoint;
  95849. /**
  95850. * Represents a Motor-Enabled Joint
  95851. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95852. */
  95853. var MotorEnabledJoint = /** @class */ (function (_super) {
  95854. __extends(MotorEnabledJoint, _super);
  95855. /**
  95856. * Initializes the Motor-Enabled Joint
  95857. * @param type The type of the joint
  95858. * @param jointData The physica joint data for the joint
  95859. */
  95860. function MotorEnabledJoint(type, jointData) {
  95861. return _super.call(this, type, jointData) || this;
  95862. }
  95863. /**
  95864. * Set the motor values.
  95865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95866. * @param force the force to apply
  95867. * @param maxForce max force for this motor.
  95868. */
  95869. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  95870. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95871. };
  95872. /**
  95873. * Set the motor's limits.
  95874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95875. * @param upperLimit The upper limit of the motor
  95876. * @param lowerLimit The lower limit of the motor
  95877. */
  95878. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95879. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95880. };
  95881. return MotorEnabledJoint;
  95882. }(PhysicsJoint));
  95883. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  95884. /**
  95885. * This class represents a single physics Hinge-Joint
  95886. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95887. */
  95888. var HingeJoint = /** @class */ (function (_super) {
  95889. __extends(HingeJoint, _super);
  95890. /**
  95891. * Initializes the Hinge-Joint
  95892. * @param jointData The joint data for the Hinge-Joint
  95893. */
  95894. function HingeJoint(jointData) {
  95895. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  95896. }
  95897. /**
  95898. * Set the motor values.
  95899. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95900. * @param {number} force the force to apply
  95901. * @param {number} maxForce max force for this motor.
  95902. */
  95903. HingeJoint.prototype.setMotor = function (force, maxForce) {
  95904. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95905. };
  95906. /**
  95907. * Set the motor's limits.
  95908. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95909. * @param upperLimit The upper limit of the motor
  95910. * @param lowerLimit The lower limit of the motor
  95911. */
  95912. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95913. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95914. };
  95915. return HingeJoint;
  95916. }(MotorEnabledJoint));
  95917. BABYLON.HingeJoint = HingeJoint;
  95918. /**
  95919. * This class represents a dual hinge physics joint (same as wheel joint)
  95920. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95921. */
  95922. var Hinge2Joint = /** @class */ (function (_super) {
  95923. __extends(Hinge2Joint, _super);
  95924. /**
  95925. * Initializes the Hinge2-Joint
  95926. * @param jointData The joint data for the Hinge2-Joint
  95927. */
  95928. function Hinge2Joint(jointData) {
  95929. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  95930. }
  95931. /**
  95932. * Set the motor values.
  95933. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95934. * @param {number} force the force to apply
  95935. * @param {number} maxForce max force for this motor.
  95936. * @param {motorIndex} the motor's index, 0 or 1.
  95937. */
  95938. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  95939. if (motorIndex === void 0) { motorIndex = 0; }
  95940. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  95941. };
  95942. /**
  95943. * Set the motor limits.
  95944. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95945. * @param {number} upperLimit the upper limit
  95946. * @param {number} lowerLimit lower limit
  95947. * @param {motorIndex} the motor's index, 0 or 1.
  95948. */
  95949. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  95950. if (motorIndex === void 0) { motorIndex = 0; }
  95951. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  95952. };
  95953. return Hinge2Joint;
  95954. }(MotorEnabledJoint));
  95955. BABYLON.Hinge2Joint = Hinge2Joint;
  95956. })(BABYLON || (BABYLON = {}));
  95957. //# sourceMappingURL=babylon.physicsJoint.js.map
  95958. var BABYLON;
  95959. (function (BABYLON) {
  95960. /**
  95961. * Represents a physics imposter
  95962. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95963. */
  95964. var PhysicsImpostor = /** @class */ (function () {
  95965. /**
  95966. * Initializes the physics imposter
  95967. * @param object The physics-enabled object used as the physics imposter
  95968. * @param type The type of the physics imposter
  95969. * @param _options The options for the physics imposter
  95970. * @param _scene The Babylon scene
  95971. */
  95972. function PhysicsImpostor(
  95973. /**
  95974. * The physics-enabled object used as the physics imposter
  95975. */
  95976. object,
  95977. /**
  95978. * The type of the physics imposter
  95979. */
  95980. type, _options, _scene) {
  95981. if (_options === void 0) { _options = { mass: 0 }; }
  95982. var _this = this;
  95983. this.object = object;
  95984. this.type = type;
  95985. this._options = _options;
  95986. this._scene = _scene;
  95987. this._bodyUpdateRequired = false;
  95988. this._onBeforePhysicsStepCallbacks = new Array();
  95989. this._onAfterPhysicsStepCallbacks = new Array();
  95990. this._onPhysicsCollideCallbacks = [];
  95991. this._deltaPosition = BABYLON.Vector3.Zero();
  95992. this._isDisposed = false;
  95993. //temp variables for parent rotation calculations
  95994. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  95995. this._tmpQuat = new BABYLON.Quaternion();
  95996. this._tmpQuat2 = new BABYLON.Quaternion();
  95997. /**
  95998. * this function is executed by the physics engine.
  95999. */
  96000. this.beforeStep = function () {
  96001. if (!_this._physicsEngine) {
  96002. return;
  96003. }
  96004. _this.object.translate(_this._deltaPosition, -1);
  96005. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96006. _this.object.computeWorldMatrix(false);
  96007. if (_this.object.parent && _this.object.rotationQuaternion) {
  96008. _this.getParentsRotation();
  96009. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96010. }
  96011. else {
  96012. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96013. }
  96014. if (!_this._options.disableBidirectionalTransformation) {
  96015. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96016. }
  96017. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96018. func(_this);
  96019. });
  96020. };
  96021. /**
  96022. * this function is executed by the physics engine
  96023. */
  96024. this.afterStep = function () {
  96025. if (!_this._physicsEngine) {
  96026. return;
  96027. }
  96028. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96029. func(_this);
  96030. });
  96031. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96032. // object has now its world rotation. needs to be converted to local.
  96033. if (_this.object.parent && _this.object.rotationQuaternion) {
  96034. _this.getParentsRotation();
  96035. _this._tmpQuat.conjugateInPlace();
  96036. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96037. }
  96038. // take the position set and make it the absolute position of this object.
  96039. _this.object.setAbsolutePosition(_this.object.position);
  96040. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96041. _this.object.translate(_this._deltaPosition, 1);
  96042. };
  96043. /**
  96044. * Legacy collision detection event support
  96045. */
  96046. this.onCollideEvent = null;
  96047. /**
  96048. * event and body object due to cannon's event-based architecture.
  96049. */
  96050. this.onCollide = function (e) {
  96051. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96052. return;
  96053. }
  96054. if (!_this._physicsEngine) {
  96055. return;
  96056. }
  96057. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96058. if (otherImpostor) {
  96059. // Legacy collision detection event support
  96060. if (_this.onCollideEvent) {
  96061. _this.onCollideEvent(_this, otherImpostor);
  96062. }
  96063. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96064. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96065. }).forEach(function (obj) {
  96066. obj.callback(_this, otherImpostor);
  96067. });
  96068. }
  96069. };
  96070. //sanity check!
  96071. if (!this.object) {
  96072. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96073. return;
  96074. }
  96075. //legacy support for old syntax.
  96076. if (!this._scene && object.getScene) {
  96077. this._scene = object.getScene();
  96078. }
  96079. if (!this._scene) {
  96080. return;
  96081. }
  96082. this._physicsEngine = this._scene.getPhysicsEngine();
  96083. if (!this._physicsEngine) {
  96084. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96085. }
  96086. else {
  96087. //set the object's quaternion, if not set
  96088. if (!this.object.rotationQuaternion) {
  96089. if (this.object.rotation) {
  96090. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96091. }
  96092. else {
  96093. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96094. }
  96095. }
  96096. //default options params
  96097. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96098. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96099. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96100. this._joints = [];
  96101. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96102. if (!this.object.parent || this._options.ignoreParent) {
  96103. this._init();
  96104. }
  96105. else if (this.object.parent.physicsImpostor) {
  96106. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96107. }
  96108. }
  96109. }
  96110. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96111. /**
  96112. * Specifies if the physics imposter is disposed
  96113. */
  96114. get: function () {
  96115. return this._isDisposed;
  96116. },
  96117. enumerable: true,
  96118. configurable: true
  96119. });
  96120. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96121. /**
  96122. * Gets the mass of the physics imposter
  96123. */
  96124. get: function () {
  96125. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96126. },
  96127. set: function (value) {
  96128. this.setMass(value);
  96129. },
  96130. enumerable: true,
  96131. configurable: true
  96132. });
  96133. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96134. /**
  96135. * Gets the coefficient of friction
  96136. */
  96137. get: function () {
  96138. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96139. },
  96140. /**
  96141. * Sets the coefficient of friction
  96142. */
  96143. set: function (value) {
  96144. if (!this._physicsEngine) {
  96145. return;
  96146. }
  96147. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96148. },
  96149. enumerable: true,
  96150. configurable: true
  96151. });
  96152. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96153. /**
  96154. * Gets the coefficient of restitution
  96155. */
  96156. get: function () {
  96157. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96158. },
  96159. /**
  96160. * Sets the coefficient of restitution
  96161. */
  96162. set: function (value) {
  96163. if (!this._physicsEngine) {
  96164. return;
  96165. }
  96166. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96167. },
  96168. enumerable: true,
  96169. configurable: true
  96170. });
  96171. /**
  96172. * This function will completly initialize this impostor.
  96173. * It will create a new body - but only if this mesh has no parent.
  96174. * If it has, this impostor will not be used other than to define the impostor
  96175. * of the child mesh.
  96176. * @hidden
  96177. */
  96178. PhysicsImpostor.prototype._init = function () {
  96179. if (!this._physicsEngine) {
  96180. return;
  96181. }
  96182. this._physicsEngine.removeImpostor(this);
  96183. this.physicsBody = null;
  96184. this._parent = this._parent || this._getPhysicsParent();
  96185. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96186. this._physicsEngine.addImpostor(this);
  96187. }
  96188. };
  96189. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96190. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96191. var parentMesh = this.object.parent;
  96192. return parentMesh.physicsImpostor;
  96193. }
  96194. return null;
  96195. };
  96196. /**
  96197. * Should a new body be generated.
  96198. * @returns boolean specifying if body initialization is required
  96199. */
  96200. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96201. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96202. };
  96203. /**
  96204. * Sets the updated scaling
  96205. * @param updated Specifies if the scaling is updated
  96206. */
  96207. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96208. this.forceUpdate();
  96209. };
  96210. /**
  96211. * Force a regeneration of this or the parent's impostor's body.
  96212. * Use under cautious - This will remove all joints already implemented.
  96213. */
  96214. PhysicsImpostor.prototype.forceUpdate = function () {
  96215. this._init();
  96216. if (this.parent && !this._options.ignoreParent) {
  96217. this.parent.forceUpdate();
  96218. }
  96219. };
  96220. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96221. /*public get mesh(): AbstractMesh {
  96222. return this._mesh;
  96223. }*/
  96224. /**
  96225. * Gets the body that holds this impostor. Either its own, or its parent.
  96226. */
  96227. get: function () {
  96228. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96229. },
  96230. /**
  96231. * Set the physics body. Used mainly by the physics engine/plugin
  96232. */
  96233. set: function (physicsBody) {
  96234. if (this._physicsBody && this._physicsEngine) {
  96235. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96236. }
  96237. this._physicsBody = physicsBody;
  96238. this.resetUpdateFlags();
  96239. },
  96240. enumerable: true,
  96241. configurable: true
  96242. });
  96243. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96244. /**
  96245. * Get the parent of the physics imposter
  96246. * @returns Physics imposter or null
  96247. */
  96248. get: function () {
  96249. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96250. },
  96251. /**
  96252. * Sets the parent of the physics imposter
  96253. */
  96254. set: function (value) {
  96255. this._parent = value;
  96256. },
  96257. enumerable: true,
  96258. configurable: true
  96259. });
  96260. /**
  96261. * Resets the update flags
  96262. */
  96263. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96264. this._bodyUpdateRequired = false;
  96265. };
  96266. /**
  96267. * Gets the object extend size
  96268. * @returns the object extend size
  96269. */
  96270. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96271. if (this.object.getBoundingInfo) {
  96272. var q = this.object.rotationQuaternion;
  96273. //reset rotation
  96274. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96275. //calculate the world matrix with no rotation
  96276. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96277. var boundingInfo = this.object.getBoundingInfo();
  96278. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96279. //bring back the rotation
  96280. this.object.rotationQuaternion = q;
  96281. //calculate the world matrix with the new rotation
  96282. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96283. return size;
  96284. }
  96285. else {
  96286. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96287. }
  96288. };
  96289. /**
  96290. * Gets the object center
  96291. * @returns The object center
  96292. */
  96293. PhysicsImpostor.prototype.getObjectCenter = function () {
  96294. if (this.object.getBoundingInfo) {
  96295. var boundingInfo = this.object.getBoundingInfo();
  96296. return boundingInfo.boundingBox.centerWorld;
  96297. }
  96298. else {
  96299. return this.object.position;
  96300. }
  96301. };
  96302. /**
  96303. * Get a specific parametes from the options parameter
  96304. * @param paramName The object parameter name
  96305. * @returns The object parameter
  96306. */
  96307. PhysicsImpostor.prototype.getParam = function (paramName) {
  96308. return this._options[paramName];
  96309. };
  96310. /**
  96311. * Sets a specific parameter in the options given to the physics plugin
  96312. * @param paramName The parameter name
  96313. * @param value The value of the parameter
  96314. */
  96315. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96316. this._options[paramName] = value;
  96317. this._bodyUpdateRequired = true;
  96318. };
  96319. /**
  96320. * Specifically change the body's mass option. Won't recreate the physics body object
  96321. * @param mass The mass of the physics imposter
  96322. */
  96323. PhysicsImpostor.prototype.setMass = function (mass) {
  96324. if (this.getParam("mass") !== mass) {
  96325. this.setParam("mass", mass);
  96326. }
  96327. if (this._physicsEngine) {
  96328. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96329. }
  96330. };
  96331. /**
  96332. * Gets the linear velocity
  96333. * @returns linear velocity or null
  96334. */
  96335. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96336. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96337. };
  96338. /**
  96339. * Sets the linear velocity
  96340. * @param velocity linear velocity or null
  96341. */
  96342. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96343. if (this._physicsEngine) {
  96344. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96345. }
  96346. };
  96347. /**
  96348. * Gets the angular velocity
  96349. * @returns angular velocity or null
  96350. */
  96351. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96352. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96353. };
  96354. /**
  96355. * Sets the angular velocity
  96356. * @param velocity The velocity or null
  96357. */
  96358. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96359. if (this._physicsEngine) {
  96360. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96361. }
  96362. };
  96363. /**
  96364. * Execute a function with the physics plugin native code
  96365. * Provide a function the will have two variables - the world object and the physics body object
  96366. * @param func The function to execute with the physics plugin native code
  96367. */
  96368. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96369. if (this._physicsEngine) {
  96370. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96371. }
  96372. };
  96373. /**
  96374. * Register a function that will be executed before the physics world is stepping forward
  96375. * @param func The function to execute before the physics world is stepped forward
  96376. */
  96377. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96378. this._onBeforePhysicsStepCallbacks.push(func);
  96379. };
  96380. /**
  96381. * Unregister a function that will be executed before the physics world is stepping forward
  96382. * @param func The function to execute before the physics world is stepped forward
  96383. */
  96384. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96385. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96386. if (index > -1) {
  96387. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96388. }
  96389. else {
  96390. BABYLON.Tools.Warn("Function to remove was not found");
  96391. }
  96392. };
  96393. /**
  96394. * Register a function that will be executed after the physics step
  96395. * @param func The function to execute after physics step
  96396. */
  96397. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  96398. this._onAfterPhysicsStepCallbacks.push(func);
  96399. };
  96400. /**
  96401. * Unregisters a function that will be executed after the physics step
  96402. * @param func The function to execute after physics step
  96403. */
  96404. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  96405. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  96406. if (index > -1) {
  96407. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  96408. }
  96409. else {
  96410. BABYLON.Tools.Warn("Function to remove was not found");
  96411. }
  96412. };
  96413. /**
  96414. * register a function that will be executed when this impostor collides against a different body
  96415. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  96416. * @param func Callback that is executed on collision
  96417. */
  96418. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  96419. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96420. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  96421. };
  96422. /**
  96423. * Unregisters the physics imposter on contact
  96424. * @param collideAgainst The physics object to collide against
  96425. * @param func Callback to execute on collision
  96426. */
  96427. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  96428. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96429. var index = -1;
  96430. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  96431. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  96432. // chcek the arrays match
  96433. var sameList = cbDef.otherImpostors.every(function (impostor) {
  96434. return collidedAgainstList.indexOf(impostor) > -1;
  96435. });
  96436. if (sameList) {
  96437. index = idx;
  96438. }
  96439. return sameList;
  96440. }
  96441. return false;
  96442. });
  96443. if (found) {
  96444. this._onPhysicsCollideCallbacks.splice(index, 1);
  96445. }
  96446. else {
  96447. BABYLON.Tools.Warn("Function to remove was not found");
  96448. }
  96449. };
  96450. /**
  96451. * Get the parent rotation
  96452. * @returns The parent rotation
  96453. */
  96454. PhysicsImpostor.prototype.getParentsRotation = function () {
  96455. var parent = this.object.parent;
  96456. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  96457. while (parent) {
  96458. if (parent.rotationQuaternion) {
  96459. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  96460. }
  96461. else {
  96462. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  96463. }
  96464. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  96465. parent = parent.parent;
  96466. }
  96467. return this._tmpQuat;
  96468. };
  96469. /**
  96470. * Apply a force
  96471. * @param force The force to apply
  96472. * @param contactPoint The contact point for the force
  96473. * @returns The physics imposter
  96474. */
  96475. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  96476. if (this._physicsEngine) {
  96477. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  96478. }
  96479. return this;
  96480. };
  96481. /**
  96482. * Apply an impulse
  96483. * @param force The impulse force
  96484. * @param contactPoint The contact point for the impulse force
  96485. * @returns The physics imposter
  96486. */
  96487. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  96488. if (this._physicsEngine) {
  96489. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  96490. }
  96491. return this;
  96492. };
  96493. /**
  96494. * A help function to create a joint
  96495. * @param otherImpostor A physics imposter used to create a joint
  96496. * @param jointType The type of joint
  96497. * @param jointData The data for the joint
  96498. * @returns The physics imposter
  96499. */
  96500. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  96501. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  96502. this.addJoint(otherImpostor, joint);
  96503. return this;
  96504. };
  96505. /**
  96506. * Add a joint to this impostor with a different impostor
  96507. * @param otherImpostor A physics imposter used to add a joint
  96508. * @param joint The joint to add
  96509. * @returns The physics imposter
  96510. */
  96511. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  96512. this._joints.push({
  96513. otherImpostor: otherImpostor,
  96514. joint: joint
  96515. });
  96516. if (this._physicsEngine) {
  96517. this._physicsEngine.addJoint(this, otherImpostor, joint);
  96518. }
  96519. return this;
  96520. };
  96521. /**
  96522. * Will keep this body still, in a sleep mode.
  96523. * @returns the physics imposter
  96524. */
  96525. PhysicsImpostor.prototype.sleep = function () {
  96526. if (this._physicsEngine) {
  96527. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  96528. }
  96529. return this;
  96530. };
  96531. /**
  96532. * Wake the body up.
  96533. * @returns The physics imposter
  96534. */
  96535. PhysicsImpostor.prototype.wakeUp = function () {
  96536. if (this._physicsEngine) {
  96537. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  96538. }
  96539. return this;
  96540. };
  96541. /**
  96542. * Clones the physics imposter
  96543. * @param newObject The physics imposter clones to this physics-enabled object
  96544. * @returns A nullable physics imposter
  96545. */
  96546. PhysicsImpostor.prototype.clone = function (newObject) {
  96547. if (!newObject) {
  96548. return null;
  96549. }
  96550. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  96551. };
  96552. /**
  96553. * Disposes the physics imposter
  96554. */
  96555. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  96556. var _this = this;
  96557. //no dispose if no physics engine is available.
  96558. if (!this._physicsEngine) {
  96559. return;
  96560. }
  96561. this._joints.forEach(function (j) {
  96562. if (_this._physicsEngine) {
  96563. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  96564. }
  96565. });
  96566. //dispose the physics body
  96567. this._physicsEngine.removeImpostor(this);
  96568. if (this.parent) {
  96569. this.parent.forceUpdate();
  96570. }
  96571. else {
  96572. /*this._object.getChildMeshes().forEach(function(mesh) {
  96573. if (mesh.physicsImpostor) {
  96574. if (disposeChildren) {
  96575. mesh.physicsImpostor.dispose();
  96576. mesh.physicsImpostor = null;
  96577. }
  96578. }
  96579. })*/
  96580. }
  96581. this._isDisposed = true;
  96582. };
  96583. /**
  96584. * Sets the delta position
  96585. * @param position The delta position amount
  96586. */
  96587. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  96588. this._deltaPosition.copyFrom(position);
  96589. };
  96590. /**
  96591. * Sets the delta rotation
  96592. * @param rotation The delta rotation amount
  96593. */
  96594. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  96595. if (!this._deltaRotation) {
  96596. this._deltaRotation = new BABYLON.Quaternion();
  96597. }
  96598. this._deltaRotation.copyFrom(rotation);
  96599. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  96600. };
  96601. /**
  96602. * Gets the box size of the physics imposter and stores the result in the input parameter
  96603. * @param result Stores the box size
  96604. * @returns The physics imposter
  96605. */
  96606. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  96607. if (this._physicsEngine) {
  96608. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  96609. }
  96610. return this;
  96611. };
  96612. /**
  96613. * Gets the radius of the physics imposter
  96614. * @returns Radius of the physics imposter
  96615. */
  96616. PhysicsImpostor.prototype.getRadius = function () {
  96617. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  96618. };
  96619. /**
  96620. * Sync a bone with this impostor
  96621. * @param bone The bone to sync to the impostor.
  96622. * @param boneMesh The mesh that the bone is influencing.
  96623. * @param jointPivot The pivot of the joint / bone in local space.
  96624. * @param distToJoint Optional distance from the impostor to the joint.
  96625. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96626. */
  96627. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  96628. var tempVec = PhysicsImpostor._tmpVecs[0];
  96629. var mesh = this.object;
  96630. if (mesh.rotationQuaternion) {
  96631. if (adjustRotation) {
  96632. var tempQuat = PhysicsImpostor._tmpQuat;
  96633. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  96634. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  96635. }
  96636. else {
  96637. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  96638. }
  96639. }
  96640. tempVec.x = 0;
  96641. tempVec.y = 0;
  96642. tempVec.z = 0;
  96643. if (jointPivot) {
  96644. tempVec.x = jointPivot.x;
  96645. tempVec.y = jointPivot.y;
  96646. tempVec.z = jointPivot.z;
  96647. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  96648. if (distToJoint === undefined || distToJoint === null) {
  96649. distToJoint = jointPivot.length();
  96650. }
  96651. tempVec.x *= distToJoint;
  96652. tempVec.y *= distToJoint;
  96653. tempVec.z *= distToJoint;
  96654. }
  96655. if (bone.getParent()) {
  96656. tempVec.addInPlace(mesh.getAbsolutePosition());
  96657. bone.setAbsolutePosition(tempVec, boneMesh);
  96658. }
  96659. else {
  96660. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  96661. boneMesh.position.x -= tempVec.x;
  96662. boneMesh.position.y -= tempVec.y;
  96663. boneMesh.position.z -= tempVec.z;
  96664. }
  96665. };
  96666. /**
  96667. * Sync impostor to a bone
  96668. * @param bone The bone that the impostor will be synced to.
  96669. * @param boneMesh The mesh that the bone is influencing.
  96670. * @param jointPivot The pivot of the joint / bone in local space.
  96671. * @param distToJoint Optional distance from the impostor to the joint.
  96672. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96673. * @param boneAxis Optional vector3 axis the bone is aligned with
  96674. */
  96675. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  96676. var mesh = this.object;
  96677. if (mesh.rotationQuaternion) {
  96678. if (adjustRotation) {
  96679. var tempQuat = PhysicsImpostor._tmpQuat;
  96680. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  96681. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  96682. }
  96683. else {
  96684. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  96685. }
  96686. }
  96687. var pos = PhysicsImpostor._tmpVecs[0];
  96688. var boneDir = PhysicsImpostor._tmpVecs[1];
  96689. if (!boneAxis) {
  96690. boneAxis = PhysicsImpostor._tmpVecs[2];
  96691. boneAxis.x = 0;
  96692. boneAxis.y = 1;
  96693. boneAxis.z = 0;
  96694. }
  96695. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  96696. bone.getAbsolutePositionToRef(boneMesh, pos);
  96697. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  96698. distToJoint = jointPivot.length();
  96699. }
  96700. if (distToJoint !== undefined && distToJoint !== null) {
  96701. pos.x += boneDir.x * distToJoint;
  96702. pos.y += boneDir.y * distToJoint;
  96703. pos.z += boneDir.z * distToJoint;
  96704. }
  96705. mesh.setAbsolutePosition(pos);
  96706. };
  96707. /**
  96708. * The default object size of the imposter
  96709. */
  96710. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  96711. /**
  96712. * The identity quaternion of the imposter
  96713. */
  96714. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  96715. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  96716. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  96717. //Impostor types
  96718. /**
  96719. * No-Imposter type
  96720. */
  96721. PhysicsImpostor.NoImpostor = 0;
  96722. /**
  96723. * Sphere-Imposter type
  96724. */
  96725. PhysicsImpostor.SphereImpostor = 1;
  96726. /**
  96727. * Box-Imposter type
  96728. */
  96729. PhysicsImpostor.BoxImpostor = 2;
  96730. /**
  96731. * Plane-Imposter type
  96732. */
  96733. PhysicsImpostor.PlaneImpostor = 3;
  96734. /**
  96735. * Mesh-imposter type
  96736. */
  96737. PhysicsImpostor.MeshImpostor = 4;
  96738. /**
  96739. * Cylinder-Imposter type
  96740. */
  96741. PhysicsImpostor.CylinderImpostor = 7;
  96742. /**
  96743. * Particle-Imposter type
  96744. */
  96745. PhysicsImpostor.ParticleImpostor = 8;
  96746. /**
  96747. * Heightmap-Imposter type
  96748. */
  96749. PhysicsImpostor.HeightmapImpostor = 9;
  96750. return PhysicsImpostor;
  96751. }());
  96752. BABYLON.PhysicsImpostor = PhysicsImpostor;
  96753. })(BABYLON || (BABYLON = {}));
  96754. //# sourceMappingURL=babylon.physicsImpostor.js.map
  96755. var BABYLON;
  96756. (function (BABYLON) {
  96757. /**
  96758. * Class used to control physics engine
  96759. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  96760. */
  96761. var PhysicsEngine = /** @class */ (function () {
  96762. /**
  96763. * Creates a new Physics Engine
  96764. * @param gravity defines the gravity vector used by the simulation
  96765. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  96766. */
  96767. function PhysicsEngine(gravity, _physicsPlugin) {
  96768. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  96769. this._physicsPlugin = _physicsPlugin;
  96770. this._impostors = [];
  96771. this._joints = [];
  96772. if (!this._physicsPlugin.isSupported()) {
  96773. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  96774. + "Please make sure it is included.");
  96775. }
  96776. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  96777. this.setGravity(gravity);
  96778. this.setTimeStep();
  96779. }
  96780. /**
  96781. * Sets the gravity vector used by the simulation
  96782. * @param gravity defines the gravity vector to use
  96783. */
  96784. PhysicsEngine.prototype.setGravity = function (gravity) {
  96785. this.gravity = gravity;
  96786. this._physicsPlugin.setGravity(this.gravity);
  96787. };
  96788. /**
  96789. * Set the time step of the physics engine.
  96790. * Default is 1/60.
  96791. * To slow it down, enter 1/600 for example.
  96792. * To speed it up, 1/30
  96793. * @param newTimeStep defines the new timestep to apply to this world.
  96794. */
  96795. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  96796. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  96797. this._physicsPlugin.setTimeStep(newTimeStep);
  96798. };
  96799. /**
  96800. * Get the time step of the physics engine.
  96801. * @returns the current time step
  96802. */
  96803. PhysicsEngine.prototype.getTimeStep = function () {
  96804. return this._physicsPlugin.getTimeStep();
  96805. };
  96806. /**
  96807. * Release all resources
  96808. */
  96809. PhysicsEngine.prototype.dispose = function () {
  96810. this._impostors.forEach(function (impostor) {
  96811. impostor.dispose();
  96812. });
  96813. this._physicsPlugin.dispose();
  96814. };
  96815. /**
  96816. * Gets the name of the current physics plugin
  96817. * @returns the name of the plugin
  96818. */
  96819. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  96820. return this._physicsPlugin.name;
  96821. };
  96822. /**
  96823. * Adding a new impostor for the impostor tracking.
  96824. * This will be done by the impostor itself.
  96825. * @param impostor the impostor to add
  96826. */
  96827. PhysicsEngine.prototype.addImpostor = function (impostor) {
  96828. impostor.uniqueId = this._impostors.push(impostor);
  96829. //if no parent, generate the body
  96830. if (!impostor.parent) {
  96831. this._physicsPlugin.generatePhysicsBody(impostor);
  96832. }
  96833. };
  96834. /**
  96835. * Remove an impostor from the engine.
  96836. * This impostor and its mesh will not longer be updated by the physics engine.
  96837. * @param impostor the impostor to remove
  96838. */
  96839. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  96840. var index = this._impostors.indexOf(impostor);
  96841. if (index > -1) {
  96842. var removed = this._impostors.splice(index, 1);
  96843. //Is it needed?
  96844. if (removed.length) {
  96845. //this will also remove it from the world.
  96846. removed[0].physicsBody = null;
  96847. }
  96848. }
  96849. };
  96850. /**
  96851. * Add a joint to the physics engine
  96852. * @param mainImpostor defines the main impostor to which the joint is added.
  96853. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  96854. * @param joint defines the joint that will connect both impostors.
  96855. */
  96856. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  96857. var impostorJoint = {
  96858. mainImpostor: mainImpostor,
  96859. connectedImpostor: connectedImpostor,
  96860. joint: joint
  96861. };
  96862. joint.physicsPlugin = this._physicsPlugin;
  96863. this._joints.push(impostorJoint);
  96864. this._physicsPlugin.generateJoint(impostorJoint);
  96865. };
  96866. /**
  96867. * Removes a joint from the simulation
  96868. * @param mainImpostor defines the impostor used with the joint
  96869. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  96870. * @param joint defines the joint to remove
  96871. */
  96872. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  96873. var matchingJoints = this._joints.filter(function (impostorJoint) {
  96874. return (impostorJoint.connectedImpostor === connectedImpostor
  96875. && impostorJoint.joint === joint
  96876. && impostorJoint.mainImpostor === mainImpostor);
  96877. });
  96878. if (matchingJoints.length) {
  96879. this._physicsPlugin.removeJoint(matchingJoints[0]);
  96880. //TODO remove it from the list as well
  96881. }
  96882. };
  96883. /**
  96884. * Called by the scene. No need to call it.
  96885. * @param delta defines the timespam between frames
  96886. */
  96887. PhysicsEngine.prototype._step = function (delta) {
  96888. var _this = this;
  96889. //check if any mesh has no body / requires an update
  96890. this._impostors.forEach(function (impostor) {
  96891. if (impostor.isBodyInitRequired()) {
  96892. _this._physicsPlugin.generatePhysicsBody(impostor);
  96893. }
  96894. });
  96895. if (delta > 0.1) {
  96896. delta = 0.1;
  96897. }
  96898. else if (delta <= 0) {
  96899. delta = 1.0 / 60.0;
  96900. }
  96901. this._physicsPlugin.executeStep(delta, this._impostors);
  96902. };
  96903. /**
  96904. * Gets the current plugin used to run the simulation
  96905. * @returns current plugin
  96906. */
  96907. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  96908. return this._physicsPlugin;
  96909. };
  96910. /**
  96911. * Gets the list of physic impostors
  96912. * @returns an array of PhysicsImpostor
  96913. */
  96914. PhysicsEngine.prototype.getImpostors = function () {
  96915. return this._impostors;
  96916. };
  96917. /**
  96918. * Gets the impostor for a physics enabled object
  96919. * @param object defines the object impersonated by the impostor
  96920. * @returns the PhysicsImpostor or null if not found
  96921. */
  96922. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  96923. for (var i = 0; i < this._impostors.length; ++i) {
  96924. if (this._impostors[i].object === object) {
  96925. return this._impostors[i];
  96926. }
  96927. }
  96928. return null;
  96929. };
  96930. /**
  96931. * Gets the impostor for a physics body object
  96932. * @param body defines physics body used by the impostor
  96933. * @returns the PhysicsImpostor or null if not found
  96934. */
  96935. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  96936. for (var i = 0; i < this._impostors.length; ++i) {
  96937. if (this._impostors[i].physicsBody === body) {
  96938. return this._impostors[i];
  96939. }
  96940. }
  96941. return null;
  96942. };
  96943. /**
  96944. * Global value used to control the smallest number supported by the simulation
  96945. */
  96946. PhysicsEngine.Epsilon = 0.001;
  96947. return PhysicsEngine;
  96948. }());
  96949. BABYLON.PhysicsEngine = PhysicsEngine;
  96950. })(BABYLON || (BABYLON = {}));
  96951. //# sourceMappingURL=babylon.physicsEngine.js.map
  96952. var BABYLON;
  96953. (function (BABYLON) {
  96954. /**
  96955. * A helper for physics simulations
  96956. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96957. */
  96958. var PhysicsHelper = /** @class */ (function () {
  96959. /**
  96960. * Initializes the Physics helper
  96961. * @param scene Babylon.js scene
  96962. */
  96963. function PhysicsHelper(scene) {
  96964. this._scene = scene;
  96965. this._physicsEngine = this._scene.getPhysicsEngine();
  96966. if (!this._physicsEngine) {
  96967. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  96968. }
  96969. }
  96970. /**
  96971. * Applies a radial explosion impulse
  96972. * @param origin the origin of the explosion
  96973. * @param radius the explosion radius
  96974. * @param strength the explosion strength
  96975. * @param falloff possible options: Constant & Linear. Defaults to Constant
  96976. * @returns A physics radial explosion event, or null
  96977. */
  96978. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  96979. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  96980. if (!this._physicsEngine) {
  96981. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  96982. return null;
  96983. }
  96984. var impostors = this._physicsEngine.getImpostors();
  96985. if (impostors.length === 0) {
  96986. return null;
  96987. }
  96988. var event = new PhysicsRadialExplosionEvent(this._scene);
  96989. impostors.forEach(function (impostor) {
  96990. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  96991. if (!impostorForceAndContactPoint) {
  96992. return;
  96993. }
  96994. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96995. });
  96996. event.dispose(false);
  96997. return event;
  96998. };
  96999. /**
  97000. * Applies a radial explosion force
  97001. * @param origin the origin of the explosion
  97002. * @param radius the explosion radius
  97003. * @param strength the explosion strength
  97004. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97005. * @returns A physics radial explosion event, or null
  97006. */
  97007. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97008. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97009. if (!this._physicsEngine) {
  97010. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97011. return null;
  97012. }
  97013. var impostors = this._physicsEngine.getImpostors();
  97014. if (impostors.length === 0) {
  97015. return null;
  97016. }
  97017. var event = new PhysicsRadialExplosionEvent(this._scene);
  97018. impostors.forEach(function (impostor) {
  97019. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97020. if (!impostorForceAndContactPoint) {
  97021. return;
  97022. }
  97023. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97024. });
  97025. event.dispose(false);
  97026. return event;
  97027. };
  97028. /**
  97029. * Creates a gravitational field
  97030. * @param origin the origin of the explosion
  97031. * @param radius the explosion radius
  97032. * @param strength the explosion strength
  97033. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97034. * @returns A physics gravitational field event, or null
  97035. */
  97036. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97037. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97038. if (!this._physicsEngine) {
  97039. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97040. return null;
  97041. }
  97042. var impostors = this._physicsEngine.getImpostors();
  97043. if (impostors.length === 0) {
  97044. return null;
  97045. }
  97046. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97047. event.dispose(false);
  97048. return event;
  97049. };
  97050. /**
  97051. * Creates a physics updraft event
  97052. * @param origin the origin of the updraft
  97053. * @param radius the radius of the updraft
  97054. * @param strength the strength of the updraft
  97055. * @param height the height of the updraft
  97056. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97057. * @returns A physics updraft event, or null
  97058. */
  97059. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97060. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97061. if (!this._physicsEngine) {
  97062. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97063. return null;
  97064. }
  97065. if (this._physicsEngine.getImpostors().length === 0) {
  97066. return null;
  97067. }
  97068. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97069. event.dispose(false);
  97070. return event;
  97071. };
  97072. /**
  97073. * Creates a physics vortex event
  97074. * @param origin the of the vortex
  97075. * @param radius the radius of the vortex
  97076. * @param strength the strength of the vortex
  97077. * @param height the height of the vortex
  97078. * @returns a Physics vortex event, or null
  97079. * A physics vortex event or null
  97080. */
  97081. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97082. if (!this._physicsEngine) {
  97083. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97084. return null;
  97085. }
  97086. if (this._physicsEngine.getImpostors().length === 0) {
  97087. return null;
  97088. }
  97089. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97090. event.dispose(false);
  97091. return event;
  97092. };
  97093. return PhysicsHelper;
  97094. }());
  97095. BABYLON.PhysicsHelper = PhysicsHelper;
  97096. /**
  97097. * Represents a physics radial explosion event
  97098. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97099. */
  97100. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97101. /**
  97102. * Initializes a radial explosioin event
  97103. * @param scene BabylonJS scene
  97104. */
  97105. function PhysicsRadialExplosionEvent(scene) {
  97106. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97107. this._rays = [];
  97108. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97109. this._scene = scene;
  97110. }
  97111. /**
  97112. * Returns the data related to the radial explosion event (sphere & rays).
  97113. * @returns The radial explosion event data
  97114. */
  97115. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97116. this._dataFetched = true;
  97117. return {
  97118. sphere: this._sphere,
  97119. rays: this._rays,
  97120. };
  97121. };
  97122. /**
  97123. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97124. * @param impostor A physics imposter
  97125. * @param origin the origin of the explosion
  97126. * @param radius the explosion radius
  97127. * @param strength the explosion strength
  97128. * @param falloff possible options: Constant & Linear
  97129. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97130. */
  97131. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97132. if (impostor.mass === 0) {
  97133. return null;
  97134. }
  97135. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97136. return null;
  97137. }
  97138. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97139. return null;
  97140. }
  97141. var impostorObjectCenter = impostor.getObjectCenter();
  97142. var direction = impostorObjectCenter.subtract(origin);
  97143. var ray = new BABYLON.Ray(origin, direction, radius);
  97144. this._rays.push(ray);
  97145. var hit = ray.intersectsMesh(impostor.object);
  97146. var contactPoint = hit.pickedPoint;
  97147. if (!contactPoint) {
  97148. return null;
  97149. }
  97150. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97151. if (distanceFromOrigin > radius) {
  97152. return null;
  97153. }
  97154. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97155. ? strength
  97156. : strength * (1 - (distanceFromOrigin / radius));
  97157. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97158. return { force: force, contactPoint: contactPoint };
  97159. };
  97160. /**
  97161. * Disposes the sphere.
  97162. * @param force Specifies if the sphere should be disposed by force
  97163. */
  97164. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97165. var _this = this;
  97166. if (force === void 0) { force = true; }
  97167. if (force) {
  97168. this._sphere.dispose();
  97169. }
  97170. else {
  97171. setTimeout(function () {
  97172. if (!_this._dataFetched) {
  97173. _this._sphere.dispose();
  97174. }
  97175. }, 0);
  97176. }
  97177. };
  97178. /*** Helpers ***/
  97179. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97180. if (!this._sphere) {
  97181. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97182. this._sphere.isVisible = false;
  97183. }
  97184. };
  97185. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97186. var impostorObject = impostor.object;
  97187. this._prepareSphere();
  97188. this._sphere.position = origin;
  97189. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97190. this._sphere._updateBoundingInfo();
  97191. this._sphere.computeWorldMatrix(true);
  97192. return this._sphere.intersectsMesh(impostorObject, true);
  97193. };
  97194. return PhysicsRadialExplosionEvent;
  97195. }());
  97196. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97197. /**
  97198. * Represents a gravitational field event
  97199. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97200. */
  97201. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97202. /**
  97203. * Initializes the physics gravitational field event
  97204. * @param physicsHelper A physics helper
  97205. * @param scene BabylonJS scene
  97206. * @param origin The origin position of the gravitational field event
  97207. * @param radius The radius of the gravitational field event
  97208. * @param strength The strength of the gravitational field event
  97209. * @param falloff The falloff for the gravitational field event
  97210. */
  97211. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97212. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97213. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97214. this._physicsHelper = physicsHelper;
  97215. this._scene = scene;
  97216. this._origin = origin;
  97217. this._radius = radius;
  97218. this._strength = strength;
  97219. this._falloff = falloff;
  97220. this._tickCallback = this._tick.bind(this);
  97221. }
  97222. /**
  97223. * Returns the data related to the gravitational field event (sphere).
  97224. * @returns A gravitational field event
  97225. */
  97226. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97227. this._dataFetched = true;
  97228. return {
  97229. sphere: this._sphere,
  97230. };
  97231. };
  97232. /**
  97233. * Enables the gravitational field.
  97234. */
  97235. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97236. this._tickCallback.call(this);
  97237. this._scene.registerBeforeRender(this._tickCallback);
  97238. };
  97239. /**
  97240. * Disables the gravitational field.
  97241. */
  97242. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97243. this._scene.unregisterBeforeRender(this._tickCallback);
  97244. };
  97245. /**
  97246. * Disposes the sphere.
  97247. * @param force The force to dispose from the gravitational field event
  97248. */
  97249. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97250. var _this = this;
  97251. if (force === void 0) { force = true; }
  97252. if (force) {
  97253. this._sphere.dispose();
  97254. }
  97255. else {
  97256. setTimeout(function () {
  97257. if (!_this._dataFetched) {
  97258. _this._sphere.dispose();
  97259. }
  97260. }, 0);
  97261. }
  97262. };
  97263. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97264. // Since the params won't change, we fetch the event only once
  97265. if (this._sphere) {
  97266. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97267. }
  97268. else {
  97269. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97270. if (radialExplosionEvent) {
  97271. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97272. }
  97273. }
  97274. };
  97275. return PhysicsGravitationalFieldEvent;
  97276. }());
  97277. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97278. /**
  97279. * Represents a physics updraft event
  97280. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97281. */
  97282. var PhysicsUpdraftEvent = /** @class */ (function () {
  97283. /**
  97284. * Initializes the physics updraft event
  97285. * @param _scene BabylonJS scene
  97286. * @param _origin The origin position of the updraft
  97287. * @param _radius The radius of the updraft
  97288. * @param _strength The strength of the updraft
  97289. * @param _height The height of the updraft
  97290. * @param _updraftMode The mode of the updraft
  97291. */
  97292. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97293. this._scene = _scene;
  97294. this._origin = _origin;
  97295. this._radius = _radius;
  97296. this._strength = _strength;
  97297. this._height = _height;
  97298. this._updraftMode = _updraftMode;
  97299. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97300. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97301. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97302. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97303. this._physicsEngine = this._scene.getPhysicsEngine();
  97304. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97305. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97306. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97307. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97308. }
  97309. this._tickCallback = this._tick.bind(this);
  97310. }
  97311. /**
  97312. * Returns the data related to the updraft event (cylinder).
  97313. * @returns A physics updraft event
  97314. */
  97315. PhysicsUpdraftEvent.prototype.getData = function () {
  97316. this._dataFetched = true;
  97317. return {
  97318. cylinder: this._cylinder,
  97319. };
  97320. };
  97321. /**
  97322. * Enables the updraft.
  97323. */
  97324. PhysicsUpdraftEvent.prototype.enable = function () {
  97325. this._tickCallback.call(this);
  97326. this._scene.registerBeforeRender(this._tickCallback);
  97327. };
  97328. /**
  97329. * Disables the cortex.
  97330. */
  97331. PhysicsUpdraftEvent.prototype.disable = function () {
  97332. this._scene.unregisterBeforeRender(this._tickCallback);
  97333. };
  97334. /**
  97335. * Disposes the sphere.
  97336. * @param force Specifies if the updraft should be disposed by force
  97337. */
  97338. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97339. var _this = this;
  97340. if (force === void 0) { force = true; }
  97341. if (force) {
  97342. this._cylinder.dispose();
  97343. }
  97344. else {
  97345. setTimeout(function () {
  97346. if (!_this._dataFetched) {
  97347. _this._cylinder.dispose();
  97348. }
  97349. }, 0);
  97350. }
  97351. };
  97352. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97353. if (impostor.mass === 0) {
  97354. return null;
  97355. }
  97356. if (!this._intersectsWithCylinder(impostor)) {
  97357. return null;
  97358. }
  97359. var impostorObjectCenter = impostor.getObjectCenter();
  97360. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97361. var direction = this._originDirection;
  97362. }
  97363. else {
  97364. var direction = impostorObjectCenter.subtract(this._originTop);
  97365. }
  97366. var multiplier = this._strength * -1;
  97367. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97368. return { force: force, contactPoint: impostorObjectCenter };
  97369. };
  97370. PhysicsUpdraftEvent.prototype._tick = function () {
  97371. var _this = this;
  97372. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97373. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97374. if (!impostorForceAndContactPoint) {
  97375. return;
  97376. }
  97377. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97378. });
  97379. };
  97380. /*** Helpers ***/
  97381. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97382. if (!this._cylinder) {
  97383. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97384. height: this._height,
  97385. diameter: this._radius * 2,
  97386. }, this._scene);
  97387. this._cylinder.isVisible = false;
  97388. }
  97389. };
  97390. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97391. var impostorObject = impostor.object;
  97392. this._prepareCylinder();
  97393. this._cylinder.position = this._cylinderPosition;
  97394. return this._cylinder.intersectsMesh(impostorObject, true);
  97395. };
  97396. return PhysicsUpdraftEvent;
  97397. }());
  97398. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  97399. /**
  97400. * Represents a physics vortex event
  97401. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97402. */
  97403. var PhysicsVortexEvent = /** @class */ (function () {
  97404. /**
  97405. * Initializes the physics vortex event
  97406. * @param _scene The BabylonJS scene
  97407. * @param _origin The origin position of the vortex
  97408. * @param _radius The radius of the vortex
  97409. * @param _strength The strength of the vortex
  97410. * @param _height The height of the vortex
  97411. */
  97412. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  97413. this._scene = _scene;
  97414. this._origin = _origin;
  97415. this._radius = _radius;
  97416. this._strength = _strength;
  97417. this._height = _height;
  97418. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97419. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  97420. this._updraftMultiplier = 0.02;
  97421. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97422. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97423. this._physicsEngine = this._scene.getPhysicsEngine();
  97424. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97425. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97426. this._tickCallback = this._tick.bind(this);
  97427. }
  97428. /**
  97429. * Returns the data related to the vortex event (cylinder).
  97430. * @returns The physics vortex event data
  97431. */
  97432. PhysicsVortexEvent.prototype.getData = function () {
  97433. this._dataFetched = true;
  97434. return {
  97435. cylinder: this._cylinder,
  97436. };
  97437. };
  97438. /**
  97439. * Enables the vortex.
  97440. */
  97441. PhysicsVortexEvent.prototype.enable = function () {
  97442. this._tickCallback.call(this);
  97443. this._scene.registerBeforeRender(this._tickCallback);
  97444. };
  97445. /**
  97446. * Disables the cortex.
  97447. */
  97448. PhysicsVortexEvent.prototype.disable = function () {
  97449. this._scene.unregisterBeforeRender(this._tickCallback);
  97450. };
  97451. /**
  97452. * Disposes the sphere.
  97453. * @param force
  97454. */
  97455. PhysicsVortexEvent.prototype.dispose = function (force) {
  97456. var _this = this;
  97457. if (force === void 0) { force = true; }
  97458. if (force) {
  97459. this._cylinder.dispose();
  97460. }
  97461. else {
  97462. setTimeout(function () {
  97463. if (!_this._dataFetched) {
  97464. _this._cylinder.dispose();
  97465. }
  97466. }, 0);
  97467. }
  97468. };
  97469. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97470. if (impostor.mass === 0) {
  97471. return null;
  97472. }
  97473. if (!this._intersectsWithCylinder(impostor)) {
  97474. return null;
  97475. }
  97476. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97477. return null;
  97478. }
  97479. var impostorObjectCenter = impostor.getObjectCenter();
  97480. 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)
  97481. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  97482. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  97483. var hit = ray.intersectsMesh(impostor.object);
  97484. var contactPoint = hit.pickedPoint;
  97485. if (!contactPoint) {
  97486. return null;
  97487. }
  97488. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  97489. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  97490. var directionToOrigin = contactPoint.normalize();
  97491. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97492. directionToOrigin = directionToOrigin.negate();
  97493. }
  97494. // TODO: find a more physically based solution
  97495. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97496. var forceX = directionToOrigin.x * this._strength / 8;
  97497. var forceY = directionToOrigin.y * this._updraftMultiplier;
  97498. var forceZ = directionToOrigin.z * this._strength / 8;
  97499. }
  97500. else {
  97501. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  97502. var forceY = this._originTop.y * this._updraftMultiplier;
  97503. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  97504. }
  97505. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  97506. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  97507. return { force: force, contactPoint: impostorObjectCenter };
  97508. };
  97509. PhysicsVortexEvent.prototype._tick = function () {
  97510. var _this = this;
  97511. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97512. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97513. if (!impostorForceAndContactPoint) {
  97514. return;
  97515. }
  97516. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97517. });
  97518. };
  97519. /*** Helpers ***/
  97520. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  97521. if (!this._cylinder) {
  97522. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  97523. height: this._height,
  97524. diameter: this._radius * 2,
  97525. }, this._scene);
  97526. this._cylinder.isVisible = false;
  97527. }
  97528. };
  97529. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  97530. var impostorObject = impostor.object;
  97531. this._prepareCylinder();
  97532. this._cylinder.position = this._cylinderPosition;
  97533. return this._cylinder.intersectsMesh(impostorObject, true);
  97534. };
  97535. return PhysicsVortexEvent;
  97536. }());
  97537. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  97538. /**
  97539. * The strenght of the force in correspondence to the distance of the affected object
  97540. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97541. */
  97542. var PhysicsRadialImpulseFalloff;
  97543. (function (PhysicsRadialImpulseFalloff) {
  97544. /** Defines that impulse is constant in strength across it's whole radius */
  97545. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  97546. /** DEfines that impulse gets weaker if it's further from the origin */
  97547. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  97548. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  97549. /**
  97550. * The strength of the force in correspondence to the distance of the affected object
  97551. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97552. */
  97553. var PhysicsUpdraftMode;
  97554. (function (PhysicsUpdraftMode) {
  97555. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  97556. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  97557. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  97558. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  97559. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  97560. })(BABYLON || (BABYLON = {}));
  97561. //# sourceMappingURL=babylon.physicsHelper.js.map
  97562. var BABYLON;
  97563. (function (BABYLON) {
  97564. /** @hidden */
  97565. var CannonJSPlugin = /** @class */ (function () {
  97566. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  97567. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  97568. if (iterations === void 0) { iterations = 10; }
  97569. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  97570. this.name = "CannonJSPlugin";
  97571. this._physicsMaterials = new Array();
  97572. this._fixedTimeStep = 1 / 60;
  97573. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  97574. this.BJSCANNON = CANNON;
  97575. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  97576. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  97577. this._tmpPosition = BABYLON.Vector3.Zero();
  97578. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  97579. this._tmpUnityRotation = new BABYLON.Quaternion();
  97580. if (!this.isSupported()) {
  97581. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  97582. return;
  97583. }
  97584. this._extendNamespace();
  97585. this.world = new this.BJSCANNON.World();
  97586. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  97587. this.world.solver.iterations = iterations;
  97588. }
  97589. CannonJSPlugin.prototype.setGravity = function (gravity) {
  97590. this.world.gravity.copy(gravity);
  97591. };
  97592. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  97593. this._fixedTimeStep = timeStep;
  97594. };
  97595. CannonJSPlugin.prototype.getTimeStep = function () {
  97596. return this._fixedTimeStep;
  97597. };
  97598. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  97599. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  97600. };
  97601. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  97602. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97603. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97604. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  97605. };
  97606. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  97607. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97608. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97609. impostor.physicsBody.applyForce(impulse, worldPoint);
  97610. };
  97611. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  97612. //parent-child relationship. Does this impostor has a parent impostor?
  97613. if (impostor.parent) {
  97614. if (impostor.physicsBody) {
  97615. this.removePhysicsBody(impostor);
  97616. //TODO is that needed?
  97617. impostor.forceUpdate();
  97618. }
  97619. return;
  97620. }
  97621. //should a new body be created for this impostor?
  97622. if (impostor.isBodyInitRequired()) {
  97623. var shape = this._createShape(impostor);
  97624. //unregister events, if body is being changed
  97625. var oldBody = impostor.physicsBody;
  97626. if (oldBody) {
  97627. this.removePhysicsBody(impostor);
  97628. }
  97629. //create the body and material
  97630. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  97631. var bodyCreationObject = {
  97632. mass: impostor.getParam("mass"),
  97633. material: material
  97634. };
  97635. // A simple extend, in case native options were used.
  97636. var nativeOptions = impostor.getParam("nativeOptions");
  97637. for (var key in nativeOptions) {
  97638. if (nativeOptions.hasOwnProperty(key)) {
  97639. bodyCreationObject[key] = nativeOptions[key];
  97640. }
  97641. }
  97642. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  97643. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  97644. this.world.addEventListener("preStep", impostor.beforeStep);
  97645. this.world.addEventListener("postStep", impostor.afterStep);
  97646. impostor.physicsBody.addShape(shape);
  97647. this.world.add(impostor.physicsBody);
  97648. //try to keep the body moving in the right direction by taking old properties.
  97649. //Should be tested!
  97650. if (oldBody) {
  97651. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  97652. impostor.physicsBody[param].copy(oldBody[param]);
  97653. });
  97654. }
  97655. this._processChildMeshes(impostor);
  97656. }
  97657. //now update the body's transformation
  97658. this._updatePhysicsBodyTransformation(impostor);
  97659. };
  97660. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  97661. var _this = this;
  97662. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  97663. var currentRotation = mainImpostor.object.rotationQuaternion;
  97664. if (meshChildren.length) {
  97665. var processMesh = function (localPosition, mesh) {
  97666. if (!currentRotation || !mesh.rotationQuaternion) {
  97667. return;
  97668. }
  97669. var childImpostor = mesh.getPhysicsImpostor();
  97670. if (childImpostor) {
  97671. var parent = childImpostor.parent;
  97672. if (parent !== mainImpostor) {
  97673. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  97674. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  97675. if (childImpostor.physicsBody) {
  97676. _this.removePhysicsBody(childImpostor);
  97677. childImpostor.physicsBody = null;
  97678. }
  97679. childImpostor.parent = mainImpostor;
  97680. childImpostor.resetUpdateFlags();
  97681. 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));
  97682. //Add the mass of the children.
  97683. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  97684. }
  97685. }
  97686. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  97687. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  97688. };
  97689. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  97690. }
  97691. };
  97692. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97693. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  97694. this.world.removeEventListener("preStep", impostor.beforeStep);
  97695. this.world.removeEventListener("postStep", impostor.afterStep);
  97696. this.world.remove(impostor.physicsBody);
  97697. };
  97698. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97699. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97700. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97701. if (!mainBody || !connectedBody) {
  97702. return;
  97703. }
  97704. var constraint;
  97705. var jointData = impostorJoint.joint.jointData;
  97706. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  97707. var constraintData = {
  97708. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  97709. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  97710. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  97711. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  97712. maxForce: jointData.nativeParams.maxForce,
  97713. collideConnected: !!jointData.collision
  97714. };
  97715. switch (impostorJoint.joint.type) {
  97716. case BABYLON.PhysicsJoint.HingeJoint:
  97717. case BABYLON.PhysicsJoint.Hinge2Joint:
  97718. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  97719. break;
  97720. case BABYLON.PhysicsJoint.DistanceJoint:
  97721. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  97722. break;
  97723. case BABYLON.PhysicsJoint.SpringJoint:
  97724. var springData = jointData;
  97725. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  97726. restLength: springData.length,
  97727. stiffness: springData.stiffness,
  97728. damping: springData.damping,
  97729. localAnchorA: constraintData.pivotA,
  97730. localAnchorB: constraintData.pivotB
  97731. });
  97732. break;
  97733. case BABYLON.PhysicsJoint.LockJoint:
  97734. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  97735. break;
  97736. case BABYLON.PhysicsJoint.PointToPointJoint:
  97737. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97738. default:
  97739. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  97740. break;
  97741. }
  97742. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  97743. constraint.collideConnected = !!jointData.collision;
  97744. impostorJoint.joint.physicsJoint = constraint;
  97745. //don't add spring as constraint, as it is not one.
  97746. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97747. this.world.addConstraint(constraint);
  97748. }
  97749. else {
  97750. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  97751. constraint.applyForce();
  97752. };
  97753. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97754. }
  97755. };
  97756. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97757. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97758. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  97759. }
  97760. else {
  97761. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97762. }
  97763. };
  97764. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  97765. var index;
  97766. var mat;
  97767. for (index = 0; index < this._physicsMaterials.length; index++) {
  97768. mat = this._physicsMaterials[index];
  97769. if (mat.friction === friction && mat.restitution === restitution) {
  97770. return mat;
  97771. }
  97772. }
  97773. var currentMat = new this.BJSCANNON.Material(name);
  97774. currentMat.friction = friction;
  97775. currentMat.restitution = restitution;
  97776. this._physicsMaterials.push(currentMat);
  97777. return currentMat;
  97778. };
  97779. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  97780. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  97781. };
  97782. CannonJSPlugin.prototype._createShape = function (impostor) {
  97783. var object = impostor.object;
  97784. var returnValue;
  97785. var extendSize = impostor.getObjectExtendSize();
  97786. switch (impostor.type) {
  97787. case BABYLON.PhysicsImpostor.SphereImpostor:
  97788. var radiusX = extendSize.x;
  97789. var radiusY = extendSize.y;
  97790. var radiusZ = extendSize.z;
  97791. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  97792. break;
  97793. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  97794. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97795. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  97796. break;
  97797. case BABYLON.PhysicsImpostor.BoxImpostor:
  97798. var box = extendSize.scale(0.5);
  97799. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  97800. break;
  97801. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97802. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  97803. returnValue = new this.BJSCANNON.Plane();
  97804. break;
  97805. case BABYLON.PhysicsImpostor.MeshImpostor:
  97806. // should transform the vertex data to world coordinates!!
  97807. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  97808. var rawFaces = object.getIndices ? object.getIndices() : [];
  97809. if (!rawVerts) {
  97810. return;
  97811. }
  97812. // get only scale! so the object could transform correctly.
  97813. var oldPosition = object.position.clone();
  97814. var oldRotation = object.rotation && object.rotation.clone();
  97815. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  97816. object.position.copyFromFloats(0, 0, 0);
  97817. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97818. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97819. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97820. var transform = object.computeWorldMatrix(true);
  97821. // convert rawVerts to object space
  97822. var temp = new Array();
  97823. var index;
  97824. for (index = 0; index < rawVerts.length; index += 3) {
  97825. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  97826. }
  97827. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  97828. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  97829. //now set back the transformation!
  97830. object.position.copyFrom(oldPosition);
  97831. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  97832. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  97833. break;
  97834. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  97835. var oldPosition2 = object.position.clone();
  97836. var oldRotation2 = object.rotation && object.rotation.clone();
  97837. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  97838. object.position.copyFromFloats(0, 0, 0);
  97839. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97840. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97841. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97842. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  97843. returnValue = this._createHeightmap(object);
  97844. object.position.copyFrom(oldPosition2);
  97845. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  97846. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  97847. object.computeWorldMatrix(true);
  97848. break;
  97849. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97850. returnValue = new this.BJSCANNON.Particle();
  97851. break;
  97852. }
  97853. return returnValue;
  97854. };
  97855. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  97856. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97857. var transform = object.computeWorldMatrix(true);
  97858. // convert rawVerts to object space
  97859. var temp = new Array();
  97860. var index;
  97861. for (index = 0; index < pos.length; index += 3) {
  97862. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  97863. }
  97864. pos = temp;
  97865. var matrix = new Array();
  97866. //For now pointDepth will not be used and will be automatically calculated.
  97867. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  97868. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  97869. var boundingInfo = object.getBoundingInfo();
  97870. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  97871. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  97872. var elementSize = dim * 2 / arraySize;
  97873. for (var i = 0; i < pos.length; i = i + 3) {
  97874. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  97875. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  97876. var y = -pos[i + 2] + minY;
  97877. if (!matrix[x]) {
  97878. matrix[x] = [];
  97879. }
  97880. if (!matrix[x][z]) {
  97881. matrix[x][z] = y;
  97882. }
  97883. matrix[x][z] = Math.max(y, matrix[x][z]);
  97884. }
  97885. for (var x = 0; x <= arraySize; ++x) {
  97886. if (!matrix[x]) {
  97887. var loc = 1;
  97888. while (!matrix[(x + loc) % arraySize]) {
  97889. loc++;
  97890. }
  97891. matrix[x] = matrix[(x + loc) % arraySize].slice();
  97892. //console.log("missing x", x);
  97893. }
  97894. for (var z = 0; z <= arraySize; ++z) {
  97895. if (!matrix[x][z]) {
  97896. var loc = 1;
  97897. var newValue;
  97898. while (newValue === undefined) {
  97899. newValue = matrix[x][(z + loc++) % arraySize];
  97900. }
  97901. matrix[x][z] = newValue;
  97902. }
  97903. }
  97904. }
  97905. var shape = new this.BJSCANNON.Heightfield(matrix, {
  97906. elementSize: elementSize
  97907. });
  97908. //For future reference, needed for body transformation
  97909. shape.minY = minY;
  97910. return shape;
  97911. };
  97912. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  97913. var object = impostor.object;
  97914. //make sure it is updated...
  97915. object.computeWorldMatrix && object.computeWorldMatrix(true);
  97916. // The delta between the mesh position and the mesh bounding box center
  97917. var bInfo = object.getBoundingInfo();
  97918. if (!bInfo) {
  97919. return;
  97920. }
  97921. var center = impostor.getObjectCenter();
  97922. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  97923. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  97924. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  97925. this._tmpPosition.copyFrom(center);
  97926. var quaternion = object.rotationQuaternion;
  97927. if (!quaternion) {
  97928. return;
  97929. }
  97930. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  97931. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  97932. //-90 DEG in X, precalculated
  97933. quaternion = quaternion.multiply(this._minus90X);
  97934. //Invert! (Precalculated, 90 deg in X)
  97935. //No need to clone. this will never change.
  97936. impostor.setDeltaRotation(this._plus90X);
  97937. }
  97938. //If it is a heightfield, if should be centered.
  97939. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  97940. var mesh = object;
  97941. var boundingInfo = mesh.getBoundingInfo();
  97942. //calculate the correct body position:
  97943. var rotationQuaternion = mesh.rotationQuaternion;
  97944. mesh.rotationQuaternion = this._tmpUnityRotation;
  97945. mesh.computeWorldMatrix(true);
  97946. //get original center with no rotation
  97947. var c = center.clone();
  97948. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  97949. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  97950. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  97951. mesh.setPreTransformMatrix(p);
  97952. mesh.computeWorldMatrix(true);
  97953. //calculate the translation
  97954. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  97955. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  97956. //add it inverted to the delta
  97957. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  97958. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  97959. //rotation is back
  97960. mesh.rotationQuaternion = rotationQuaternion;
  97961. mesh.setPreTransformMatrix(oldPivot);
  97962. mesh.computeWorldMatrix(true);
  97963. }
  97964. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  97965. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  97966. //this._tmpPosition.copyFrom(object.position);
  97967. }
  97968. impostor.setDeltaPosition(this._tmpDeltaPosition);
  97969. //Now update the impostor object
  97970. impostor.physicsBody.position.copy(this._tmpPosition);
  97971. impostor.physicsBody.quaternion.copy(quaternion);
  97972. };
  97973. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97974. impostor.object.position.copyFrom(impostor.physicsBody.position);
  97975. if (impostor.object.rotationQuaternion) {
  97976. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  97977. }
  97978. };
  97979. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97980. impostor.physicsBody.position.copy(newPosition);
  97981. impostor.physicsBody.quaternion.copy(newRotation);
  97982. };
  97983. CannonJSPlugin.prototype.isSupported = function () {
  97984. return this.BJSCANNON !== undefined;
  97985. };
  97986. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97987. impostor.physicsBody.velocity.copy(velocity);
  97988. };
  97989. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97990. impostor.physicsBody.angularVelocity.copy(velocity);
  97991. };
  97992. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97993. var v = impostor.physicsBody.velocity;
  97994. if (!v) {
  97995. return null;
  97996. }
  97997. return new BABYLON.Vector3(v.x, v.y, v.z);
  97998. };
  97999. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98000. var v = impostor.physicsBody.angularVelocity;
  98001. if (!v) {
  98002. return null;
  98003. }
  98004. return new BABYLON.Vector3(v.x, v.y, v.z);
  98005. };
  98006. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98007. impostor.physicsBody.mass = mass;
  98008. impostor.physicsBody.updateMassProperties();
  98009. };
  98010. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98011. return impostor.physicsBody.mass;
  98012. };
  98013. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98014. return impostor.physicsBody.material.friction;
  98015. };
  98016. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98017. impostor.physicsBody.material.friction = friction;
  98018. };
  98019. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98020. return impostor.physicsBody.material.restitution;
  98021. };
  98022. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98023. impostor.physicsBody.material.restitution = restitution;
  98024. };
  98025. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98026. impostor.physicsBody.sleep();
  98027. };
  98028. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98029. impostor.physicsBody.wakeUp();
  98030. };
  98031. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98032. joint.physicsJoint.distance = maxDistance;
  98033. };
  98034. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98035. // if (!motorIndex) {
  98036. // joint.physicsJoint.enableMotor();
  98037. // }
  98038. // }
  98039. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98040. // if (!motorIndex) {
  98041. // joint.physicsJoint.disableMotor();
  98042. // }
  98043. // }
  98044. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98045. if (!motorIndex) {
  98046. joint.physicsJoint.enableMotor();
  98047. joint.physicsJoint.setMotorSpeed(speed);
  98048. if (maxForce) {
  98049. this.setLimit(joint, maxForce);
  98050. }
  98051. }
  98052. };
  98053. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98054. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98055. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98056. };
  98057. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98058. var body = impostor.physicsBody;
  98059. mesh.position.x = body.position.x;
  98060. mesh.position.y = body.position.y;
  98061. mesh.position.z = body.position.z;
  98062. if (mesh.rotationQuaternion) {
  98063. mesh.rotationQuaternion.x = body.quaternion.x;
  98064. mesh.rotationQuaternion.y = body.quaternion.y;
  98065. mesh.rotationQuaternion.z = body.quaternion.z;
  98066. mesh.rotationQuaternion.w = body.quaternion.w;
  98067. }
  98068. };
  98069. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98070. var shape = impostor.physicsBody.shapes[0];
  98071. return shape.boundingSphereRadius;
  98072. };
  98073. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98074. var shape = impostor.physicsBody.shapes[0];
  98075. result.x = shape.halfExtents.x * 2;
  98076. result.y = shape.halfExtents.y * 2;
  98077. result.z = shape.halfExtents.z * 2;
  98078. };
  98079. CannonJSPlugin.prototype.dispose = function () {
  98080. };
  98081. CannonJSPlugin.prototype._extendNamespace = function () {
  98082. //this will force cannon to execute at least one step when using interpolation
  98083. var step_tmp1 = new this.BJSCANNON.Vec3();
  98084. var Engine = this.BJSCANNON;
  98085. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98086. maxSubSteps = maxSubSteps || 10;
  98087. timeSinceLastCalled = timeSinceLastCalled || 0;
  98088. if (timeSinceLastCalled === 0) {
  98089. this.internalStep(dt);
  98090. this.time += dt;
  98091. }
  98092. else {
  98093. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98094. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98095. var t0 = performance.now();
  98096. for (var i = 0; i !== internalSteps; i++) {
  98097. this.internalStep(dt);
  98098. if (performance.now() - t0 > dt * 1000) {
  98099. break;
  98100. }
  98101. }
  98102. this.time += timeSinceLastCalled;
  98103. var h = this.time % dt;
  98104. var h_div_dt = h / dt;
  98105. var interpvelo = step_tmp1;
  98106. var bodies = this.bodies;
  98107. for (var j = 0; j !== bodies.length; j++) {
  98108. var b = bodies[j];
  98109. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98110. b.position.vsub(b.previousPosition, interpvelo);
  98111. interpvelo.scale(h_div_dt, interpvelo);
  98112. b.position.vadd(interpvelo, b.interpolatedPosition);
  98113. }
  98114. else {
  98115. b.interpolatedPosition.copy(b.position);
  98116. b.interpolatedQuaternion.copy(b.quaternion);
  98117. }
  98118. }
  98119. }
  98120. };
  98121. };
  98122. return CannonJSPlugin;
  98123. }());
  98124. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98125. })(BABYLON || (BABYLON = {}));
  98126. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  98127. var BABYLON;
  98128. (function (BABYLON) {
  98129. /** @hidden */
  98130. var OimoJSPlugin = /** @class */ (function () {
  98131. function OimoJSPlugin(iterations) {
  98132. this.name = "OimoJSPlugin";
  98133. this._tmpImpostorsArray = [];
  98134. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98135. this.BJSOIMO = OIMO;
  98136. this.world = new this.BJSOIMO.World({
  98137. iterations: iterations
  98138. });
  98139. this.world.clear();
  98140. }
  98141. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98142. this.world.gravity.copy(gravity);
  98143. };
  98144. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98145. this.world.timeStep = timeStep;
  98146. };
  98147. OimoJSPlugin.prototype.getTimeStep = function () {
  98148. return this.world.timeStep;
  98149. };
  98150. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98151. var _this = this;
  98152. impostors.forEach(function (impostor) {
  98153. impostor.beforeStep();
  98154. });
  98155. this.world.step();
  98156. impostors.forEach(function (impostor) {
  98157. impostor.afterStep();
  98158. //update the ordered impostors array
  98159. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98160. });
  98161. //check for collisions
  98162. var contact = this.world.contacts;
  98163. while (contact !== null) {
  98164. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98165. contact = contact.next;
  98166. continue;
  98167. }
  98168. //is this body colliding with any other? get the impostor
  98169. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98170. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98171. if (!mainImpostor || !collidingImpostor) {
  98172. contact = contact.next;
  98173. continue;
  98174. }
  98175. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98176. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98177. contact = contact.next;
  98178. }
  98179. };
  98180. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98181. var mass = impostor.physicsBody.mass;
  98182. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98183. };
  98184. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98185. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98186. this.applyImpulse(impostor, force, contactPoint);
  98187. };
  98188. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98189. var _this = this;
  98190. //parent-child relationship. Does this impostor has a parent impostor?
  98191. if (impostor.parent) {
  98192. if (impostor.physicsBody) {
  98193. this.removePhysicsBody(impostor);
  98194. //TODO is that needed?
  98195. impostor.forceUpdate();
  98196. }
  98197. return;
  98198. }
  98199. if (impostor.isBodyInitRequired()) {
  98200. var bodyConfig = {
  98201. name: impostor.uniqueId,
  98202. //Oimo must have mass, also for static objects.
  98203. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98204. size: [],
  98205. type: [],
  98206. pos: [],
  98207. posShape: [],
  98208. rot: [],
  98209. rotShape: [],
  98210. move: impostor.getParam("mass") !== 0,
  98211. density: impostor.getParam("mass"),
  98212. friction: impostor.getParam("friction"),
  98213. restitution: impostor.getParam("restitution"),
  98214. //Supporting older versions of Oimo
  98215. world: this.world
  98216. };
  98217. var impostors = [impostor];
  98218. var addToArray = function (parent) {
  98219. if (!parent.getChildMeshes) {
  98220. return;
  98221. }
  98222. parent.getChildMeshes().forEach(function (m) {
  98223. if (m.physicsImpostor) {
  98224. impostors.push(m.physicsImpostor);
  98225. //m.physicsImpostor._init();
  98226. }
  98227. });
  98228. };
  98229. addToArray(impostor.object);
  98230. var checkWithEpsilon_1 = function (value) {
  98231. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98232. };
  98233. var globalQuaternion_1 = new BABYLON.Quaternion();
  98234. impostors.forEach(function (i) {
  98235. if (!i.object.rotationQuaternion) {
  98236. return;
  98237. }
  98238. //get the correct bounding box
  98239. var oldQuaternion = i.object.rotationQuaternion;
  98240. globalQuaternion_1 = oldQuaternion.clone();
  98241. var rot = oldQuaternion.toEulerAngles();
  98242. var extendSize = i.getObjectExtendSize();
  98243. var radToDeg = 57.295779513082320876;
  98244. if (i === impostor) {
  98245. var center = impostor.getObjectCenter();
  98246. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98247. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98248. //Can also use Array.prototype.push.apply
  98249. bodyConfig.pos.push(center.x);
  98250. bodyConfig.pos.push(center.y);
  98251. bodyConfig.pos.push(center.z);
  98252. bodyConfig.posShape.push(0, 0, 0);
  98253. //tmp solution
  98254. bodyConfig.rot.push(0);
  98255. bodyConfig.rot.push(0);
  98256. bodyConfig.rot.push(0);
  98257. bodyConfig.rotShape.push(0, 0, 0);
  98258. }
  98259. else {
  98260. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98261. bodyConfig.posShape.push(localPosition.x);
  98262. bodyConfig.posShape.push(localPosition.y);
  98263. bodyConfig.posShape.push(localPosition.z);
  98264. bodyConfig.pos.push(0, 0, 0);
  98265. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  98266. bodyConfig.rot.push(0);
  98267. bodyConfig.rot.push(0);
  98268. bodyConfig.rot.push(0);
  98269. bodyConfig.rotShape.push(rot.x * radToDeg);
  98270. bodyConfig.rotShape.push(rot.y * radToDeg);
  98271. bodyConfig.rotShape.push(rot.z * radToDeg);
  98272. }
  98273. // register mesh
  98274. switch (i.type) {
  98275. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98276. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98277. case BABYLON.PhysicsImpostor.SphereImpostor:
  98278. var radiusX = extendSize.x;
  98279. var radiusY = extendSize.y;
  98280. var radiusZ = extendSize.z;
  98281. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98282. bodyConfig.type.push('sphere');
  98283. //due to the way oimo works with compounds, add 3 times
  98284. bodyConfig.size.push(size);
  98285. bodyConfig.size.push(size);
  98286. bodyConfig.size.push(size);
  98287. break;
  98288. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98289. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98290. var sizeY = checkWithEpsilon_1(extendSize.y);
  98291. bodyConfig.type.push('cylinder');
  98292. bodyConfig.size.push(sizeX);
  98293. bodyConfig.size.push(sizeY);
  98294. //due to the way oimo works with compounds, add one more value.
  98295. bodyConfig.size.push(sizeY);
  98296. break;
  98297. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98298. case BABYLON.PhysicsImpostor.BoxImpostor:
  98299. default:
  98300. var sizeX = checkWithEpsilon_1(extendSize.x);
  98301. var sizeY = checkWithEpsilon_1(extendSize.y);
  98302. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98303. bodyConfig.type.push('box');
  98304. //if (i === impostor) {
  98305. bodyConfig.size.push(sizeX);
  98306. bodyConfig.size.push(sizeY);
  98307. bodyConfig.size.push(sizeZ);
  98308. //} else {
  98309. // bodyConfig.size.push(0,0,0);
  98310. //}
  98311. break;
  98312. }
  98313. //actually not needed, but hey...
  98314. i.object.rotationQuaternion = oldQuaternion;
  98315. });
  98316. impostor.physicsBody = this.world.add(bodyConfig);
  98317. // set the quaternion, ignoring the previously defined (euler) rotation
  98318. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98319. // update with delta 0, so the body will reveive the new rotation.
  98320. impostor.physicsBody.updatePosition(0);
  98321. }
  98322. else {
  98323. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98324. }
  98325. impostor.setDeltaPosition(this._tmpPositionVector);
  98326. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98327. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98328. };
  98329. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98330. //impostor.physicsBody.dispose();
  98331. //Same as : (older oimo versions)
  98332. this.world.removeRigidBody(impostor.physicsBody);
  98333. };
  98334. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98335. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98336. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98337. if (!mainBody || !connectedBody) {
  98338. return;
  98339. }
  98340. var jointData = impostorJoint.joint.jointData;
  98341. var options = jointData.nativeParams || {};
  98342. var type;
  98343. var nativeJointData = {
  98344. body1: mainBody,
  98345. body2: connectedBody,
  98346. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98347. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98348. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98349. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98350. min: options.min,
  98351. max: options.max,
  98352. collision: options.collision || jointData.collision,
  98353. spring: options.spring,
  98354. //supporting older version of Oimo
  98355. world: this.world
  98356. };
  98357. switch (impostorJoint.joint.type) {
  98358. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98359. type = "jointBall";
  98360. break;
  98361. case BABYLON.PhysicsJoint.SpringJoint:
  98362. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98363. var springData = jointData;
  98364. nativeJointData.min = springData.length || nativeJointData.min;
  98365. //Max should also be set, just make sure it is at least min
  98366. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98367. case BABYLON.PhysicsJoint.DistanceJoint:
  98368. type = "jointDistance";
  98369. nativeJointData.max = jointData.maxDistance;
  98370. break;
  98371. case BABYLON.PhysicsJoint.PrismaticJoint:
  98372. type = "jointPrisme";
  98373. break;
  98374. case BABYLON.PhysicsJoint.SliderJoint:
  98375. type = "jointSlide";
  98376. break;
  98377. case BABYLON.PhysicsJoint.WheelJoint:
  98378. type = "jointWheel";
  98379. break;
  98380. case BABYLON.PhysicsJoint.HingeJoint:
  98381. default:
  98382. type = "jointHinge";
  98383. break;
  98384. }
  98385. nativeJointData.type = type;
  98386. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98387. };
  98388. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98389. //Bug in Oimo prevents us from disposing a joint in the playground
  98390. //joint.joint.physicsJoint.dispose();
  98391. //So we will bruteforce it!
  98392. try {
  98393. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98394. }
  98395. catch (e) {
  98396. BABYLON.Tools.Warn(e);
  98397. }
  98398. };
  98399. OimoJSPlugin.prototype.isSupported = function () {
  98400. return this.BJSOIMO !== undefined;
  98401. };
  98402. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98403. if (!impostor.physicsBody.sleeping) {
  98404. //TODO check that
  98405. /*if (impostor.physicsBody.shapes.next) {
  98406. var parentShape = this._getLastShape(impostor.physicsBody);
  98407. impostor.object.position.copyFrom(parentShape.position);
  98408. console.log(parentShape.position);
  98409. } else {*/
  98410. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  98411. //}
  98412. if (impostor.object.rotationQuaternion) {
  98413. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  98414. }
  98415. }
  98416. };
  98417. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98418. var body = impostor.physicsBody;
  98419. body.position.copy(newPosition);
  98420. body.orientation.copy(newRotation);
  98421. body.syncShapes();
  98422. body.awake();
  98423. };
  98424. /*private _getLastShape(body: any): any {
  98425. var lastShape = body.shapes;
  98426. while (lastShape.next) {
  98427. lastShape = lastShape.next;
  98428. }
  98429. return lastShape;
  98430. }*/
  98431. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98432. impostor.physicsBody.linearVelocity.copy(velocity);
  98433. };
  98434. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98435. impostor.physicsBody.angularVelocity.copy(velocity);
  98436. };
  98437. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98438. var v = impostor.physicsBody.linearVelocity;
  98439. if (!v) {
  98440. return null;
  98441. }
  98442. return new BABYLON.Vector3(v.x, v.y, v.z);
  98443. };
  98444. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98445. var v = impostor.physicsBody.angularVelocity;
  98446. if (!v) {
  98447. return null;
  98448. }
  98449. return new BABYLON.Vector3(v.x, v.y, v.z);
  98450. };
  98451. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98452. var staticBody = mass === 0;
  98453. //this will actually set the body's density and not its mass.
  98454. //But this is how oimo treats the mass variable.
  98455. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  98456. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  98457. };
  98458. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  98459. return impostor.physicsBody.shapes.density;
  98460. };
  98461. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  98462. return impostor.physicsBody.shapes.friction;
  98463. };
  98464. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98465. impostor.physicsBody.shapes.friction = friction;
  98466. };
  98467. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98468. return impostor.physicsBody.shapes.restitution;
  98469. };
  98470. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98471. impostor.physicsBody.shapes.restitution = restitution;
  98472. };
  98473. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  98474. impostor.physicsBody.sleep();
  98475. };
  98476. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  98477. impostor.physicsBody.awake();
  98478. };
  98479. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98480. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  98481. if (minDistance !== void 0) {
  98482. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  98483. }
  98484. };
  98485. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98486. //TODO separate rotational and transational motors.
  98487. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98488. if (motor) {
  98489. motor.setMotor(speed, maxForce);
  98490. }
  98491. };
  98492. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  98493. //TODO separate rotational and transational motors.
  98494. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98495. if (motor) {
  98496. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  98497. }
  98498. };
  98499. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98500. var body = impostor.physicsBody;
  98501. mesh.position.x = body.position.x;
  98502. mesh.position.y = body.position.y;
  98503. mesh.position.z = body.position.z;
  98504. if (mesh.rotationQuaternion) {
  98505. mesh.rotationQuaternion.x = body.orientation.x;
  98506. mesh.rotationQuaternion.y = body.orientation.y;
  98507. mesh.rotationQuaternion.z = body.orientation.z;
  98508. mesh.rotationQuaternion.w = body.orientation.s;
  98509. }
  98510. };
  98511. OimoJSPlugin.prototype.getRadius = function (impostor) {
  98512. return impostor.physicsBody.shapes.radius;
  98513. };
  98514. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98515. var shape = impostor.physicsBody.shapes;
  98516. result.x = shape.halfWidth * 2;
  98517. result.y = shape.halfHeight * 2;
  98518. result.z = shape.halfDepth * 2;
  98519. };
  98520. OimoJSPlugin.prototype.dispose = function () {
  98521. this.world.clear();
  98522. };
  98523. return OimoJSPlugin;
  98524. }());
  98525. BABYLON.OimoJSPlugin = OimoJSPlugin;
  98526. })(BABYLON || (BABYLON = {}));
  98527. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  98528. var BABYLON;
  98529. (function (BABYLON) {
  98530. /**
  98531. * Gets the current physics engine
  98532. * @returns a IPhysicsEngine or null if none attached
  98533. */
  98534. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  98535. return this._physicsEngine;
  98536. };
  98537. /**
  98538. * Enables physics to the current scene
  98539. * @param gravity defines the scene's gravity for the physics engine
  98540. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  98541. * @return a boolean indicating if the physics engine was initialized
  98542. */
  98543. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  98544. if (gravity === void 0) { gravity = null; }
  98545. if (this._physicsEngine) {
  98546. return true;
  98547. }
  98548. // Register the component to the scene
  98549. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  98550. if (!component) {
  98551. component = new PhysicsEngineSceneComponent(this);
  98552. this._addComponent(component);
  98553. }
  98554. try {
  98555. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  98556. return true;
  98557. }
  98558. catch (e) {
  98559. BABYLON.Tools.Error(e.message);
  98560. return false;
  98561. }
  98562. };
  98563. /**
  98564. * Disables and disposes the physics engine associated with the scene
  98565. */
  98566. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  98567. if (!this._physicsEngine) {
  98568. return;
  98569. }
  98570. this._physicsEngine.dispose();
  98571. this._physicsEngine = null;
  98572. };
  98573. /**
  98574. * Gets a boolean indicating if there is an active physics engine
  98575. * @returns a boolean indicating if there is an active physics engine
  98576. */
  98577. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  98578. return this._physicsEngine !== undefined;
  98579. };
  98580. /**
  98581. * Deletes a physics compound impostor
  98582. * @param compound defines the compound to delete
  98583. */
  98584. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  98585. var mesh = compound.parts[0].mesh;
  98586. if (mesh.physicsImpostor) {
  98587. mesh.physicsImpostor.dispose( /*true*/);
  98588. mesh.physicsImpostor = null;
  98589. }
  98590. };
  98591. /** @hidden */
  98592. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  98593. if (this._physicsEngine) {
  98594. this.onBeforePhysicsObservable.notifyObservers(this);
  98595. this._physicsEngine._step(step / 1000);
  98596. this.onAfterPhysicsObservable.notifyObservers(this);
  98597. }
  98598. };
  98599. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  98600. get: function () {
  98601. return this._physicsImpostor;
  98602. },
  98603. set: function (value) {
  98604. var _this = this;
  98605. if (this._physicsImpostor === value) {
  98606. return;
  98607. }
  98608. if (this._disposePhysicsObserver) {
  98609. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  98610. }
  98611. this._physicsImpostor = value;
  98612. if (value) {
  98613. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  98614. // Physics
  98615. if (_this.physicsImpostor) {
  98616. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  98617. _this.physicsImpostor = null;
  98618. }
  98619. });
  98620. }
  98621. },
  98622. enumerable: true,
  98623. configurable: true
  98624. });
  98625. /**
  98626. * Gets the current physics impostor
  98627. * @see http://doc.babylonjs.com/features/physics_engine
  98628. * @returns a physics impostor or null
  98629. */
  98630. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  98631. return this.physicsImpostor;
  98632. };
  98633. /**
  98634. * Apply a physic impulse to the mesh
  98635. * @param force defines the force to apply
  98636. * @param contactPoint defines where to apply the force
  98637. * @returns the current mesh
  98638. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  98639. */
  98640. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  98641. if (!this.physicsImpostor) {
  98642. return this;
  98643. }
  98644. this.physicsImpostor.applyImpulse(force, contactPoint);
  98645. return this;
  98646. };
  98647. /**
  98648. * Creates a physic joint between two meshes
  98649. * @param otherMesh defines the other mesh to use
  98650. * @param pivot1 defines the pivot to use on this mesh
  98651. * @param pivot2 defines the pivot to use on the other mesh
  98652. * @param options defines additional options (can be plugin dependent)
  98653. * @returns the current mesh
  98654. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  98655. */
  98656. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  98657. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  98658. return this;
  98659. }
  98660. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  98661. mainPivot: pivot1,
  98662. connectedPivot: pivot2,
  98663. nativeParams: options
  98664. });
  98665. return this;
  98666. };
  98667. /**
  98668. * Defines the physics engine scene component responsible to manage a physics engine
  98669. */
  98670. var PhysicsEngineSceneComponent = /** @class */ (function () {
  98671. /**
  98672. * Creates a new instance of the component for the given scene
  98673. * @param scene Defines the scene to register the component in
  98674. */
  98675. function PhysicsEngineSceneComponent(scene) {
  98676. var _this = this;
  98677. /**
  98678. * The component name helpful to identify the component in the list of scene components.
  98679. */
  98680. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  98681. this.scene = scene;
  98682. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  98683. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  98684. // Replace the function used to get the deterministic frame time
  98685. this.scene.getDeterministicFrameTime = function () {
  98686. if (_this.scene._physicsEngine) {
  98687. return _this.scene._physicsEngine.getTimeStep() * 1000;
  98688. }
  98689. return 1000.0 / 60.0;
  98690. };
  98691. }
  98692. /**
  98693. * Registers the component in a given scene
  98694. */
  98695. PhysicsEngineSceneComponent.prototype.register = function () {
  98696. };
  98697. /**
  98698. * Rebuilds the elements related to this component in case of
  98699. * context lost for instance.
  98700. */
  98701. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  98702. // Nothing to do for this component
  98703. };
  98704. /**
  98705. * Disposes the component and the associated ressources
  98706. */
  98707. PhysicsEngineSceneComponent.prototype.dispose = function () {
  98708. this.scene.onBeforePhysicsObservable.clear();
  98709. this.scene.onAfterPhysicsObservable.clear();
  98710. if (this.scene._physicsEngine) {
  98711. this.scene.disablePhysicsEngine();
  98712. }
  98713. };
  98714. return PhysicsEngineSceneComponent;
  98715. }());
  98716. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  98717. })(BABYLON || (BABYLON = {}));
  98718. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  98719. var BABYLON;
  98720. (function (BABYLON) {
  98721. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  98722. // All values and structures referenced from:
  98723. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  98724. var DDS_MAGIC = 0x20534444;
  98725. var
  98726. //DDSD_CAPS = 0x1,
  98727. //DDSD_HEIGHT = 0x2,
  98728. //DDSD_WIDTH = 0x4,
  98729. //DDSD_PITCH = 0x8,
  98730. //DDSD_PIXELFORMAT = 0x1000,
  98731. DDSD_MIPMAPCOUNT = 0x20000;
  98732. //DDSD_LINEARSIZE = 0x80000,
  98733. //DDSD_DEPTH = 0x800000;
  98734. // var DDSCAPS_COMPLEX = 0x8,
  98735. // DDSCAPS_MIPMAP = 0x400000,
  98736. // DDSCAPS_TEXTURE = 0x1000;
  98737. var DDSCAPS2_CUBEMAP = 0x200;
  98738. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  98739. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  98740. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  98741. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  98742. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  98743. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  98744. // DDSCAPS2_VOLUME = 0x200000;
  98745. var
  98746. //DDPF_ALPHAPIXELS = 0x1,
  98747. //DDPF_ALPHA = 0x2,
  98748. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  98749. //DDPF_YUV = 0x200,
  98750. DDPF_LUMINANCE = 0x20000;
  98751. function FourCCToInt32(value) {
  98752. return value.charCodeAt(0) +
  98753. (value.charCodeAt(1) << 8) +
  98754. (value.charCodeAt(2) << 16) +
  98755. (value.charCodeAt(3) << 24);
  98756. }
  98757. function Int32ToFourCC(value) {
  98758. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  98759. }
  98760. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  98761. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  98762. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  98763. var FOURCC_DX10 = FourCCToInt32("DX10");
  98764. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  98765. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  98766. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  98767. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  98768. var headerLengthInt = 31; // The header length in 32 bit ints
  98769. // Offsets into the header array
  98770. var off_magic = 0;
  98771. var off_size = 1;
  98772. var off_flags = 2;
  98773. var off_height = 3;
  98774. var off_width = 4;
  98775. var off_mipmapCount = 7;
  98776. var off_pfFlags = 20;
  98777. var off_pfFourCC = 21;
  98778. var off_RGBbpp = 22;
  98779. var off_RMask = 23;
  98780. var off_GMask = 24;
  98781. var off_BMask = 25;
  98782. var off_AMask = 26;
  98783. // var off_caps1 = 27;
  98784. var off_caps2 = 28;
  98785. // var off_caps3 = 29;
  98786. // var off_caps4 = 30;
  98787. var off_dxgiFormat = 32;
  98788. /**
  98789. * Class used to provide DDS decompression tools
  98790. */
  98791. var DDSTools = /** @class */ (function () {
  98792. function DDSTools() {
  98793. }
  98794. /**
  98795. * Gets DDS information from an array buffer
  98796. * @param arrayBuffer defines the array buffer to read data from
  98797. * @returns the DDS information
  98798. */
  98799. DDSTools.GetDDSInfo = function (arrayBuffer) {
  98800. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  98801. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  98802. var mipmapCount = 1;
  98803. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  98804. mipmapCount = Math.max(1, header[off_mipmapCount]);
  98805. }
  98806. var fourCC = header[off_pfFourCC];
  98807. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  98808. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98809. switch (fourCC) {
  98810. case FOURCC_D3DFMT_R16G16B16A16F:
  98811. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98812. break;
  98813. case FOURCC_D3DFMT_R32G32B32A32F:
  98814. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98815. break;
  98816. case FOURCC_DX10:
  98817. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  98818. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98819. break;
  98820. }
  98821. }
  98822. return {
  98823. width: header[off_width],
  98824. height: header[off_height],
  98825. mipmapCount: mipmapCount,
  98826. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  98827. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  98828. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  98829. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  98830. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  98831. dxgiFormat: dxgiFormat,
  98832. textureType: textureType
  98833. };
  98834. };
  98835. DDSTools._ToHalfFloat = function (value) {
  98836. if (!DDSTools._FloatView) {
  98837. DDSTools._FloatView = new Float32Array(1);
  98838. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  98839. }
  98840. DDSTools._FloatView[0] = value;
  98841. var x = DDSTools._Int32View[0];
  98842. var bits = (x >> 16) & 0x8000; /* Get the sign */
  98843. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  98844. var e = (x >> 23) & 0xff; /* Using int is faster here */
  98845. /* If zero, or denormal, or exponent underflows too much for a denormal
  98846. * half, return signed zero. */
  98847. if (e < 103) {
  98848. return bits;
  98849. }
  98850. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  98851. if (e > 142) {
  98852. bits |= 0x7c00;
  98853. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  98854. * not Inf, so make sure we set one mantissa bit too. */
  98855. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  98856. return bits;
  98857. }
  98858. /* If exponent underflows but not too much, return a denormal */
  98859. if (e < 113) {
  98860. m |= 0x0800;
  98861. /* Extra rounding may overflow and set mantissa to 0 and exponent
  98862. * to 1, which is OK. */
  98863. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  98864. return bits;
  98865. }
  98866. bits |= ((e - 112) << 10) | (m >> 1);
  98867. bits += m & 1;
  98868. return bits;
  98869. };
  98870. DDSTools._FromHalfFloat = function (value) {
  98871. var s = (value & 0x8000) >> 15;
  98872. var e = (value & 0x7C00) >> 10;
  98873. var f = value & 0x03FF;
  98874. if (e === 0) {
  98875. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  98876. }
  98877. else if (e == 0x1F) {
  98878. return f ? NaN : ((s ? -1 : 1) * Infinity);
  98879. }
  98880. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  98881. };
  98882. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98883. var destArray = new Float32Array(dataLength);
  98884. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98885. var index = 0;
  98886. for (var y = 0; y < height; y++) {
  98887. for (var x = 0; x < width; x++) {
  98888. var srcPos = (x + y * width) * 4;
  98889. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  98890. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  98891. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  98892. if (DDSTools.StoreLODInAlphaChannel) {
  98893. destArray[index + 3] = lod;
  98894. }
  98895. else {
  98896. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  98897. }
  98898. index += 4;
  98899. }
  98900. }
  98901. return destArray;
  98902. };
  98903. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98904. if (DDSTools.StoreLODInAlphaChannel) {
  98905. var destArray = new Uint16Array(dataLength);
  98906. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98907. var index = 0;
  98908. for (var y = 0; y < height; y++) {
  98909. for (var x = 0; x < width; x++) {
  98910. var srcPos = (x + y * width) * 4;
  98911. destArray[index] = srcData[srcPos];
  98912. destArray[index + 1] = srcData[srcPos + 1];
  98913. destArray[index + 2] = srcData[srcPos + 2];
  98914. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  98915. index += 4;
  98916. }
  98917. }
  98918. return destArray;
  98919. }
  98920. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  98921. };
  98922. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98923. if (DDSTools.StoreLODInAlphaChannel) {
  98924. var destArray = new Float32Array(dataLength);
  98925. var srcData = new Float32Array(arrayBuffer, dataOffset);
  98926. var index = 0;
  98927. for (var y = 0; y < height; y++) {
  98928. for (var x = 0; x < width; x++) {
  98929. var srcPos = (x + y * width) * 4;
  98930. destArray[index] = srcData[srcPos];
  98931. destArray[index + 1] = srcData[srcPos + 1];
  98932. destArray[index + 2] = srcData[srcPos + 2];
  98933. destArray[index + 3] = lod;
  98934. index += 4;
  98935. }
  98936. }
  98937. return destArray;
  98938. }
  98939. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  98940. };
  98941. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98942. var destArray = new Uint8Array(dataLength);
  98943. var srcData = new Float32Array(arrayBuffer, dataOffset);
  98944. var index = 0;
  98945. for (var y = 0; y < height; y++) {
  98946. for (var x = 0; x < width; x++) {
  98947. var srcPos = (x + y * width) * 4;
  98948. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  98949. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  98950. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  98951. if (DDSTools.StoreLODInAlphaChannel) {
  98952. destArray[index + 3] = lod;
  98953. }
  98954. else {
  98955. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  98956. }
  98957. index += 4;
  98958. }
  98959. }
  98960. return destArray;
  98961. };
  98962. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98963. var destArray = new Uint8Array(dataLength);
  98964. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98965. var index = 0;
  98966. for (var y = 0; y < height; y++) {
  98967. for (var x = 0; x < width; x++) {
  98968. var srcPos = (x + y * width) * 4;
  98969. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  98970. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  98971. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  98972. if (DDSTools.StoreLODInAlphaChannel) {
  98973. destArray[index + 3] = lod;
  98974. }
  98975. else {
  98976. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  98977. }
  98978. index += 4;
  98979. }
  98980. }
  98981. return destArray;
  98982. };
  98983. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  98984. var byteArray = new Uint8Array(dataLength);
  98985. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  98986. var index = 0;
  98987. for (var y = 0; y < height; y++) {
  98988. for (var x = 0; x < width; x++) {
  98989. var srcPos = (x + y * width) * 4;
  98990. byteArray[index] = srcData[srcPos + rOffset];
  98991. byteArray[index + 1] = srcData[srcPos + gOffset];
  98992. byteArray[index + 2] = srcData[srcPos + bOffset];
  98993. byteArray[index + 3] = srcData[srcPos + aOffset];
  98994. index += 4;
  98995. }
  98996. }
  98997. return byteArray;
  98998. };
  98999. DDSTools._ExtractLongWordOrder = function (value) {
  99000. if (value === 0 || value === 255 || value === -16777216) {
  99001. return 0;
  99002. }
  99003. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99004. };
  99005. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99006. var byteArray = new Uint8Array(dataLength);
  99007. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99008. var index = 0;
  99009. for (var y = 0; y < height; y++) {
  99010. for (var x = 0; x < width; x++) {
  99011. var srcPos = (x + y * width) * 3;
  99012. byteArray[index] = srcData[srcPos + rOffset];
  99013. byteArray[index + 1] = srcData[srcPos + gOffset];
  99014. byteArray[index + 2] = srcData[srcPos + bOffset];
  99015. index += 3;
  99016. }
  99017. }
  99018. return byteArray;
  99019. };
  99020. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99021. var byteArray = new Uint8Array(dataLength);
  99022. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99023. var index = 0;
  99024. for (var y = 0; y < height; y++) {
  99025. for (var x = 0; x < width; x++) {
  99026. var srcPos = (x + y * width);
  99027. byteArray[index] = srcData[srcPos];
  99028. index++;
  99029. }
  99030. }
  99031. return byteArray;
  99032. };
  99033. /**
  99034. * Uploads DDS Levels to a Babylon Texture
  99035. * @hidden
  99036. */
  99037. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99038. if (lodIndex === void 0) { lodIndex = -1; }
  99039. var sphericalPolynomialFaces = null;
  99040. if (info.sphericalPolynomial) {
  99041. sphericalPolynomialFaces = new Array();
  99042. }
  99043. var ext = engine.getCaps().s3tc;
  99044. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99045. var fourCC, width, height, dataLength = 0, dataOffset;
  99046. var byteArray, mipmapCount, mip;
  99047. var internalCompressedFormat = 0;
  99048. var blockBytes = 1;
  99049. if (header[off_magic] !== DDS_MAGIC) {
  99050. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99051. return;
  99052. }
  99053. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99054. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99055. return;
  99056. }
  99057. if (info.isCompressed && !ext) {
  99058. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99059. return;
  99060. }
  99061. var bpp = header[off_RGBbpp];
  99062. dataOffset = header[off_size] + 4;
  99063. var computeFormats = false;
  99064. if (info.isFourCC) {
  99065. fourCC = header[off_pfFourCC];
  99066. switch (fourCC) {
  99067. case FOURCC_DXT1:
  99068. blockBytes = 8;
  99069. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99070. break;
  99071. case FOURCC_DXT3:
  99072. blockBytes = 16;
  99073. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99074. break;
  99075. case FOURCC_DXT5:
  99076. blockBytes = 16;
  99077. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99078. break;
  99079. case FOURCC_D3DFMT_R16G16B16A16F:
  99080. computeFormats = true;
  99081. break;
  99082. case FOURCC_D3DFMT_R32G32B32A32F:
  99083. computeFormats = true;
  99084. break;
  99085. case FOURCC_DX10:
  99086. // There is an additionnal header so dataOffset need to be changed
  99087. dataOffset += 5 * 4; // 5 uints
  99088. var supported = false;
  99089. switch (info.dxgiFormat) {
  99090. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99091. computeFormats = true;
  99092. supported = true;
  99093. break;
  99094. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99095. info.isRGB = true;
  99096. info.isFourCC = false;
  99097. bpp = 32;
  99098. supported = true;
  99099. break;
  99100. }
  99101. if (supported) {
  99102. break;
  99103. }
  99104. default:
  99105. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99106. return;
  99107. }
  99108. }
  99109. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99110. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99111. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99112. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99113. if (computeFormats) {
  99114. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99115. }
  99116. mipmapCount = 1;
  99117. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99118. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99119. }
  99120. for (var face = 0; face < faces; face++) {
  99121. width = header[off_width];
  99122. height = header[off_height];
  99123. for (mip = 0; mip < mipmapCount; ++mip) {
  99124. if (lodIndex === -1 || lodIndex === mip) {
  99125. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99126. var i = (lodIndex === -1) ? mip : 0;
  99127. if (!info.isCompressed && info.isFourCC) {
  99128. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99129. dataLength = width * height * 4;
  99130. var floatArray = null;
  99131. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99132. if (bpp === 128) {
  99133. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99134. if (sphericalPolynomialFaces && i == 0) {
  99135. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99136. }
  99137. }
  99138. else if (bpp === 64) {
  99139. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99140. if (sphericalPolynomialFaces && i == 0) {
  99141. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99142. }
  99143. }
  99144. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99145. }
  99146. else {
  99147. if (bpp === 128) {
  99148. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99149. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99150. if (sphericalPolynomialFaces && i == 0) {
  99151. sphericalPolynomialFaces.push(floatArray);
  99152. }
  99153. }
  99154. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99155. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99156. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99157. if (sphericalPolynomialFaces && i == 0) {
  99158. sphericalPolynomialFaces.push(floatArray);
  99159. }
  99160. }
  99161. else { // 64
  99162. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99163. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99164. if (sphericalPolynomialFaces && i == 0) {
  99165. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99166. }
  99167. }
  99168. }
  99169. if (floatArray) {
  99170. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99171. }
  99172. }
  99173. else if (info.isRGB) {
  99174. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99175. if (bpp === 24) {
  99176. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99177. dataLength = width * height * 3;
  99178. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99179. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99180. }
  99181. else { // 32
  99182. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99183. dataLength = width * height * 4;
  99184. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99185. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99186. }
  99187. }
  99188. else if (info.isLuminance) {
  99189. var unpackAlignment = engine._getUnpackAlignement();
  99190. var unpaddedRowSize = width;
  99191. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99192. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99193. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99194. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99195. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99196. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99197. }
  99198. else {
  99199. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99200. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99201. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99202. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99203. }
  99204. }
  99205. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99206. width *= 0.5;
  99207. height *= 0.5;
  99208. width = Math.max(1.0, width);
  99209. height = Math.max(1.0, height);
  99210. }
  99211. if (currentFace !== undefined) {
  99212. // Loading a single face
  99213. break;
  99214. }
  99215. }
  99216. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99217. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99218. size: header[off_width],
  99219. right: sphericalPolynomialFaces[0],
  99220. left: sphericalPolynomialFaces[1],
  99221. up: sphericalPolynomialFaces[2],
  99222. down: sphericalPolynomialFaces[3],
  99223. front: sphericalPolynomialFaces[4],
  99224. back: sphericalPolynomialFaces[5],
  99225. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99226. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99227. gammaSpace: false,
  99228. });
  99229. }
  99230. else {
  99231. info.sphericalPolynomial = undefined;
  99232. }
  99233. };
  99234. /**
  99235. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99236. */
  99237. DDSTools.StoreLODInAlphaChannel = false;
  99238. return DDSTools;
  99239. }());
  99240. BABYLON.DDSTools = DDSTools;
  99241. })(BABYLON || (BABYLON = {}));
  99242. //# sourceMappingURL=babylon.dds.js.map
  99243. var BABYLON;
  99244. (function (BABYLON) {
  99245. /**
  99246. * Implementation of the DDS Texture Loader.
  99247. */
  99248. var DDSTextureLoader = /** @class */ (function () {
  99249. function DDSTextureLoader() {
  99250. /**
  99251. * Defines wether the loader supports cascade loading the different faces.
  99252. */
  99253. this.supportCascades = true;
  99254. }
  99255. /**
  99256. * This returns if the loader support the current file information.
  99257. * @param extension defines the file extension of the file being loaded
  99258. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99259. * @param fallback defines the fallback internal texture if any
  99260. * @param isBase64 defines whether the texture is encoded as a base64
  99261. * @param isBuffer defines whether the texture data are stored as a buffer
  99262. * @returns true if the loader can load the specified file
  99263. */
  99264. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99265. return extension.indexOf(".dds") === 0;
  99266. };
  99267. /**
  99268. * Transform the url before loading if required.
  99269. * @param rootUrl the url of the texture
  99270. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99271. * @returns the transformed texture
  99272. */
  99273. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99274. return rootUrl;
  99275. };
  99276. /**
  99277. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99278. * @param rootUrl the url of the texture
  99279. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99280. * @returns the fallback texture
  99281. */
  99282. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99283. return null;
  99284. };
  99285. /**
  99286. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99287. * @param data contains the texture data
  99288. * @param texture defines the BabylonJS internal texture
  99289. * @param createPolynomials will be true if polynomials have been requested
  99290. * @param onLoad defines the callback to trigger once the texture is ready
  99291. * @param onError defines the callback to trigger in case of error
  99292. */
  99293. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99294. var engine = texture.getEngine();
  99295. var info;
  99296. var loadMipmap = false;
  99297. if (Array.isArray(imgs)) {
  99298. for (var index = 0; index < imgs.length; index++) {
  99299. var data_1 = imgs[index];
  99300. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99301. texture.width = info.width;
  99302. texture.height = info.height;
  99303. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99304. engine._unpackFlipY(info.isCompressed);
  99305. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99306. if (!info.isFourCC && info.mipmapCount === 1) {
  99307. engine.generateMipMapsForCubemap(texture);
  99308. }
  99309. }
  99310. }
  99311. else {
  99312. var data = imgs;
  99313. info = BABYLON.DDSTools.GetDDSInfo(data);
  99314. texture.width = info.width;
  99315. texture.height = info.height;
  99316. if (createPolynomials) {
  99317. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99318. }
  99319. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99320. engine._unpackFlipY(info.isCompressed);
  99321. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99322. if (!info.isFourCC && info.mipmapCount === 1) {
  99323. engine.generateMipMapsForCubemap(texture);
  99324. }
  99325. }
  99326. engine._setCubeMapTextureParams(loadMipmap);
  99327. texture.isReady = true;
  99328. if (onLoad) {
  99329. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99330. }
  99331. };
  99332. /**
  99333. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99334. * @param data contains the texture data
  99335. * @param texture defines the BabylonJS internal texture
  99336. * @param callback defines the method to call once ready to upload
  99337. */
  99338. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99339. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99340. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99341. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99342. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99343. });
  99344. };
  99345. return DDSTextureLoader;
  99346. }());
  99347. // Register the loader.
  99348. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99349. })(BABYLON || (BABYLON = {}));
  99350. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  99351. var BABYLON;
  99352. (function (BABYLON) {
  99353. /**
  99354. * Based on jsTGALoader - Javascript loader for TGA file
  99355. * By Vincent Thibault
  99356. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99357. */
  99358. var TGATools = /** @class */ (function () {
  99359. function TGATools() {
  99360. }
  99361. /**
  99362. * Gets the header of a TGA file
  99363. * @param data defines the TGA data
  99364. * @returns the header
  99365. */
  99366. TGATools.GetTGAHeader = function (data) {
  99367. var offset = 0;
  99368. var header = {
  99369. id_length: data[offset++],
  99370. colormap_type: data[offset++],
  99371. image_type: data[offset++],
  99372. colormap_index: data[offset++] | data[offset++] << 8,
  99373. colormap_length: data[offset++] | data[offset++] << 8,
  99374. colormap_size: data[offset++],
  99375. origin: [
  99376. data[offset++] | data[offset++] << 8,
  99377. data[offset++] | data[offset++] << 8
  99378. ],
  99379. width: data[offset++] | data[offset++] << 8,
  99380. height: data[offset++] | data[offset++] << 8,
  99381. pixel_size: data[offset++],
  99382. flags: data[offset++]
  99383. };
  99384. return header;
  99385. };
  99386. /**
  99387. * Uploads TGA content to a Babylon Texture
  99388. * @hidden
  99389. */
  99390. TGATools.UploadContent = function (texture, data) {
  99391. // Not enough data to contain header ?
  99392. if (data.length < 19) {
  99393. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99394. return;
  99395. }
  99396. // Read Header
  99397. var offset = 18;
  99398. var header = TGATools.GetTGAHeader(data);
  99399. // Assume it's a valid Targa file.
  99400. if (header.id_length + offset > data.length) {
  99401. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  99402. return;
  99403. }
  99404. // Skip not needed data
  99405. offset += header.id_length;
  99406. var use_rle = false;
  99407. var use_pal = false;
  99408. var use_grey = false;
  99409. // Get some informations.
  99410. switch (header.image_type) {
  99411. case TGATools._TYPE_RLE_INDEXED:
  99412. use_rle = true;
  99413. case TGATools._TYPE_INDEXED:
  99414. use_pal = true;
  99415. break;
  99416. case TGATools._TYPE_RLE_RGB:
  99417. use_rle = true;
  99418. case TGATools._TYPE_RGB:
  99419. // use_rgb = true;
  99420. break;
  99421. case TGATools._TYPE_RLE_GREY:
  99422. use_rle = true;
  99423. case TGATools._TYPE_GREY:
  99424. use_grey = true;
  99425. break;
  99426. }
  99427. var pixel_data;
  99428. // var numAlphaBits = header.flags & 0xf;
  99429. var pixel_size = header.pixel_size >> 3;
  99430. var pixel_total = header.width * header.height * pixel_size;
  99431. // Read palettes
  99432. var palettes;
  99433. if (use_pal) {
  99434. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  99435. }
  99436. // Read LRE
  99437. if (use_rle) {
  99438. pixel_data = new Uint8Array(pixel_total);
  99439. var c, count, i;
  99440. var localOffset = 0;
  99441. var pixels = new Uint8Array(pixel_size);
  99442. while (offset < pixel_total && localOffset < pixel_total) {
  99443. c = data[offset++];
  99444. count = (c & 0x7f) + 1;
  99445. // RLE pixels
  99446. if (c & 0x80) {
  99447. // Bind pixel tmp array
  99448. for (i = 0; i < pixel_size; ++i) {
  99449. pixels[i] = data[offset++];
  99450. }
  99451. // Copy pixel array
  99452. for (i = 0; i < count; ++i) {
  99453. pixel_data.set(pixels, localOffset + i * pixel_size);
  99454. }
  99455. localOffset += pixel_size * count;
  99456. }
  99457. // Raw pixels
  99458. else {
  99459. count *= pixel_size;
  99460. for (i = 0; i < count; ++i) {
  99461. pixel_data[localOffset + i] = data[offset++];
  99462. }
  99463. localOffset += count;
  99464. }
  99465. }
  99466. }
  99467. // RAW Pixels
  99468. else {
  99469. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  99470. }
  99471. // Load to texture
  99472. var x_start, y_start, x_step, y_step, y_end, x_end;
  99473. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  99474. default:
  99475. case TGATools._ORIGIN_UL:
  99476. x_start = 0;
  99477. x_step = 1;
  99478. x_end = header.width;
  99479. y_start = 0;
  99480. y_step = 1;
  99481. y_end = header.height;
  99482. break;
  99483. case TGATools._ORIGIN_BL:
  99484. x_start = 0;
  99485. x_step = 1;
  99486. x_end = header.width;
  99487. y_start = header.height - 1;
  99488. y_step = -1;
  99489. y_end = -1;
  99490. break;
  99491. case TGATools._ORIGIN_UR:
  99492. x_start = header.width - 1;
  99493. x_step = -1;
  99494. x_end = -1;
  99495. y_start = 0;
  99496. y_step = 1;
  99497. y_end = header.height;
  99498. break;
  99499. case TGATools._ORIGIN_BR:
  99500. x_start = header.width - 1;
  99501. x_step = -1;
  99502. x_end = -1;
  99503. y_start = header.height - 1;
  99504. y_step = -1;
  99505. y_end = -1;
  99506. break;
  99507. }
  99508. // Load the specify method
  99509. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  99510. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  99511. var engine = texture.getEngine();
  99512. engine._uploadDataToTextureDirectly(texture, imageData);
  99513. };
  99514. /** @hidden */
  99515. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99516. var image = pixel_data, colormap = palettes;
  99517. var width = header.width, height = header.height;
  99518. var color, i = 0, x, y;
  99519. var imageData = new Uint8Array(width * height * 4);
  99520. for (y = y_start; y !== y_end; y += y_step) {
  99521. for (x = x_start; x !== x_end; x += x_step, i++) {
  99522. color = image[i];
  99523. imageData[(x + width * y) * 4 + 3] = 255;
  99524. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  99525. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  99526. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  99527. }
  99528. }
  99529. return imageData;
  99530. };
  99531. /** @hidden */
  99532. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99533. var image = pixel_data;
  99534. var width = header.width, height = header.height;
  99535. var color, i = 0, x, y;
  99536. var imageData = new Uint8Array(width * height * 4);
  99537. for (y = y_start; y !== y_end; y += y_step) {
  99538. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99539. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  99540. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  99541. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  99542. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  99543. imageData[(x + width * y) * 4 + 0] = r;
  99544. imageData[(x + width * y) * 4 + 1] = g;
  99545. imageData[(x + width * y) * 4 + 2] = b;
  99546. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  99547. }
  99548. }
  99549. return imageData;
  99550. };
  99551. /** @hidden */
  99552. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99553. var image = pixel_data;
  99554. var width = header.width, height = header.height;
  99555. var i = 0, x, y;
  99556. var imageData = new Uint8Array(width * height * 4);
  99557. for (y = y_start; y !== y_end; y += y_step) {
  99558. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  99559. imageData[(x + width * y) * 4 + 3] = 255;
  99560. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99561. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99562. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99563. }
  99564. }
  99565. return imageData;
  99566. };
  99567. /** @hidden */
  99568. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99569. var image = pixel_data;
  99570. var width = header.width, height = header.height;
  99571. var i = 0, x, y;
  99572. var imageData = new Uint8Array(width * height * 4);
  99573. for (y = y_start; y !== y_end; y += y_step) {
  99574. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  99575. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99576. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99577. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99578. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  99579. }
  99580. }
  99581. return imageData;
  99582. };
  99583. /** @hidden */
  99584. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99585. var image = pixel_data;
  99586. var width = header.width, height = header.height;
  99587. var color, i = 0, x, y;
  99588. var imageData = new Uint8Array(width * height * 4);
  99589. for (y = y_start; y !== y_end; y += y_step) {
  99590. for (x = x_start; x !== x_end; x += x_step, i++) {
  99591. color = image[i];
  99592. imageData[(x + width * y) * 4 + 0] = color;
  99593. imageData[(x + width * y) * 4 + 1] = color;
  99594. imageData[(x + width * y) * 4 + 2] = color;
  99595. imageData[(x + width * y) * 4 + 3] = 255;
  99596. }
  99597. }
  99598. return imageData;
  99599. };
  99600. /** @hidden */
  99601. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99602. var image = pixel_data;
  99603. var width = header.width, height = header.height;
  99604. var i = 0, x, y;
  99605. var imageData = new Uint8Array(width * height * 4);
  99606. for (y = y_start; y !== y_end; y += y_step) {
  99607. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99608. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  99609. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  99610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99611. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  99612. }
  99613. }
  99614. return imageData;
  99615. };
  99616. //private static _TYPE_NO_DATA = 0;
  99617. TGATools._TYPE_INDEXED = 1;
  99618. TGATools._TYPE_RGB = 2;
  99619. TGATools._TYPE_GREY = 3;
  99620. TGATools._TYPE_RLE_INDEXED = 9;
  99621. TGATools._TYPE_RLE_RGB = 10;
  99622. TGATools._TYPE_RLE_GREY = 11;
  99623. TGATools._ORIGIN_MASK = 0x30;
  99624. TGATools._ORIGIN_SHIFT = 0x04;
  99625. TGATools._ORIGIN_BL = 0x00;
  99626. TGATools._ORIGIN_BR = 0x01;
  99627. TGATools._ORIGIN_UL = 0x02;
  99628. TGATools._ORIGIN_UR = 0x03;
  99629. return TGATools;
  99630. }());
  99631. BABYLON.TGATools = TGATools;
  99632. })(BABYLON || (BABYLON = {}));
  99633. //# sourceMappingURL=babylon.tga.js.map
  99634. var BABYLON;
  99635. (function (BABYLON) {
  99636. /**
  99637. * Implementation of the TGA Texture Loader.
  99638. */
  99639. var TGATextureLoader = /** @class */ (function () {
  99640. function TGATextureLoader() {
  99641. /**
  99642. * Defines wether the loader supports cascade loading the different faces.
  99643. */
  99644. this.supportCascades = false;
  99645. }
  99646. /**
  99647. * This returns if the loader support the current file information.
  99648. * @param extension defines the file extension of the file being loaded
  99649. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99650. * @param fallback defines the fallback internal texture if any
  99651. * @param isBase64 defines whether the texture is encoded as a base64
  99652. * @param isBuffer defines whether the texture data are stored as a buffer
  99653. * @returns true if the loader can load the specified file
  99654. */
  99655. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99656. return extension.indexOf(".tga") === 0;
  99657. };
  99658. /**
  99659. * Transform the url before loading if required.
  99660. * @param rootUrl the url of the texture
  99661. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99662. * @returns the transformed texture
  99663. */
  99664. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99665. return rootUrl;
  99666. };
  99667. /**
  99668. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99669. * @param rootUrl the url of the texture
  99670. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99671. * @returns the fallback texture
  99672. */
  99673. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99674. return null;
  99675. };
  99676. /**
  99677. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99678. * @param data contains the texture data
  99679. * @param texture defines the BabylonJS internal texture
  99680. * @param createPolynomials will be true if polynomials have been requested
  99681. * @param onLoad defines the callback to trigger once the texture is ready
  99682. * @param onError defines the callback to trigger in case of error
  99683. */
  99684. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99685. throw ".env not supported in Cube.";
  99686. };
  99687. /**
  99688. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99689. * @param data contains the texture data
  99690. * @param texture defines the BabylonJS internal texture
  99691. * @param callback defines the method to call once ready to upload
  99692. */
  99693. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  99694. var uintData = new Uint8Array(data);
  99695. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  99696. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  99697. BABYLON.TGATools.UploadContent(texture, uintData);
  99698. });
  99699. };
  99700. return TGATextureLoader;
  99701. }());
  99702. // Register the loader.
  99703. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  99704. })(BABYLON || (BABYLON = {}));
  99705. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  99706. var BABYLON;
  99707. (function (BABYLON) {
  99708. /**
  99709. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  99710. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  99711. */
  99712. var KhronosTextureContainer = /** @class */ (function () {
  99713. /**
  99714. * Creates a new KhronosTextureContainer
  99715. * @param arrayBuffer contents of the KTX container file
  99716. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  99717. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  99718. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  99719. */
  99720. function KhronosTextureContainer(
  99721. /** contents of the KTX container file */
  99722. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  99723. this.arrayBuffer = arrayBuffer;
  99724. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  99725. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  99726. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  99727. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  99728. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  99729. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  99730. BABYLON.Tools.Error("texture missing KTX identifier");
  99731. return;
  99732. }
  99733. // load the reset of the header in native 32 bit int
  99734. var header = new Int32Array(this.arrayBuffer, 12, 13);
  99735. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  99736. var oppositeEndianess = header[0] === 0x01020304;
  99737. // read all the header elements in order they exist in the file, without modification (sans endainness)
  99738. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  99739. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  99740. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  99741. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  99742. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  99743. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  99744. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  99745. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  99746. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  99747. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  99748. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  99749. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  99750. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  99751. if (this.glType !== 0) {
  99752. BABYLON.Tools.Error("only compressed formats currently supported");
  99753. return;
  99754. }
  99755. else {
  99756. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  99757. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  99758. }
  99759. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  99760. BABYLON.Tools.Error("only 2D textures currently supported");
  99761. return;
  99762. }
  99763. if (this.numberOfArrayElements !== 0) {
  99764. BABYLON.Tools.Error("texture arrays not currently supported");
  99765. return;
  99766. }
  99767. if (this.numberOfFaces !== facesExpected) {
  99768. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  99769. return;
  99770. }
  99771. // we now have a completely validated file, so could use existence of loadType as success
  99772. // would need to make this more elaborate & adjust checks above to support more than one load type
  99773. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  99774. }
  99775. //
  99776. /**
  99777. * Revert the endianness of a value.
  99778. * Not as fast hardware based, but will probably never need to use
  99779. * @param val defines the value to convert
  99780. * @returns the new value
  99781. */
  99782. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  99783. return ((val & 0xFF) << 24)
  99784. | ((val & 0xFF00) << 8)
  99785. | ((val >> 8) & 0xFF00)
  99786. | ((val >> 24) & 0xFF);
  99787. };
  99788. /**
  99789. * Uploads KTX content to a Babylon Texture.
  99790. * It is assumed that the texture has already been created & is currently bound
  99791. * @hidden
  99792. */
  99793. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  99794. switch (this.loadType) {
  99795. case KhronosTextureContainer.COMPRESSED_2D:
  99796. this._upload2DCompressedLevels(texture, loadMipmaps);
  99797. break;
  99798. case KhronosTextureContainer.TEX_2D:
  99799. case KhronosTextureContainer.COMPRESSED_3D:
  99800. case KhronosTextureContainer.TEX_3D:
  99801. }
  99802. };
  99803. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  99804. // initialize width & height for level 1
  99805. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  99806. var width = this.pixelWidth;
  99807. var height = this.pixelHeight;
  99808. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  99809. for (var level = 0; level < mipmapCount; level++) {
  99810. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  99811. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  99812. for (var face = 0; face < this.numberOfFaces; face++) {
  99813. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  99814. var engine = texture.getEngine();
  99815. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  99816. dataOffset += imageSize; // add size of the image for the next face/mipmap
  99817. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  99818. }
  99819. width = Math.max(1.0, width * 0.5);
  99820. height = Math.max(1.0, height * 0.5);
  99821. }
  99822. };
  99823. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  99824. // load types
  99825. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  99826. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  99827. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  99828. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  99829. return KhronosTextureContainer;
  99830. }());
  99831. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  99832. })(BABYLON || (BABYLON = {}));
  99833. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  99834. var BABYLON;
  99835. (function (BABYLON) {
  99836. /**
  99837. * Implementation of the KTX Texture Loader.
  99838. */
  99839. var KTXTextureLoader = /** @class */ (function () {
  99840. function KTXTextureLoader() {
  99841. /**
  99842. * Defines wether the loader supports cascade loading the different faces.
  99843. */
  99844. this.supportCascades = false;
  99845. }
  99846. /**
  99847. * This returns if the loader support the current file information.
  99848. * @param extension defines the file extension of the file being loaded
  99849. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99850. * @param fallback defines the fallback internal texture if any
  99851. * @param isBase64 defines whether the texture is encoded as a base64
  99852. * @param isBuffer defines whether the texture data are stored as a buffer
  99853. * @returns true if the loader can load the specified file
  99854. */
  99855. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99856. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  99857. return true;
  99858. }
  99859. return false;
  99860. };
  99861. /**
  99862. * Transform the url before loading if required.
  99863. * @param rootUrl the url of the texture
  99864. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99865. * @returns the transformed texture
  99866. */
  99867. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99868. var lastDot = rootUrl.lastIndexOf('.');
  99869. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  99870. };
  99871. /**
  99872. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99873. * @param rootUrl the url of the texture
  99874. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99875. * @returns the fallback texture
  99876. */
  99877. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99878. // remove the format appended to the rootUrl in the original createCubeTexture call.
  99879. var exp = new RegExp("" + textureFormatInUse + "$");
  99880. return rootUrl.replace(exp, "");
  99881. };
  99882. /**
  99883. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99884. * @param data contains the texture data
  99885. * @param texture defines the BabylonJS internal texture
  99886. * @param createPolynomials will be true if polynomials have been requested
  99887. * @param onLoad defines the callback to trigger once the texture is ready
  99888. * @param onError defines the callback to trigger in case of error
  99889. */
  99890. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99891. if (Array.isArray(data)) {
  99892. return;
  99893. }
  99894. var engine = texture.getEngine();
  99895. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  99896. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  99897. engine._unpackFlipY(true);
  99898. ktx.uploadLevels(texture, texture.generateMipMaps);
  99899. texture.width = ktx.pixelWidth;
  99900. texture.height = ktx.pixelHeight;
  99901. engine._setCubeMapTextureParams(loadMipmap);
  99902. texture.isReady = true;
  99903. };
  99904. /**
  99905. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99906. * @param data contains the texture data
  99907. * @param texture defines the BabylonJS internal texture
  99908. * @param callback defines the method to call once ready to upload
  99909. */
  99910. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  99911. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  99912. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  99913. ktx.uploadLevels(texture, texture.generateMipMaps);
  99914. });
  99915. };
  99916. return KTXTextureLoader;
  99917. }());
  99918. // Register the loader.
  99919. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  99920. })(BABYLON || (BABYLON = {}));
  99921. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  99922. var BABYLON;
  99923. (function (BABYLON) {
  99924. /**
  99925. * Sets of helpers addressing the serialization and deserialization of environment texture
  99926. * stored in a BabylonJS env file.
  99927. * Those files are usually stored as .env files.
  99928. */
  99929. var EnvironmentTextureTools = /** @class */ (function () {
  99930. function EnvironmentTextureTools() {
  99931. }
  99932. /**
  99933. * Gets the environment info from an env file.
  99934. * @param data The array buffer containing the .env bytes.
  99935. * @returns the environment file info (the json header) if successfully parsed.
  99936. */
  99937. EnvironmentTextureTools.GetEnvInfo = function (data) {
  99938. var dataView = new DataView(data);
  99939. var pos = 0;
  99940. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  99941. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  99942. BABYLON.Tools.Error('Not a babylon environment map');
  99943. return null;
  99944. }
  99945. }
  99946. // Read json manifest - collect characters up to null terminator
  99947. var manifestString = '';
  99948. var charCode = 0x00;
  99949. while ((charCode = dataView.getUint8(pos++))) {
  99950. manifestString += String.fromCharCode(charCode);
  99951. }
  99952. var manifest = JSON.parse(manifestString);
  99953. if (manifest.specular) {
  99954. // Extend the header with the position of the payload.
  99955. manifest.specular.specularDataPosition = pos;
  99956. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  99957. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  99958. }
  99959. return manifest;
  99960. };
  99961. /**
  99962. * Creates an environment texture from a loaded cube texture.
  99963. * @param texture defines the cube texture to convert in env file
  99964. * @return a promise containing the environment data if succesfull.
  99965. */
  99966. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  99967. var _this = this;
  99968. var internalTexture = texture.getInternalTexture();
  99969. if (!internalTexture) {
  99970. return Promise.reject("The cube texture is invalid.");
  99971. }
  99972. if (!texture._prefiltered) {
  99973. return Promise.reject("The cube texture is invalid (not prefiltered).");
  99974. }
  99975. var engine = internalTexture.getEngine();
  99976. if (engine && engine.premultipliedAlpha) {
  99977. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  99978. }
  99979. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  99980. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  99981. }
  99982. var canvas = engine.getRenderingCanvas();
  99983. if (!canvas) {
  99984. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  99985. }
  99986. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99987. if (!engine.getCaps().textureFloatRender) {
  99988. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99989. if (!engine.getCaps().textureHalfFloatRender) {
  99990. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  99991. }
  99992. }
  99993. var cubeWidth = internalTexture.width;
  99994. var hostingScene = new BABYLON.Scene(engine);
  99995. var specularTextures = {};
  99996. var promises = [];
  99997. // Read and collect all mipmaps data from the cube.
  99998. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  99999. mipmapsCount = Math.round(mipmapsCount);
  100000. var _loop_1 = function (i) {
  100001. var faceWidth = Math.pow(2, mipmapsCount - i);
  100002. var _loop_2 = function (face) {
  100003. var data = texture.readPixels(face, i);
  100004. // Creates a temp texture with the face data.
  100005. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100006. // And rgbdEncode them.
  100007. var promise = new Promise(function (resolve, reject) {
  100008. 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);
  100009. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100010. rgbdPostProcess.onApply = function (effect) {
  100011. effect._bindTexture("textureSampler", tempTexture);
  100012. };
  100013. // As the process needs to happen on the main canvas, keep track of the current size
  100014. var currentW = engine.getRenderWidth();
  100015. var currentH = engine.getRenderHeight();
  100016. // Set the desired size for the texture
  100017. engine.setSize(faceWidth, faceWidth);
  100018. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100019. // Reading datas from WebGL
  100020. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100021. var fileReader = new FileReader();
  100022. fileReader.onload = function (event) {
  100023. var arrayBuffer = event.target.result;
  100024. specularTextures[i * 6 + face] = arrayBuffer;
  100025. resolve();
  100026. };
  100027. fileReader.readAsArrayBuffer(blob);
  100028. });
  100029. // Reapply the previous canvas size
  100030. engine.setSize(currentW, currentH);
  100031. });
  100032. });
  100033. promises.push(promise);
  100034. };
  100035. // All faces of the cube.
  100036. for (var face = 0; face < 6; face++) {
  100037. _loop_2(face);
  100038. }
  100039. };
  100040. for (var i = 0; i <= mipmapsCount; i++) {
  100041. _loop_1(i);
  100042. }
  100043. // Once all the textures haves been collected as RGBD stored in PNGs
  100044. return Promise.all(promises).then(function () {
  100045. // We can delete the hosting scene keeping track of all the creation objects
  100046. hostingScene.dispose();
  100047. // Creates the json header for the env texture
  100048. var info = {
  100049. version: 1,
  100050. width: cubeWidth,
  100051. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100052. specular: {
  100053. mipmaps: [],
  100054. lodGenerationScale: texture.lodGenerationScale
  100055. }
  100056. };
  100057. // Sets the specular image data information
  100058. var position = 0;
  100059. for (var i = 0; i <= mipmapsCount; i++) {
  100060. for (var face = 0; face < 6; face++) {
  100061. var byteLength = specularTextures[i * 6 + face].byteLength;
  100062. info.specular.mipmaps.push({
  100063. length: byteLength,
  100064. position: position
  100065. });
  100066. position += byteLength;
  100067. }
  100068. }
  100069. // Encode the JSON as an array buffer
  100070. var infoString = JSON.stringify(info);
  100071. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100072. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100073. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100074. infoView[i] = infoString.charCodeAt(i);
  100075. }
  100076. // Ends up with a null terminator for easier parsing
  100077. infoView[infoString.length] = 0x00;
  100078. // Computes the final required size and creates the storage
  100079. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100080. var finalBuffer = new ArrayBuffer(totalSize);
  100081. var finalBufferView = new Uint8Array(finalBuffer);
  100082. var dataView = new DataView(finalBuffer);
  100083. // Copy the magic bytes identifying the file in
  100084. var pos = 0;
  100085. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100086. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100087. }
  100088. // Add the json info
  100089. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100090. pos += infoBuffer.byteLength;
  100091. // Finally inserts the texture data
  100092. for (var i = 0; i <= mipmapsCount; i++) {
  100093. for (var face = 0; face < 6; face++) {
  100094. var dataBuffer = specularTextures[i * 6 + face];
  100095. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100096. pos += dataBuffer.byteLength;
  100097. }
  100098. }
  100099. // Voila
  100100. return finalBuffer;
  100101. });
  100102. };
  100103. /**
  100104. * Creates a JSON representation of the spherical data.
  100105. * @param texture defines the texture containing the polynomials
  100106. * @return the JSON representation of the spherical info
  100107. */
  100108. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100109. var polynmials = texture.sphericalPolynomial;
  100110. if (polynmials == null) {
  100111. return null;
  100112. }
  100113. return {
  100114. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100115. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100116. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100117. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100118. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100119. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100120. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100121. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100122. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100123. };
  100124. };
  100125. /**
  100126. * Uploads the texture info contained in the env file to the GPU.
  100127. * @param texture defines the internal texture to upload to
  100128. * @param arrayBuffer defines the buffer cotaining the data to load
  100129. * @param info defines the texture info retrieved through the GetEnvInfo method
  100130. * @returns a promise
  100131. */
  100132. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100133. if (info.version !== 1) {
  100134. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100135. }
  100136. var specularInfo = info.specular;
  100137. if (!specularInfo) {
  100138. // Nothing else parsed so far
  100139. return Promise.resolve();
  100140. }
  100141. // Double checks the enclosed info
  100142. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100143. mipmapsCount = Math.round(mipmapsCount) + 1;
  100144. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100145. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100146. }
  100147. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100148. var imageData = new Array(mipmapsCount);
  100149. for (var i = 0; i < mipmapsCount; i++) {
  100150. imageData[i] = new Array(6);
  100151. for (var face = 0; face < 6; face++) {
  100152. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100153. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100154. }
  100155. }
  100156. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100157. };
  100158. /**
  100159. * Uploads the levels of image data to the GPU.
  100160. * @param texture defines the internal texture to upload to
  100161. * @param imageData defines the array buffer views of image data [mipmap][face]
  100162. * @returns a promise
  100163. */
  100164. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100165. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100166. throw new Error("Texture size must be a power of two");
  100167. }
  100168. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100169. // Gets everything ready.
  100170. var engine = texture.getEngine();
  100171. var expandTexture = false;
  100172. var generateNonLODTextures = false;
  100173. var rgbdPostProcess = null;
  100174. var cubeRtt = null;
  100175. var lodTextures = null;
  100176. var caps = engine.getCaps();
  100177. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100178. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100179. texture.generateMipMaps = true;
  100180. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100181. // Add extra process if texture lod is not supported
  100182. if (!caps.textureLOD) {
  100183. expandTexture = false;
  100184. generateNonLODTextures = true;
  100185. lodTextures = {};
  100186. }
  100187. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100188. else if (engine.webGLVersion < 2) {
  100189. expandTexture = false;
  100190. }
  100191. // If half float available we can uncompress the texture
  100192. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100193. expandTexture = true;
  100194. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100195. }
  100196. // If full float available we can uncompress the texture
  100197. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100198. expandTexture = true;
  100199. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100200. }
  100201. // Expand the texture if possible
  100202. if (expandTexture) {
  100203. // Simply run through the decode PP
  100204. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100205. texture._isRGBD = false;
  100206. texture.invertY = false;
  100207. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100208. generateDepthBuffer: false,
  100209. generateMipMaps: true,
  100210. generateStencilBuffer: false,
  100211. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100212. type: texture.type,
  100213. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100214. });
  100215. }
  100216. else {
  100217. texture._isRGBD = true;
  100218. texture.invertY = true;
  100219. // In case of missing support, applies the same patch than DDS files.
  100220. if (generateNonLODTextures) {
  100221. var mipSlices = 3;
  100222. var scale = texture._lodGenerationScale;
  100223. var offset = texture._lodGenerationOffset;
  100224. for (var i = 0; i < mipSlices; i++) {
  100225. //compute LOD from even spacing in smoothness (matching shader calculation)
  100226. var smoothness = i / (mipSlices - 1);
  100227. var roughness = 1 - smoothness;
  100228. var minLODIndex = offset; // roughness = 0
  100229. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100230. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100231. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100232. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100233. glTextureFromLod.isCube = true;
  100234. glTextureFromLod.invertY = true;
  100235. glTextureFromLod.generateMipMaps = false;
  100236. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100237. // Wrap in a base texture for easy binding.
  100238. var lodTexture = new BABYLON.BaseTexture(null);
  100239. lodTexture.isCube = true;
  100240. lodTexture._texture = glTextureFromLod;
  100241. lodTextures[mipmapIndex] = lodTexture;
  100242. switch (i) {
  100243. case 0:
  100244. texture._lodTextureLow = lodTexture;
  100245. break;
  100246. case 1:
  100247. texture._lodTextureMid = lodTexture;
  100248. break;
  100249. case 2:
  100250. texture._lodTextureHigh = lodTexture;
  100251. break;
  100252. }
  100253. }
  100254. }
  100255. }
  100256. var promises = [];
  100257. var _loop_3 = function (i) {
  100258. var _loop_4 = function (face) {
  100259. // Constructs an image element from image data
  100260. var bytes = imageData[i][face];
  100261. var blob = new Blob([bytes], { type: 'image/png' });
  100262. var url = URL.createObjectURL(blob);
  100263. var image = new Image();
  100264. image.src = url;
  100265. // Enqueue promise to upload to the texture.
  100266. var promise = new Promise(function (resolve, reject) {
  100267. image.onload = function () {
  100268. if (expandTexture) {
  100269. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100270. reject(message);
  100271. }, image);
  100272. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100273. // Uncompress the data to a RTT
  100274. rgbdPostProcess.onApply = function (effect) {
  100275. effect._bindTexture("textureSampler", tempTexture_1);
  100276. effect.setFloat2("scale", 1, 1);
  100277. };
  100278. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100279. // Cleanup
  100280. engine.restoreDefaultFramebuffer();
  100281. tempTexture_1.dispose();
  100282. window.URL.revokeObjectURL(url);
  100283. resolve();
  100284. });
  100285. }
  100286. else {
  100287. engine._uploadImageToTexture(texture, image, face, i);
  100288. // Upload the face to the non lod texture support
  100289. if (generateNonLODTextures) {
  100290. var lodTexture = lodTextures[i];
  100291. if (lodTexture) {
  100292. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100293. }
  100294. }
  100295. resolve();
  100296. }
  100297. };
  100298. image.onerror = function (error) {
  100299. reject(error);
  100300. };
  100301. });
  100302. promises.push(promise);
  100303. };
  100304. // All faces
  100305. for (var face = 0; face < 6; face++) {
  100306. _loop_4(face);
  100307. }
  100308. };
  100309. // All mipmaps up to provided number of images
  100310. for (var i = 0; i < imageData.length; i++) {
  100311. _loop_3(i);
  100312. }
  100313. // Fill remaining mipmaps with black textures.
  100314. if (imageData.length < mipmapsCount) {
  100315. var data = void 0;
  100316. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100317. var dataLength = size * size * 4;
  100318. switch (texture.type) {
  100319. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100320. data = new Uint8Array(dataLength);
  100321. break;
  100322. }
  100323. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100324. data = new Uint16Array(dataLength);
  100325. break;
  100326. }
  100327. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100328. data = new Float32Array(dataLength);
  100329. break;
  100330. }
  100331. }
  100332. for (var i = imageData.length; i < mipmapsCount; i++) {
  100333. for (var face = 0; face < 6; face++) {
  100334. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100335. }
  100336. }
  100337. }
  100338. // Once all done, finishes the cleanup and return
  100339. return Promise.all(promises).then(function () {
  100340. // Release temp RTT.
  100341. if (cubeRtt) {
  100342. engine._releaseFramebufferObjects(cubeRtt);
  100343. cubeRtt._swapAndDie(texture);
  100344. }
  100345. // Release temp Post Process.
  100346. if (rgbdPostProcess) {
  100347. rgbdPostProcess.dispose();
  100348. }
  100349. // Flag internal texture as ready in case they are in use.
  100350. if (generateNonLODTextures) {
  100351. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100352. texture._lodTextureHigh._texture.isReady = true;
  100353. }
  100354. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100355. texture._lodTextureMid._texture.isReady = true;
  100356. }
  100357. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100358. texture._lodTextureLow._texture.isReady = true;
  100359. }
  100360. }
  100361. });
  100362. };
  100363. /**
  100364. * Uploads spherical polynomials information to the texture.
  100365. * @param texture defines the texture we are trying to upload the information to
  100366. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100367. */
  100368. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100369. if (info.version !== 1) {
  100370. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100371. }
  100372. var irradianceInfo = info.irradiance;
  100373. if (!irradianceInfo) {
  100374. return;
  100375. }
  100376. var sp = new BABYLON.SphericalPolynomial();
  100377. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100378. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100379. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100380. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100381. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100382. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100383. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100384. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100385. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100386. texture._sphericalPolynomial = sp;
  100387. };
  100388. /**
  100389. * Magic number identifying the env file.
  100390. */
  100391. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100392. return EnvironmentTextureTools;
  100393. }());
  100394. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  100395. })(BABYLON || (BABYLON = {}));
  100396. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  100397. var BABYLON;
  100398. (function (BABYLON) {
  100399. /**
  100400. * Implementation of the ENV Texture Loader.
  100401. */
  100402. var ENVTextureLoader = /** @class */ (function () {
  100403. function ENVTextureLoader() {
  100404. /**
  100405. * Defines wether the loader supports cascade loading the different faces.
  100406. */
  100407. this.supportCascades = false;
  100408. }
  100409. /**
  100410. * This returns if the loader support the current file information.
  100411. * @param extension defines the file extension of the file being loaded
  100412. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100413. * @param fallback defines the fallback internal texture if any
  100414. * @param isBase64 defines whether the texture is encoded as a base64
  100415. * @param isBuffer defines whether the texture data are stored as a buffer
  100416. * @returns true if the loader can load the specified file
  100417. */
  100418. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100419. return extension.indexOf(".env") === 0;
  100420. };
  100421. /**
  100422. * Transform the url before loading if required.
  100423. * @param rootUrl the url of the texture
  100424. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100425. * @returns the transformed texture
  100426. */
  100427. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100428. return rootUrl;
  100429. };
  100430. /**
  100431. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100432. * @param rootUrl the url of the texture
  100433. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100434. * @returns the fallback texture
  100435. */
  100436. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100437. return null;
  100438. };
  100439. /**
  100440. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100441. * @param data contains the texture data
  100442. * @param texture defines the BabylonJS internal texture
  100443. * @param createPolynomials will be true if polynomials have been requested
  100444. * @param onLoad defines the callback to trigger once the texture is ready
  100445. * @param onError defines the callback to trigger in case of error
  100446. */
  100447. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100448. if (Array.isArray(data)) {
  100449. return;
  100450. }
  100451. data = data;
  100452. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  100453. if (info) {
  100454. texture.width = info.width;
  100455. texture.height = info.width;
  100456. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  100457. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  100458. texture.isReady = true;
  100459. if (onLoad) {
  100460. onLoad();
  100461. }
  100462. });
  100463. }
  100464. else if (onError) {
  100465. onError("Can not parse the environment file", null);
  100466. }
  100467. };
  100468. /**
  100469. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100470. * @param data contains the texture data
  100471. * @param texture defines the BabylonJS internal texture
  100472. * @param callback defines the method to call once ready to upload
  100473. */
  100474. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  100475. throw ".env not supported in 2d.";
  100476. };
  100477. return ENVTextureLoader;
  100478. }());
  100479. // Register the loader.
  100480. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  100481. })(BABYLON || (BABYLON = {}));
  100482. //# sourceMappingURL=babylon.envTextureLoader.js.map
  100483. var BABYLON;
  100484. (function (BABYLON) {
  100485. /**
  100486. * Renders a layer on top of an existing scene
  100487. */
  100488. var UtilityLayerRenderer = /** @class */ (function () {
  100489. /**
  100490. * Instantiates a UtilityLayerRenderer
  100491. * @param originalScene the original scene that will be rendered on top of
  100492. */
  100493. function UtilityLayerRenderer(
  100494. /** the original scene that will be rendered on top of */
  100495. originalScene) {
  100496. var _this = this;
  100497. this.originalScene = originalScene;
  100498. this._pointerCaptures = {};
  100499. this._lastPointerEvents = {};
  100500. /**
  100501. * If the utility layer should automatically be rendered on top of existing scene
  100502. */
  100503. this.shouldRender = true;
  100504. /**
  100505. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  100506. */
  100507. this.onlyCheckPointerDownEvents = true;
  100508. /**
  100509. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  100510. */
  100511. this.processAllEvents = false;
  100512. /**
  100513. * Observable raised when the pointer move from the utility layer scene to the main scene
  100514. */
  100515. this.onPointerOutObservable = new BABYLON.Observable();
  100516. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  100517. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  100518. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  100519. this.utilityLayerScene._allowPostProcessClearColor = false;
  100520. originalScene.getEngine().scenes.pop();
  100521. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  100522. this.utilityLayerScene.detachControl();
  100523. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  100524. if (!_this.processAllEvents) {
  100525. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  100526. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  100527. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  100528. return;
  100529. }
  100530. }
  100531. var pointerEvent = (prePointerInfo.event);
  100532. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  100533. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100534. return;
  100535. }
  100536. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  100537. if (!prePointerInfo.ray && utilityScenePick) {
  100538. prePointerInfo.ray = utilityScenePick.ray;
  100539. }
  100540. // always fire the prepointer oversvable
  100541. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  100542. // allow every non pointer down event to flow to the utility layer
  100543. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  100544. if (!prePointerInfo.skipOnPointerObservable) {
  100545. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100546. }
  100547. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  100548. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100549. }
  100550. return;
  100551. }
  100552. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  100553. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  100554. if (utilityScenePick && utilityScenePick.hit) {
  100555. if (!prePointerInfo.skipOnPointerObservable) {
  100556. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100557. }
  100558. prePointerInfo.skipOnPointerObservable = true;
  100559. }
  100560. }
  100561. else {
  100562. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  100563. var pointerEvent_1 = (prePointerInfo.event);
  100564. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  100565. if (originalScenePick && utilityScenePick) {
  100566. // No pick in utility scene
  100567. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  100568. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100569. // We touched an utility mesh present in the main scene
  100570. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100571. prePointerInfo.skipOnPointerObservable = true;
  100572. }
  100573. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100574. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  100575. }
  100576. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100577. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100578. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100579. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100580. }
  100581. }
  100582. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  100583. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  100584. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  100585. // If a previous utility layer set this, do not unset this
  100586. if (!prePointerInfo.skipOnPointerObservable) {
  100587. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  100588. }
  100589. }
  100590. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  100591. // We have a pick in both scenes but main is closer than utility
  100592. // We touched an utility mesh present in the main scene
  100593. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100594. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100595. prePointerInfo.skipOnPointerObservable = true;
  100596. }
  100597. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100598. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100599. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100600. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100601. }
  100602. }
  100603. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  100604. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  100605. }
  100606. }
  100607. }
  100608. });
  100609. // Render directly on top of existing scene without clearing
  100610. this.utilityLayerScene.autoClear = false;
  100611. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  100612. if (_this.shouldRender) {
  100613. _this.render();
  100614. }
  100615. });
  100616. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  100617. _this.dispose();
  100618. });
  100619. this._updateCamera();
  100620. }
  100621. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  100622. /**
  100623. * 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)
  100624. */
  100625. get: function () {
  100626. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  100627. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100628. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100629. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100630. });
  100631. }
  100632. return UtilityLayerRenderer._DefaultUtilityLayer;
  100633. },
  100634. enumerable: true,
  100635. configurable: true
  100636. });
  100637. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  100638. /**
  100639. * 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)
  100640. */
  100641. get: function () {
  100642. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  100643. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100644. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  100645. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100646. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100647. });
  100648. }
  100649. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  100650. },
  100651. enumerable: true,
  100652. configurable: true
  100653. });
  100654. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  100655. if (!prePointerInfo.skipOnPointerObservable) {
  100656. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  100657. this._lastPointerEvents[pointerEvent.pointerId] = true;
  100658. }
  100659. };
  100660. /**
  100661. * Renders the utility layers scene on top of the original scene
  100662. */
  100663. UtilityLayerRenderer.prototype.render = function () {
  100664. this._updateCamera();
  100665. if (this.utilityLayerScene.activeCamera) {
  100666. // Set the camera's scene to utility layers scene
  100667. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  100668. var camera = this.utilityLayerScene.activeCamera;
  100669. camera._scene = this.utilityLayerScene;
  100670. if (camera.leftCamera) {
  100671. camera.leftCamera._scene = this.utilityLayerScene;
  100672. }
  100673. if (camera.rightCamera) {
  100674. camera.rightCamera._scene = this.utilityLayerScene;
  100675. }
  100676. this.utilityLayerScene.render(false);
  100677. // Reset camera's scene back to original
  100678. camera._scene = oldScene;
  100679. if (camera.leftCamera) {
  100680. camera.leftCamera._scene = oldScene;
  100681. }
  100682. if (camera.rightCamera) {
  100683. camera.rightCamera._scene = oldScene;
  100684. }
  100685. }
  100686. };
  100687. /**
  100688. * Disposes of the renderer
  100689. */
  100690. UtilityLayerRenderer.prototype.dispose = function () {
  100691. this.onPointerOutObservable.clear();
  100692. if (this._afterRenderObserver) {
  100693. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  100694. }
  100695. if (this._sceneDisposeObserver) {
  100696. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100697. }
  100698. if (this._originalPointerObserver) {
  100699. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  100700. }
  100701. this.utilityLayerScene.dispose();
  100702. };
  100703. UtilityLayerRenderer.prototype._updateCamera = function () {
  100704. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  100705. };
  100706. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100707. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100708. return UtilityLayerRenderer;
  100709. }());
  100710. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  100711. })(BABYLON || (BABYLON = {}));
  100712. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  100713. //# sourceMappingURL=babylon.behavior.js.map
  100714. var BABYLON;
  100715. (function (BABYLON) {
  100716. /**
  100717. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  100718. */
  100719. var PointerDragBehavior = /** @class */ (function () {
  100720. /**
  100721. * Creates a pointer drag behavior that can be attached to a mesh
  100722. * @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)
  100723. */
  100724. function PointerDragBehavior(options) {
  100725. /**
  100726. * 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)
  100727. */
  100728. this.maxDragAngle = 0;
  100729. /**
  100730. * @hidden
  100731. */
  100732. this._useAlternatePickedPointAboveMaxDragAngle = false;
  100733. /**
  100734. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100735. */
  100736. this.currentDraggingPointerID = -1;
  100737. /**
  100738. * If the behavior is currently in a dragging state
  100739. */
  100740. this.dragging = false;
  100741. /**
  100742. * 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)
  100743. */
  100744. this.dragDeltaRatio = 0.2;
  100745. /**
  100746. * If the drag plane orientation should be updated during the dragging (Default: true)
  100747. */
  100748. this.updateDragPlane = true;
  100749. // Debug mode will display drag planes to help visualize behavior
  100750. this._debugMode = false;
  100751. this._moving = false;
  100752. /**
  100753. * Fires each time the attached mesh is dragged with the pointer
  100754. * * delta between last drag position and current drag position in world space
  100755. * * dragDistance along the drag axis
  100756. * * dragPlaneNormal normal of the current drag plane used during the drag
  100757. * * dragPlanePoint in world space where the drag intersects the drag plane
  100758. */
  100759. this.onDragObservable = new BABYLON.Observable();
  100760. /**
  100761. * Fires each time a drag begins (eg. mouse down on mesh)
  100762. */
  100763. this.onDragStartObservable = new BABYLON.Observable();
  100764. /**
  100765. * Fires each time a drag ends (eg. mouse release after drag)
  100766. */
  100767. this.onDragEndObservable = new BABYLON.Observable();
  100768. /**
  100769. * If the attached mesh should be moved when dragged
  100770. */
  100771. this.moveAttached = true;
  100772. /**
  100773. * If the drag behavior will react to drag events (Default: true)
  100774. */
  100775. this.enabled = true;
  100776. /**
  100777. * If camera controls should be detached during the drag
  100778. */
  100779. this.detachCameraControls = true;
  100780. /**
  100781. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  100782. */
  100783. this.useObjectOrienationForDragging = true;
  100784. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  100785. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  100786. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  100787. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100788. this._attachedElement = null;
  100789. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100790. this._lastPointerRay = {};
  100791. this._dragDelta = new BABYLON.Vector3();
  100792. // Variables to avoid instantiation in the below method
  100793. this._pointA = new BABYLON.Vector3(0, 0, 0);
  100794. this._pointB = new BABYLON.Vector3(0, 0, 0);
  100795. this._pointC = new BABYLON.Vector3(0, 0, 0);
  100796. this._lineA = new BABYLON.Vector3(0, 0, 0);
  100797. this._lineB = new BABYLON.Vector3(0, 0, 0);
  100798. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  100799. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  100800. this._options = options ? options : {};
  100801. var optionCount = 0;
  100802. if (this._options.dragAxis) {
  100803. optionCount++;
  100804. }
  100805. if (this._options.dragPlaneNormal) {
  100806. optionCount++;
  100807. }
  100808. if (optionCount > 1) {
  100809. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  100810. }
  100811. }
  100812. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  100813. /**
  100814. * The name of the behavior
  100815. */
  100816. get: function () {
  100817. return "PointerDrag";
  100818. },
  100819. enumerable: true,
  100820. configurable: true
  100821. });
  100822. /**
  100823. * Initializes the behavior
  100824. */
  100825. PointerDragBehavior.prototype.init = function () { };
  100826. /**
  100827. * Attaches the drag behavior the passed in mesh
  100828. * @param ownerNode The mesh that will be dragged around once attached
  100829. */
  100830. PointerDragBehavior.prototype.attach = function (ownerNode) {
  100831. var _this = this;
  100832. this._scene = ownerNode.getScene();
  100833. this._attachedNode = ownerNode;
  100834. // Initialize drag plane to not interfere with existing scene
  100835. if (!PointerDragBehavior._planeScene) {
  100836. if (this._debugMode) {
  100837. PointerDragBehavior._planeScene = this._scene;
  100838. }
  100839. else {
  100840. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  100841. PointerDragBehavior._planeScene.detachControl();
  100842. this._scene.getEngine().scenes.pop();
  100843. this._scene.onDisposeObservable.addOnce(function () {
  100844. PointerDragBehavior._planeScene.dispose();
  100845. PointerDragBehavior._planeScene = null;
  100846. });
  100847. }
  100848. }
  100849. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  100850. // State of the drag
  100851. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  100852. var pickPredicate = function (m) {
  100853. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  100854. };
  100855. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100856. if (!_this.enabled) {
  100857. return;
  100858. }
  100859. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100860. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100861. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  100862. }
  100863. }
  100864. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100865. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100866. _this.releaseDrag();
  100867. }
  100868. }
  100869. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100870. var pointerId = pointerInfo.event.pointerId;
  100871. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  100872. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  100873. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  100874. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  100875. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  100876. }
  100877. _this.currentDraggingPointerID = pointerId;
  100878. }
  100879. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  100880. if (!_this._lastPointerRay[pointerId]) {
  100881. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100882. }
  100883. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  100884. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  100885. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  100886. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  100887. _this._moveDrag(pointerInfo.pickInfo.ray);
  100888. }
  100889. }
  100890. }
  100891. });
  100892. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100893. if (_this._moving && _this.moveAttached) {
  100894. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  100895. // Slowly move mesh to avoid jitter
  100896. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  100897. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  100898. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  100899. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  100900. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  100901. }
  100902. });
  100903. };
  100904. /**
  100905. * Force relase the drag action by code.
  100906. */
  100907. PointerDragBehavior.prototype.releaseDrag = function () {
  100908. this.dragging = false;
  100909. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  100910. this.currentDraggingPointerID = -1;
  100911. this._moving = false;
  100912. // Reattach camera controls
  100913. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100914. this._scene.activeCamera.attachControl(this._attachedElement, true);
  100915. }
  100916. };
  100917. /**
  100918. * Simulates the start of a pointer drag event on the behavior
  100919. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  100920. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  100921. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  100922. */
  100923. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  100924. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  100925. this._startDrag(pointerId, fromRay, startPickedPoint);
  100926. var lastRay = this._lastPointerRay[pointerId];
  100927. if (pointerId === PointerDragBehavior._AnyMouseID) {
  100928. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  100929. }
  100930. if (lastRay) {
  100931. // if there was a last pointer ray drag the object there
  100932. this._moveDrag(lastRay);
  100933. }
  100934. };
  100935. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  100936. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  100937. return;
  100938. }
  100939. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  100940. // Create start ray from the camera to the object
  100941. if (fromRay) {
  100942. this._startDragRay.direction.copyFrom(fromRay.direction);
  100943. this._startDragRay.origin.copyFrom(fromRay.origin);
  100944. }
  100945. else {
  100946. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  100947. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  100948. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  100949. }
  100950. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  100951. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  100952. if (pickedPoint) {
  100953. this.dragging = true;
  100954. this.currentDraggingPointerID = pointerId;
  100955. this.lastDragPosition.copyFrom(pickedPoint);
  100956. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  100957. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  100958. // Detatch camera controls
  100959. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100960. if (this._scene.activeCamera.inputs.attachedElement) {
  100961. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  100962. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  100963. }
  100964. else {
  100965. this._attachedElement = null;
  100966. }
  100967. }
  100968. }
  100969. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  100970. };
  100971. PointerDragBehavior.prototype._moveDrag = function (ray) {
  100972. this._moving = true;
  100973. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  100974. if (pickedPoint) {
  100975. if (this.updateDragPlane) {
  100976. this._updateDragPlanePosition(ray, pickedPoint);
  100977. }
  100978. var dragLength = 0;
  100979. // depending on the drag mode option drag accordingly
  100980. if (this._options.dragAxis) {
  100981. // Convert local drag axis to world
  100982. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  100983. // Project delta drag from the drag plane onto the drag axis
  100984. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  100985. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  100986. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  100987. }
  100988. else {
  100989. dragLength = this._dragDelta.length();
  100990. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  100991. }
  100992. this._targetPosition.addInPlace(this._dragDelta);
  100993. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  100994. this.lastDragPosition.copyFrom(pickedPoint);
  100995. }
  100996. };
  100997. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  100998. var _this = this;
  100999. if (!ray) {
  101000. return null;
  101001. }
  101002. // Calculate angle between plane normal and ray
  101003. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101004. // Correct if ray is casted from oposite side
  101005. if (angle > Math.PI / 2) {
  101006. angle = Math.PI - angle;
  101007. }
  101008. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101009. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101010. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101011. // Invert ray direction along the towards object axis
  101012. this._tmpVector.copyFrom(ray.direction);
  101013. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101014. this._alternatePickedPoint.normalize();
  101015. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101016. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101017. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101018. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101019. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101020. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101021. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101022. return this._alternatePickedPoint;
  101023. }
  101024. else {
  101025. return null;
  101026. }
  101027. }
  101028. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101029. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101030. return pickResult.pickedPoint;
  101031. }
  101032. else {
  101033. return null;
  101034. }
  101035. };
  101036. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101037. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101038. this._pointA.copyFrom(dragPlanePosition);
  101039. if (this._options.dragAxis) {
  101040. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101041. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101042. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101043. ray.origin.subtractToRef(this._pointA, this._pointC);
  101044. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101045. // Get perpendicular line from direction to camera and drag axis
  101046. this._pointB.subtractToRef(this._pointA, this._lineA);
  101047. this._pointC.subtractToRef(this._pointA, this._lineB);
  101048. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101049. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101050. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101051. this._lookAt.normalize();
  101052. this._dragPlane.position.copyFrom(this._pointA);
  101053. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101054. this._dragPlane.lookAt(this._lookAt);
  101055. }
  101056. else if (this._options.dragPlaneNormal) {
  101057. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101058. this._dragPlane.position.copyFrom(this._pointA);
  101059. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101060. this._dragPlane.lookAt(this._lookAt);
  101061. }
  101062. else {
  101063. this._dragPlane.position.copyFrom(this._pointA);
  101064. this._dragPlane.lookAt(ray.origin);
  101065. }
  101066. this._dragPlane.computeWorldMatrix(true);
  101067. };
  101068. /**
  101069. * Detaches the behavior from the mesh
  101070. */
  101071. PointerDragBehavior.prototype.detach = function () {
  101072. if (this._pointerObserver) {
  101073. this._scene.onPointerObservable.remove(this._pointerObserver);
  101074. }
  101075. if (this._beforeRenderObserver) {
  101076. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101077. }
  101078. };
  101079. PointerDragBehavior._AnyMouseID = -2;
  101080. return PointerDragBehavior;
  101081. }());
  101082. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101083. })(BABYLON || (BABYLON = {}));
  101084. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  101085. var BABYLON;
  101086. (function (BABYLON) {
  101087. /**
  101088. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101089. */
  101090. var MultiPointerScaleBehavior = /** @class */ (function () {
  101091. /**
  101092. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101093. */
  101094. function MultiPointerScaleBehavior() {
  101095. this._startDistance = 0;
  101096. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101097. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101098. this._sceneRenderObserver = null;
  101099. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101100. this._dragBehaviorA.moveAttached = false;
  101101. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101102. this._dragBehaviorB.moveAttached = false;
  101103. }
  101104. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101105. /**
  101106. * The name of the behavior
  101107. */
  101108. get: function () {
  101109. return "MultiPointerScale";
  101110. },
  101111. enumerable: true,
  101112. configurable: true
  101113. });
  101114. /**
  101115. * Initializes the behavior
  101116. */
  101117. MultiPointerScaleBehavior.prototype.init = function () { };
  101118. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101119. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101120. };
  101121. /**
  101122. * Attaches the scale behavior the passed in mesh
  101123. * @param ownerNode The mesh that will be scaled around once attached
  101124. */
  101125. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101126. var _this = this;
  101127. this._ownerNode = ownerNode;
  101128. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101129. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101130. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101131. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101132. _this._dragBehaviorA.releaseDrag();
  101133. }
  101134. else {
  101135. _this._initialScale.copyFrom(ownerNode.scaling);
  101136. _this._startDistance = _this._getCurrentDistance();
  101137. }
  101138. }
  101139. });
  101140. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101141. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101142. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101143. _this._dragBehaviorB.releaseDrag();
  101144. }
  101145. else {
  101146. _this._initialScale.copyFrom(ownerNode.scaling);
  101147. _this._startDistance = _this._getCurrentDistance();
  101148. }
  101149. }
  101150. });
  101151. // Once both drag behaviors are active scale based on the distance between the two pointers
  101152. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101153. behavior.onDragObservable.add(function () {
  101154. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101155. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101156. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101157. }
  101158. });
  101159. });
  101160. ownerNode.addBehavior(this._dragBehaviorA);
  101161. ownerNode.addBehavior(this._dragBehaviorB);
  101162. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101163. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101164. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101165. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101166. if (change.length() > 0.01) {
  101167. ownerNode.scaling.addInPlace(change);
  101168. }
  101169. }
  101170. });
  101171. };
  101172. /**
  101173. * Detaches the behavior from the mesh
  101174. */
  101175. MultiPointerScaleBehavior.prototype.detach = function () {
  101176. var _this = this;
  101177. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101178. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101179. behavior.onDragStartObservable.clear();
  101180. behavior.onDragObservable.clear();
  101181. _this._ownerNode.removeBehavior(behavior);
  101182. });
  101183. };
  101184. return MultiPointerScaleBehavior;
  101185. }());
  101186. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101187. })(BABYLON || (BABYLON = {}));
  101188. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  101189. var BABYLON;
  101190. (function (BABYLON) {
  101191. /**
  101192. * 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
  101193. */
  101194. var SixDofDragBehavior = /** @class */ (function () {
  101195. /**
  101196. * 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
  101197. */
  101198. function SixDofDragBehavior() {
  101199. this._sceneRenderObserver = null;
  101200. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101201. this._moving = false;
  101202. this._startingOrientation = new BABYLON.Quaternion();
  101203. /**
  101204. * 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)
  101205. */
  101206. this.zDragFactor = 3;
  101207. /**
  101208. * If the behavior is currently in a dragging state
  101209. */
  101210. this.dragging = false;
  101211. /**
  101212. * 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)
  101213. */
  101214. this.dragDeltaRatio = 0.2;
  101215. /**
  101216. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101217. */
  101218. this.currentDraggingPointerID = -1;
  101219. /**
  101220. * If camera controls should be detached during the drag
  101221. */
  101222. this.detachCameraControls = true;
  101223. /**
  101224. * Fires each time a drag starts
  101225. */
  101226. this.onDragStartObservable = new BABYLON.Observable();
  101227. /**
  101228. * Fires each time a drag ends (eg. mouse release after drag)
  101229. */
  101230. this.onDragEndObservable = new BABYLON.Observable();
  101231. }
  101232. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101233. /**
  101234. * The name of the behavior
  101235. */
  101236. get: function () {
  101237. return "SixDofDrag";
  101238. },
  101239. enumerable: true,
  101240. configurable: true
  101241. });
  101242. /**
  101243. * Initializes the behavior
  101244. */
  101245. SixDofDragBehavior.prototype.init = function () { };
  101246. /**
  101247. * Attaches the scale behavior the passed in mesh
  101248. * @param ownerNode The mesh that will be scaled around once attached
  101249. */
  101250. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101251. var _this = this;
  101252. this._ownerNode = ownerNode;
  101253. this._scene = this._ownerNode.getScene();
  101254. if (!SixDofDragBehavior._virtualScene) {
  101255. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101256. SixDofDragBehavior._virtualScene.detachControl();
  101257. this._scene.getEngine().scenes.pop();
  101258. }
  101259. var pickedMesh = null;
  101260. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101261. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101262. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101263. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101264. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101265. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101266. var pickPredicate = function (m) {
  101267. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101268. };
  101269. var attachedElement = null;
  101270. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101271. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101272. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101273. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101274. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101275. }
  101276. pickedMesh = _this._ownerNode;
  101277. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101278. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101279. // Set position and orientation of the controller
  101280. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101281. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101282. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101283. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101284. pickedMesh.computeWorldMatrix();
  101285. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101286. if (!pickedMesh.rotationQuaternion) {
  101287. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101288. }
  101289. var oldParent = pickedMesh.parent;
  101290. pickedMesh.setParent(null);
  101291. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101292. pickedMesh.setParent(oldParent);
  101293. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101294. // Update state
  101295. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101296. _this.dragging = true;
  101297. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101298. // Detatch camera controls
  101299. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101300. if (_this._scene.activeCamera.inputs.attachedElement) {
  101301. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101302. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101303. }
  101304. else {
  101305. attachedElement = null;
  101306. }
  101307. }
  101308. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101309. _this.onDragStartObservable.notifyObservers({});
  101310. }
  101311. }
  101312. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101313. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101314. _this.dragging = false;
  101315. _this._moving = false;
  101316. _this.currentDraggingPointerID = -1;
  101317. pickedMesh = null;
  101318. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101319. // Reattach camera controls
  101320. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101321. _this._scene.activeCamera.attachControl(attachedElement, true);
  101322. }
  101323. _this.onDragEndObservable.notifyObservers({});
  101324. }
  101325. }
  101326. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101327. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101328. var zDragFactor = _this.zDragFactor;
  101329. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101330. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101331. zDragFactor = 0;
  101332. }
  101333. // Calculate controller drag distance in controller space
  101334. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101335. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101336. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101337. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101338. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101339. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101340. if (_this._virtualDragMesh.position.z < 0) {
  101341. _this._virtualDragMesh.position.z = 0;
  101342. }
  101343. // Update the controller position
  101344. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101345. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101346. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101347. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101348. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101349. if (pickedMesh.parent) {
  101350. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101351. }
  101352. if (!_this._moving) {
  101353. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101354. }
  101355. _this._moving = true;
  101356. }
  101357. }
  101358. });
  101359. var tmpQuaternion = new BABYLON.Quaternion();
  101360. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101361. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101362. if (_this.dragging && _this._moving && pickedMesh) {
  101363. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101364. // Slowly move mesh to avoid jitter
  101365. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101366. // Get change in rotation
  101367. tmpQuaternion.copyFrom(_this._startingOrientation);
  101368. tmpQuaternion.x = -tmpQuaternion.x;
  101369. tmpQuaternion.y = -tmpQuaternion.y;
  101370. tmpQuaternion.z = -tmpQuaternion.z;
  101371. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101372. // Convert change in rotation to only y axis rotation
  101373. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101374. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101375. // Slowly move mesh to avoid jitter
  101376. var oldParent = pickedMesh.parent;
  101377. pickedMesh.setParent(null);
  101378. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101379. pickedMesh.setParent(oldParent);
  101380. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101381. }
  101382. });
  101383. };
  101384. /**
  101385. * Detaches the behavior from the mesh
  101386. */
  101387. SixDofDragBehavior.prototype.detach = function () {
  101388. if (this._scene) {
  101389. this._scene.onPointerObservable.remove(this._pointerObserver);
  101390. }
  101391. if (this._ownerNode) {
  101392. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101393. }
  101394. if (this._virtualOriginMesh) {
  101395. this._virtualOriginMesh.dispose();
  101396. }
  101397. if (this._virtualDragMesh) {
  101398. this._virtualDragMesh.dispose();
  101399. }
  101400. this.onDragEndObservable.clear();
  101401. this.onDragStartObservable.clear();
  101402. };
  101403. return SixDofDragBehavior;
  101404. }());
  101405. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  101406. })(BABYLON || (BABYLON = {}));
  101407. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  101408. var BABYLON;
  101409. (function (BABYLON) {
  101410. /**
  101411. * @hidden
  101412. */
  101413. var FaceDirectionInfo = /** @class */ (function () {
  101414. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  101415. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  101416. if (diff === void 0) { diff = 0; }
  101417. if (ignore === void 0) { ignore = false; }
  101418. this.direction = direction;
  101419. this.rotatedDirection = rotatedDirection;
  101420. this.diff = diff;
  101421. this.ignore = ignore;
  101422. }
  101423. return FaceDirectionInfo;
  101424. }());
  101425. /**
  101426. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  101427. */
  101428. var AttachToBoxBehavior = /** @class */ (function () {
  101429. /**
  101430. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  101431. * @param ui The transform node that should be attched to the mesh
  101432. */
  101433. function AttachToBoxBehavior(ui) {
  101434. this.ui = ui;
  101435. /**
  101436. * The name of the behavior
  101437. */
  101438. this.name = "AttachToBoxBehavior";
  101439. /**
  101440. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  101441. */
  101442. this.distanceAwayFromFace = 0.15;
  101443. /**
  101444. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  101445. */
  101446. this.distanceAwayFromBottomOfFace = 0.15;
  101447. 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))];
  101448. this._tmpMatrix = new BABYLON.Matrix();
  101449. this._tmpVector = new BABYLON.Vector3();
  101450. this._zeroVector = BABYLON.Vector3.Zero();
  101451. this._lookAtTmpMatrix = new BABYLON.Matrix();
  101452. /* Does nothing */
  101453. }
  101454. /**
  101455. * Initializes the behavior
  101456. */
  101457. AttachToBoxBehavior.prototype.init = function () {
  101458. /* Does nothing */
  101459. };
  101460. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  101461. var _this = this;
  101462. // Go over each face and calculate the angle between the face's normal and targetDirection
  101463. this._faceVectors.forEach(function (v) {
  101464. if (!_this._target.rotationQuaternion) {
  101465. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  101466. }
  101467. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  101468. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  101469. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  101470. });
  101471. // Return the face information of the one with the normal closeset to target direction
  101472. return this._faceVectors.reduce(function (min, p) {
  101473. if (min.ignore) {
  101474. return p;
  101475. }
  101476. else if (p.ignore) {
  101477. return min;
  101478. }
  101479. else {
  101480. return min.diff < p.diff ? min : p;
  101481. }
  101482. }, this._faceVectors[0]);
  101483. };
  101484. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  101485. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  101486. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  101487. this._lookAtTmpMatrix.invert();
  101488. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  101489. };
  101490. /**
  101491. * Attaches the AttachToBoxBehavior to the passed in mesh
  101492. * @param target The mesh that the specified node will be attached to
  101493. */
  101494. AttachToBoxBehavior.prototype.attach = function (target) {
  101495. var _this = this;
  101496. this._target = target;
  101497. this._scene = this._target.getScene();
  101498. // Every frame, update the app bars position
  101499. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101500. if (!_this._scene.activeCamera) {
  101501. return;
  101502. }
  101503. // Find the face closest to the cameras position
  101504. var cameraPos = _this._scene.activeCamera.position;
  101505. if (_this._scene.activeCamera.devicePosition) {
  101506. cameraPos = _this._scene.activeCamera.devicePosition;
  101507. }
  101508. var facing = _this._closestFace(cameraPos.subtract(target.position));
  101509. if (_this._scene.activeCamera.leftCamera) {
  101510. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101511. }
  101512. else {
  101513. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101514. }
  101515. // Get camera up direction
  101516. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  101517. // Ignore faces to not select a parrelel face for the up vector of the UI
  101518. _this._faceVectors.forEach(function (v) {
  101519. if (facing.direction.x && v.direction.x) {
  101520. v.ignore = true;
  101521. }
  101522. if (facing.direction.y && v.direction.y) {
  101523. v.ignore = true;
  101524. }
  101525. if (facing.direction.z && v.direction.z) {
  101526. v.ignore = true;
  101527. }
  101528. });
  101529. var facingUp = _this._closestFace(_this._tmpVector);
  101530. // Unignore faces
  101531. _this._faceVectors.forEach(function (v) {
  101532. v.ignore = false;
  101533. });
  101534. // Position the app bar on that face
  101535. _this.ui.position.copyFrom(target.position);
  101536. if (facing.direction.x) {
  101537. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101538. _this.ui.position.addInPlace(_this._tmpVector);
  101539. }
  101540. if (facing.direction.y) {
  101541. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101542. _this.ui.position.addInPlace(_this._tmpVector);
  101543. }
  101544. if (facing.direction.z) {
  101545. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101546. _this.ui.position.addInPlace(_this._tmpVector);
  101547. }
  101548. // Rotate to be oriented properly to the camera
  101549. if (!_this.ui.rotationQuaternion) {
  101550. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  101551. }
  101552. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  101553. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  101554. // Place ui the correct distance from the bottom of the mesh
  101555. if (facingUp.direction.x) {
  101556. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  101557. }
  101558. if (facingUp.direction.y) {
  101559. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  101560. }
  101561. if (facingUp.direction.z) {
  101562. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  101563. }
  101564. _this.ui.position.addInPlace(_this._tmpVector);
  101565. });
  101566. };
  101567. /**
  101568. * Detaches the behavior from the mesh
  101569. */
  101570. AttachToBoxBehavior.prototype.detach = function () {
  101571. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  101572. };
  101573. return AttachToBoxBehavior;
  101574. }());
  101575. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  101576. })(BABYLON || (BABYLON = {}));
  101577. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  101578. var BABYLON;
  101579. (function (BABYLON) {
  101580. /**
  101581. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  101582. */
  101583. var FadeInOutBehavior = /** @class */ (function () {
  101584. /**
  101585. * Instatiates the FadeInOutBehavior
  101586. */
  101587. function FadeInOutBehavior() {
  101588. var _this = this;
  101589. /**
  101590. * Time in milliseconds to delay before fading in (Default: 0)
  101591. */
  101592. this.delay = 0;
  101593. /**
  101594. * Time in milliseconds for the mesh to fade in (Default: 300)
  101595. */
  101596. this.fadeInTime = 300;
  101597. this._millisecondsPerFrame = 1000 / 60;
  101598. this._hovered = false;
  101599. this._hoverValue = 0;
  101600. this._ownerNode = null;
  101601. this._update = function () {
  101602. if (_this._ownerNode) {
  101603. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  101604. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  101605. if (_this._ownerNode.visibility > 1) {
  101606. _this._setAllVisibility(_this._ownerNode, 1);
  101607. _this._hoverValue = _this.fadeInTime + _this.delay;
  101608. return;
  101609. }
  101610. else if (_this._ownerNode.visibility < 0) {
  101611. _this._setAllVisibility(_this._ownerNode, 0);
  101612. if (_this._hoverValue < 0) {
  101613. _this._hoverValue = 0;
  101614. return;
  101615. }
  101616. }
  101617. setTimeout(_this._update, _this._millisecondsPerFrame);
  101618. }
  101619. };
  101620. }
  101621. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  101622. /**
  101623. * The name of the behavior
  101624. */
  101625. get: function () {
  101626. return "FadeInOut";
  101627. },
  101628. enumerable: true,
  101629. configurable: true
  101630. });
  101631. /**
  101632. * Initializes the behavior
  101633. */
  101634. FadeInOutBehavior.prototype.init = function () {
  101635. };
  101636. /**
  101637. * Attaches the fade behavior on the passed in mesh
  101638. * @param ownerNode The mesh that will be faded in/out once attached
  101639. */
  101640. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  101641. this._ownerNode = ownerNode;
  101642. this._setAllVisibility(this._ownerNode, 0);
  101643. };
  101644. /**
  101645. * Detaches the behavior from the mesh
  101646. */
  101647. FadeInOutBehavior.prototype.detach = function () {
  101648. this._ownerNode = null;
  101649. };
  101650. /**
  101651. * Triggers the mesh to begin fading in or out
  101652. * @param value if the object should fade in or out (true to fade in)
  101653. */
  101654. FadeInOutBehavior.prototype.fadeIn = function (value) {
  101655. this._hovered = value;
  101656. this._update();
  101657. };
  101658. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  101659. var _this = this;
  101660. mesh.visibility = value;
  101661. mesh.getChildMeshes().forEach(function (c) {
  101662. _this._setAllVisibility(c, value);
  101663. });
  101664. };
  101665. return FadeInOutBehavior;
  101666. }());
  101667. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  101668. })(BABYLON || (BABYLON = {}));
  101669. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  101670. var BABYLON;
  101671. (function (BABYLON) {
  101672. /**
  101673. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  101674. */
  101675. var Gizmo = /** @class */ (function () {
  101676. /**
  101677. * Creates a gizmo
  101678. * @param gizmoLayer The utility layer the gizmo will be added to
  101679. */
  101680. function Gizmo(
  101681. /** The utility layer the gizmo will be added to */
  101682. gizmoLayer) {
  101683. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101684. var _this = this;
  101685. this.gizmoLayer = gizmoLayer;
  101686. /**
  101687. * Ratio for the scale of the gizmo (Default: 1)
  101688. */
  101689. this.scaleRatio = 1;
  101690. this._tmpMatrix = new BABYLON.Matrix();
  101691. /**
  101692. * If a custom mesh has been set (Default: false)
  101693. */
  101694. this._customMeshSet = false;
  101695. /**
  101696. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  101697. */
  101698. this.updateGizmoRotationToMatchAttachedMesh = true;
  101699. /**
  101700. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  101701. */
  101702. this.updateGizmoPositionToMatchAttachedMesh = true;
  101703. /**
  101704. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  101705. */
  101706. this._updateScale = true;
  101707. this._interactionsEnabled = true;
  101708. this._tempVector = new BABYLON.Vector3();
  101709. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  101710. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  101711. _this._update();
  101712. });
  101713. this.attachedMesh = null;
  101714. }
  101715. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  101716. /**
  101717. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  101718. * * When set, interactions will be enabled
  101719. */
  101720. get: function () {
  101721. return this._attachedMesh;
  101722. },
  101723. set: function (value) {
  101724. this._attachedMesh = value;
  101725. this._rootMesh.setEnabled(value ? true : false);
  101726. this._attachedMeshChanged(value);
  101727. },
  101728. enumerable: true,
  101729. configurable: true
  101730. });
  101731. /**
  101732. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  101733. * @param mesh The mesh to replace the default mesh of the gizmo
  101734. */
  101735. Gizmo.prototype.setCustomMesh = function (mesh) {
  101736. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  101737. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  101738. }
  101739. this._rootMesh.getChildMeshes().forEach(function (c) {
  101740. c.dispose();
  101741. });
  101742. mesh.parent = this._rootMesh;
  101743. this._customMeshSet = true;
  101744. };
  101745. Gizmo.prototype._attachedMeshChanged = function (value) {
  101746. };
  101747. /**
  101748. * @hidden
  101749. * Updates the gizmo to match the attached mesh's position/rotation
  101750. */
  101751. Gizmo.prototype._update = function () {
  101752. if (this.attachedMesh) {
  101753. if (this.updateGizmoRotationToMatchAttachedMesh) {
  101754. if (!this._rootMesh.rotationQuaternion) {
  101755. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  101756. }
  101757. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  101758. this._tempVector.copyFrom(this.attachedMesh.scaling);
  101759. if (this.attachedMesh.scaling.x < 0) {
  101760. this.attachedMesh.scaling.x *= -1;
  101761. }
  101762. if (this.attachedMesh.scaling.y < 0) {
  101763. this.attachedMesh.scaling.y *= -1;
  101764. }
  101765. if (this.attachedMesh.scaling.z < 0) {
  101766. this.attachedMesh.scaling.z *= -1;
  101767. }
  101768. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  101769. this.attachedMesh.scaling.copyFrom(this._tempVector);
  101770. this.attachedMesh.computeWorldMatrix();
  101771. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  101772. }
  101773. else if (this._rootMesh.rotationQuaternion) {
  101774. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  101775. }
  101776. if (this.updateGizmoPositionToMatchAttachedMesh) {
  101777. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  101778. }
  101779. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  101780. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  101781. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  101782. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  101783. }
  101784. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  101785. var dist = this._tempVector.length() * this.scaleRatio;
  101786. this._rootMesh.scaling.set(dist, dist, dist);
  101787. }
  101788. }
  101789. };
  101790. /**
  101791. * Disposes of the gizmo
  101792. */
  101793. Gizmo.prototype.dispose = function () {
  101794. this._rootMesh.dispose();
  101795. if (this._beforeRenderObserver) {
  101796. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101797. }
  101798. };
  101799. return Gizmo;
  101800. }());
  101801. BABYLON.Gizmo = Gizmo;
  101802. })(BABYLON || (BABYLON = {}));
  101803. //# sourceMappingURL=babylon.gizmo.js.map
  101804. var BABYLON;
  101805. (function (BABYLON) {
  101806. /**
  101807. * Single axis drag gizmo
  101808. */
  101809. var AxisDragGizmo = /** @class */ (function (_super) {
  101810. __extends(AxisDragGizmo, _super);
  101811. /**
  101812. * Creates an AxisDragGizmo
  101813. * @param gizmoLayer The utility layer the gizmo will be added to
  101814. * @param dragAxis The axis which the gizmo will be able to drag on
  101815. * @param color The color of the gizmo
  101816. */
  101817. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  101818. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101819. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101820. var _this = _super.call(this, gizmoLayer) || this;
  101821. _this._pointerObserver = null;
  101822. /**
  101823. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101824. */
  101825. _this.snapDistance = 0;
  101826. /**
  101827. * Event that fires each time the gizmo snaps to a new location.
  101828. * * snapDistance is the the change in distance
  101829. */
  101830. _this.onSnapObservable = new BABYLON.Observable();
  101831. // Create Material
  101832. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101833. coloredMaterial.disableLighting = true;
  101834. coloredMaterial.emissiveColor = color;
  101835. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101836. hoverMaterial.disableLighting = true;
  101837. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101838. // Build mesh on root node
  101839. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101840. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  101841. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101842. arrowTail.color = coloredMaterial.emissiveColor;
  101843. arrow.addChild(arrowMesh);
  101844. arrow.addChild(arrowTail);
  101845. // Position arrow pointing in its drag axis
  101846. arrowMesh.scaling.scaleInPlace(0.05);
  101847. arrowMesh.material = coloredMaterial;
  101848. arrowMesh.rotation.x = Math.PI / 2;
  101849. arrowMesh.position.z += 0.3;
  101850. arrowTail.scaling.scaleInPlace(0.26);
  101851. arrowTail.rotation.x = Math.PI / 2;
  101852. arrowTail.material = coloredMaterial;
  101853. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101854. arrow.scaling.scaleInPlace(1 / 3);
  101855. _this._rootMesh.addChild(arrow);
  101856. var currentSnapDragDistance = 0;
  101857. var tmpVector = new BABYLON.Vector3();
  101858. var tmpSnapEvent = { snapDistance: 0 };
  101859. // Add drag behavior to handle events when the gizmo is dragged
  101860. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101861. _this.dragBehavior.moveAttached = false;
  101862. _this._rootMesh.addBehavior(_this.dragBehavior);
  101863. var localDelta = new BABYLON.Vector3();
  101864. var tmpMatrix = new BABYLON.Matrix();
  101865. _this.dragBehavior.onDragObservable.add(function (event) {
  101866. if (_this.attachedMesh) {
  101867. // Convert delta to local translation if it has a parent
  101868. if (_this.attachedMesh.parent) {
  101869. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  101870. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  101871. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  101872. }
  101873. else {
  101874. localDelta.copyFrom(event.delta);
  101875. }
  101876. // Snapping logic
  101877. if (_this.snapDistance == 0) {
  101878. _this.attachedMesh.position.addInPlace(localDelta);
  101879. }
  101880. else {
  101881. currentSnapDragDistance += event.dragDistance;
  101882. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  101883. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  101884. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  101885. localDelta.normalizeToRef(tmpVector);
  101886. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  101887. _this.attachedMesh.position.addInPlace(tmpVector);
  101888. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  101889. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101890. }
  101891. }
  101892. }
  101893. });
  101894. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101895. if (_this._customMeshSet) {
  101896. return;
  101897. }
  101898. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101899. var material = isHovered ? hoverMaterial : coloredMaterial;
  101900. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101901. m.material = material;
  101902. if (m.color) {
  101903. m.color = material.emissiveColor;
  101904. }
  101905. });
  101906. });
  101907. return _this;
  101908. }
  101909. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  101910. if (this.dragBehavior) {
  101911. this.dragBehavior.enabled = value ? true : false;
  101912. }
  101913. };
  101914. /**
  101915. * Disposes of the gizmo
  101916. */
  101917. AxisDragGizmo.prototype.dispose = function () {
  101918. this.onSnapObservable.clear();
  101919. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101920. this.dragBehavior.detach();
  101921. _super.prototype.dispose.call(this);
  101922. };
  101923. return AxisDragGizmo;
  101924. }(BABYLON.Gizmo));
  101925. BABYLON.AxisDragGizmo = AxisDragGizmo;
  101926. })(BABYLON || (BABYLON = {}));
  101927. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  101928. var BABYLON;
  101929. (function (BABYLON) {
  101930. /**
  101931. * Single axis scale gizmo
  101932. */
  101933. var AxisScaleGizmo = /** @class */ (function (_super) {
  101934. __extends(AxisScaleGizmo, _super);
  101935. /**
  101936. * Creates an AxisScaleGizmo
  101937. * @param gizmoLayer The utility layer the gizmo will be added to
  101938. * @param dragAxis The axis which the gizmo will be able to scale on
  101939. * @param color The color of the gizmo
  101940. */
  101941. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  101942. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101943. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101944. var _this = _super.call(this, gizmoLayer) || this;
  101945. _this._pointerObserver = null;
  101946. /**
  101947. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101948. */
  101949. _this.snapDistance = 0;
  101950. /**
  101951. * Event that fires each time the gizmo snaps to a new location.
  101952. * * snapDistance is the the change in distance
  101953. */
  101954. _this.onSnapObservable = new BABYLON.Observable();
  101955. /**
  101956. * If the scaling operation should be done on all axis (default: false)
  101957. */
  101958. _this.uniformScaling = false;
  101959. // Create Material
  101960. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101961. _this._coloredMaterial.disableLighting = true;
  101962. _this._coloredMaterial.emissiveColor = color;
  101963. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101964. hoverMaterial.disableLighting = true;
  101965. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101966. // Build mesh on root node
  101967. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101968. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  101969. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101970. arrowTail.color = _this._coloredMaterial.emissiveColor;
  101971. arrow.addChild(arrowMesh);
  101972. arrow.addChild(arrowTail);
  101973. // Position arrow pointing in its drag axis
  101974. arrowMesh.scaling.scaleInPlace(0.1);
  101975. arrowMesh.material = _this._coloredMaterial;
  101976. arrowMesh.rotation.x = Math.PI / 2;
  101977. arrowMesh.position.z += 0.3;
  101978. arrowTail.scaling.scaleInPlace(0.26);
  101979. arrowTail.rotation.x = Math.PI / 2;
  101980. arrowTail.material = _this._coloredMaterial;
  101981. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101982. _this._rootMesh.addChild(arrow);
  101983. arrow.scaling.scaleInPlace(1 / 3);
  101984. // Add drag behavior to handle events when the gizmo is dragged
  101985. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101986. _this.dragBehavior.moveAttached = false;
  101987. _this._rootMesh.addBehavior(_this.dragBehavior);
  101988. var currentSnapDragDistance = 0;
  101989. var tmpVector = new BABYLON.Vector3();
  101990. var tmpSnapEvent = { snapDistance: 0 };
  101991. _this.dragBehavior.onDragObservable.add(function (event) {
  101992. if (_this.attachedMesh) {
  101993. // Snapping logic
  101994. var snapped = false;
  101995. var dragSteps = 0;
  101996. if (_this.uniformScaling) {
  101997. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  101998. if (tmpVector.y < 0) {
  101999. tmpVector.scaleInPlace(-1);
  102000. }
  102001. }
  102002. else {
  102003. tmpVector.copyFrom(dragAxis);
  102004. }
  102005. if (_this.snapDistance == 0) {
  102006. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102007. }
  102008. else {
  102009. currentSnapDragDistance += event.dragDistance;
  102010. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102011. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102012. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102013. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102014. snapped = true;
  102015. }
  102016. else {
  102017. tmpVector.scaleInPlace(0);
  102018. }
  102019. }
  102020. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102021. if (snapped) {
  102022. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102023. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102024. }
  102025. }
  102026. });
  102027. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102028. if (_this._customMeshSet) {
  102029. return;
  102030. }
  102031. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102032. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102033. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102034. m.material = material;
  102035. if (m.color) {
  102036. m.color = material.emissiveColor;
  102037. }
  102038. });
  102039. });
  102040. return _this;
  102041. }
  102042. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102043. if (this.dragBehavior) {
  102044. this.dragBehavior.enabled = value ? true : false;
  102045. }
  102046. };
  102047. /**
  102048. * Disposes of the gizmo
  102049. */
  102050. AxisScaleGizmo.prototype.dispose = function () {
  102051. this.onSnapObservable.clear();
  102052. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102053. this.dragBehavior.detach();
  102054. _super.prototype.dispose.call(this);
  102055. };
  102056. /**
  102057. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102058. * @param mesh The mesh to replace the default mesh of the gizmo
  102059. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102060. */
  102061. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102062. var _this = this;
  102063. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102064. _super.prototype.setCustomMesh.call(this, mesh);
  102065. if (useGizmoMaterial) {
  102066. this._rootMesh.getChildMeshes().forEach(function (m) {
  102067. m.material = _this._coloredMaterial;
  102068. if (m.color) {
  102069. m.color = _this._coloredMaterial.emissiveColor;
  102070. }
  102071. });
  102072. this._customMeshSet = false;
  102073. }
  102074. };
  102075. return AxisScaleGizmo;
  102076. }(BABYLON.Gizmo));
  102077. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102078. })(BABYLON || (BABYLON = {}));
  102079. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  102080. var BABYLON;
  102081. (function (BABYLON) {
  102082. /**
  102083. * Single plane rotation gizmo
  102084. */
  102085. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102086. __extends(PlaneRotationGizmo, _super);
  102087. /**
  102088. * Creates a PlaneRotationGizmo
  102089. * @param gizmoLayer The utility layer the gizmo will be added to
  102090. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102091. * @param color The color of the gizmo
  102092. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102093. */
  102094. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102095. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102096. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102097. if (tessellation === void 0) { tessellation = 32; }
  102098. var _this = _super.call(this, gizmoLayer) || this;
  102099. _this._pointerObserver = null;
  102100. /**
  102101. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102102. */
  102103. _this.snapDistance = 0;
  102104. /**
  102105. * Event that fires each time the gizmo snaps to a new location.
  102106. * * snapDistance is the the change in distance
  102107. */
  102108. _this.onSnapObservable = new BABYLON.Observable();
  102109. // Create Material
  102110. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102111. coloredMaterial.disableLighting = true;
  102112. coloredMaterial.emissiveColor = color;
  102113. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102114. hoverMaterial.disableLighting = true;
  102115. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102116. // Build mesh on root node
  102117. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102118. // Create circle out of lines
  102119. var radius = 0.8;
  102120. var points = new Array();
  102121. for (var i = 0; i < tessellation; i++) {
  102122. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102123. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102124. }
  102125. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102126. rotationMesh.color = coloredMaterial.emissiveColor;
  102127. // Position arrow pointing in its drag axis
  102128. rotationMesh.scaling.scaleInPlace(0.26);
  102129. rotationMesh.material = coloredMaterial;
  102130. rotationMesh.rotation.x = Math.PI / 2;
  102131. parentMesh.addChild(rotationMesh);
  102132. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102133. _this._rootMesh.addChild(parentMesh);
  102134. parentMesh.scaling.scaleInPlace(1 / 3);
  102135. // Add drag behavior to handle events when the gizmo is dragged
  102136. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102137. _this.dragBehavior.moveAttached = false;
  102138. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102139. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102140. _this._rootMesh.addBehavior(_this.dragBehavior);
  102141. var lastDragPosition = new BABYLON.Vector3();
  102142. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102143. if (_this.attachedMesh) {
  102144. lastDragPosition.copyFrom(e.dragPlanePoint);
  102145. }
  102146. });
  102147. var rotationMatrix = new BABYLON.Matrix();
  102148. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102149. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102150. var tmpSnapEvent = { snapDistance: 0 };
  102151. var currentSnapDragDistance = 0;
  102152. var tmpMatrix = new BABYLON.Matrix();
  102153. var tmpVector = new BABYLON.Vector3();
  102154. var amountToRotate = new BABYLON.Quaternion();
  102155. _this.dragBehavior.onDragObservable.add(function (event) {
  102156. if (_this.attachedMesh) {
  102157. if (!_this.attachedMesh.rotationQuaternion) {
  102158. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102159. }
  102160. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102161. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102162. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102163. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102164. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102165. var angle = Math.atan2(cross.length(), dot);
  102166. planeNormalTowardsCamera.copyFrom(planeNormal);
  102167. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102168. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102169. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102170. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102171. }
  102172. // Flip up vector depending on which side the camera is on
  102173. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102174. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102175. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102176. planeNormalTowardsCamera.scaleInPlace(-1);
  102177. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102178. }
  102179. }
  102180. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102181. if (halfCircleSide) {
  102182. angle = -angle;
  102183. }
  102184. // Snapping logic
  102185. var snapped = false;
  102186. if (_this.snapDistance != 0) {
  102187. currentSnapDragDistance += angle;
  102188. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102189. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102190. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102191. angle = _this.snapDistance * dragSteps;
  102192. snapped = true;
  102193. }
  102194. else {
  102195. angle = 0;
  102196. }
  102197. }
  102198. // If the mesh has a parent, convert needed world rotation to local rotation
  102199. tmpMatrix.reset();
  102200. if (_this.attachedMesh.parent) {
  102201. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102202. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102203. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102204. }
  102205. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102206. var quaternionCoefficient = Math.sin(angle / 2);
  102207. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102208. // 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
  102209. if (tmpMatrix.determinant() > 0) {
  102210. amountToRotate.toEulerAnglesToRef(tmpVector);
  102211. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102212. }
  102213. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102214. // Rotate selected mesh quaternion over fixed axis
  102215. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102216. }
  102217. else {
  102218. // Rotate selected mesh quaternion over rotated axis
  102219. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102220. }
  102221. lastDragPosition.copyFrom(event.dragPlanePoint);
  102222. if (snapped) {
  102223. tmpSnapEvent.snapDistance = angle;
  102224. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102225. }
  102226. }
  102227. });
  102228. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102229. if (_this._customMeshSet) {
  102230. return;
  102231. }
  102232. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102233. var material = isHovered ? hoverMaterial : coloredMaterial;
  102234. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102235. m.material = material;
  102236. if (m.color) {
  102237. m.color = material.emissiveColor;
  102238. }
  102239. });
  102240. });
  102241. return _this;
  102242. }
  102243. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102244. if (this.dragBehavior) {
  102245. this.dragBehavior.enabled = value ? true : false;
  102246. }
  102247. };
  102248. /**
  102249. * Disposes of the gizmo
  102250. */
  102251. PlaneRotationGizmo.prototype.dispose = function () {
  102252. this.onSnapObservable.clear();
  102253. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102254. this.dragBehavior.detach();
  102255. _super.prototype.dispose.call(this);
  102256. };
  102257. return PlaneRotationGizmo;
  102258. }(BABYLON.Gizmo));
  102259. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102260. })(BABYLON || (BABYLON = {}));
  102261. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  102262. var BABYLON;
  102263. (function (BABYLON) {
  102264. /**
  102265. * Gizmo that enables dragging a mesh along 3 axis
  102266. */
  102267. var PositionGizmo = /** @class */ (function (_super) {
  102268. __extends(PositionGizmo, _super);
  102269. /**
  102270. * Creates a PositionGizmo
  102271. * @param gizmoLayer The utility layer the gizmo will be added to
  102272. */
  102273. function PositionGizmo(gizmoLayer) {
  102274. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102275. var _this = _super.call(this, gizmoLayer) || this;
  102276. /** Fires an event when any of it's sub gizmos are dragged */
  102277. _this.onDragStartObservable = new BABYLON.Observable();
  102278. /** Fires an event when any of it's sub gizmos are released from dragging */
  102279. _this.onDragEndObservable = new BABYLON.Observable();
  102280. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102281. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102282. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102283. // Relay drag events
  102284. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102285. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102286. _this.onDragStartObservable.notifyObservers({});
  102287. });
  102288. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102289. _this.onDragEndObservable.notifyObservers({});
  102290. });
  102291. });
  102292. _this.attachedMesh = null;
  102293. return _this;
  102294. }
  102295. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102296. set: function (mesh) {
  102297. if (this.xGizmo) {
  102298. this.xGizmo.attachedMesh = mesh;
  102299. this.yGizmo.attachedMesh = mesh;
  102300. this.zGizmo.attachedMesh = mesh;
  102301. }
  102302. },
  102303. enumerable: true,
  102304. configurable: true
  102305. });
  102306. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102307. get: function () {
  102308. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102309. },
  102310. set: function (value) {
  102311. if (this.xGizmo) {
  102312. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102313. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102314. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102315. }
  102316. },
  102317. enumerable: true,
  102318. configurable: true
  102319. });
  102320. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102321. get: function () {
  102322. return this.xGizmo.snapDistance;
  102323. },
  102324. /**
  102325. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102326. */
  102327. set: function (value) {
  102328. if (this.xGizmo) {
  102329. this.xGizmo.snapDistance = value;
  102330. this.yGizmo.snapDistance = value;
  102331. this.zGizmo.snapDistance = value;
  102332. }
  102333. },
  102334. enumerable: true,
  102335. configurable: true
  102336. });
  102337. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102338. get: function () {
  102339. return this.xGizmo.scaleRatio;
  102340. },
  102341. /**
  102342. * Ratio for the scale of the gizmo (Default: 1)
  102343. */
  102344. set: function (value) {
  102345. if (this.xGizmo) {
  102346. this.xGizmo.scaleRatio = value;
  102347. this.yGizmo.scaleRatio = value;
  102348. this.zGizmo.scaleRatio = value;
  102349. }
  102350. },
  102351. enumerable: true,
  102352. configurable: true
  102353. });
  102354. /**
  102355. * Disposes of the gizmo
  102356. */
  102357. PositionGizmo.prototype.dispose = function () {
  102358. this.xGizmo.dispose();
  102359. this.yGizmo.dispose();
  102360. this.zGizmo.dispose();
  102361. this.onDragStartObservable.clear();
  102362. this.onDragEndObservable.clear();
  102363. };
  102364. /**
  102365. * CustomMeshes are not supported by this gizmo
  102366. * @param mesh The mesh to replace the default mesh of the gizmo
  102367. */
  102368. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102369. 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)");
  102370. };
  102371. return PositionGizmo;
  102372. }(BABYLON.Gizmo));
  102373. BABYLON.PositionGizmo = PositionGizmo;
  102374. })(BABYLON || (BABYLON = {}));
  102375. //# sourceMappingURL=babylon.positionGizmo.js.map
  102376. var BABYLON;
  102377. (function (BABYLON) {
  102378. /**
  102379. * Gizmo that enables rotating a mesh along 3 axis
  102380. */
  102381. var RotationGizmo = /** @class */ (function (_super) {
  102382. __extends(RotationGizmo, _super);
  102383. /**
  102384. * Creates a RotationGizmo
  102385. * @param gizmoLayer The utility layer the gizmo will be added to
  102386. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102387. */
  102388. function RotationGizmo(gizmoLayer, tessellation) {
  102389. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102390. if (tessellation === void 0) { tessellation = 32; }
  102391. var _this = _super.call(this, gizmoLayer) || this;
  102392. /** Fires an event when any of it's sub gizmos are dragged */
  102393. _this.onDragStartObservable = new BABYLON.Observable();
  102394. /** Fires an event when any of it's sub gizmos are released from dragging */
  102395. _this.onDragEndObservable = new BABYLON.Observable();
  102396. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  102397. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  102398. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  102399. // Relay drag events
  102400. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102401. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102402. _this.onDragStartObservable.notifyObservers({});
  102403. });
  102404. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102405. _this.onDragEndObservable.notifyObservers({});
  102406. });
  102407. });
  102408. _this.attachedMesh = null;
  102409. return _this;
  102410. }
  102411. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  102412. set: function (mesh) {
  102413. if (this.xGizmo) {
  102414. this.xGizmo.attachedMesh = mesh;
  102415. this.yGizmo.attachedMesh = mesh;
  102416. this.zGizmo.attachedMesh = mesh;
  102417. }
  102418. },
  102419. enumerable: true,
  102420. configurable: true
  102421. });
  102422. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102423. get: function () {
  102424. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102425. },
  102426. set: function (value) {
  102427. if (this.xGizmo) {
  102428. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102429. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102430. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102431. }
  102432. },
  102433. enumerable: true,
  102434. configurable: true
  102435. });
  102436. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  102437. get: function () {
  102438. return this.xGizmo.snapDistance;
  102439. },
  102440. /**
  102441. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102442. */
  102443. set: function (value) {
  102444. if (this.xGizmo) {
  102445. this.xGizmo.snapDistance = value;
  102446. this.yGizmo.snapDistance = value;
  102447. this.zGizmo.snapDistance = value;
  102448. }
  102449. },
  102450. enumerable: true,
  102451. configurable: true
  102452. });
  102453. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  102454. get: function () {
  102455. return this.xGizmo.scaleRatio;
  102456. },
  102457. /**
  102458. * Ratio for the scale of the gizmo (Default: 1)
  102459. */
  102460. set: function (value) {
  102461. if (this.xGizmo) {
  102462. this.xGizmo.scaleRatio = value;
  102463. this.yGizmo.scaleRatio = value;
  102464. this.zGizmo.scaleRatio = value;
  102465. }
  102466. },
  102467. enumerable: true,
  102468. configurable: true
  102469. });
  102470. /**
  102471. * Disposes of the gizmo
  102472. */
  102473. RotationGizmo.prototype.dispose = function () {
  102474. this.xGizmo.dispose();
  102475. this.yGizmo.dispose();
  102476. this.zGizmo.dispose();
  102477. this.onDragStartObservable.clear();
  102478. this.onDragEndObservable.clear();
  102479. };
  102480. /**
  102481. * CustomMeshes are not supported by this gizmo
  102482. * @param mesh The mesh to replace the default mesh of the gizmo
  102483. */
  102484. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  102485. 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)");
  102486. };
  102487. return RotationGizmo;
  102488. }(BABYLON.Gizmo));
  102489. BABYLON.RotationGizmo = RotationGizmo;
  102490. })(BABYLON || (BABYLON = {}));
  102491. //# sourceMappingURL=babylon.rotationGizmo.js.map
  102492. var BABYLON;
  102493. (function (BABYLON) {
  102494. /**
  102495. * Gizmo that enables scaling a mesh along 3 axis
  102496. */
  102497. var ScaleGizmo = /** @class */ (function (_super) {
  102498. __extends(ScaleGizmo, _super);
  102499. /**
  102500. * Creates a ScaleGizmo
  102501. * @param gizmoLayer The utility layer the gizmo will be added to
  102502. */
  102503. function ScaleGizmo(gizmoLayer) {
  102504. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102505. var _this = _super.call(this, gizmoLayer) || this;
  102506. /** Fires an event when any of it's sub gizmos are dragged */
  102507. _this.onDragStartObservable = new BABYLON.Observable();
  102508. /** Fires an event when any of it's sub gizmos are released from dragging */
  102509. _this.onDragEndObservable = new BABYLON.Observable();
  102510. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102511. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102512. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102513. // Create uniform scale gizmo
  102514. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  102515. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  102516. _this.uniformScaleGizmo.uniformScaling = true;
  102517. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102518. uniformScalingMesh.scaling.scaleInPlace(0.02);
  102519. uniformScalingMesh.visibility = 0;
  102520. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102521. octahedron.scaling.scaleInPlace(0.007);
  102522. uniformScalingMesh.addChild(octahedron);
  102523. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  102524. // Relay drag events
  102525. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  102526. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102527. _this.onDragStartObservable.notifyObservers({});
  102528. });
  102529. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102530. _this.onDragEndObservable.notifyObservers({});
  102531. });
  102532. });
  102533. _this.attachedMesh = null;
  102534. return _this;
  102535. }
  102536. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  102537. set: function (mesh) {
  102538. if (this.xGizmo) {
  102539. this.xGizmo.attachedMesh = mesh;
  102540. this.yGizmo.attachedMesh = mesh;
  102541. this.zGizmo.attachedMesh = mesh;
  102542. this.uniformScaleGizmo.attachedMesh = mesh;
  102543. }
  102544. },
  102545. enumerable: true,
  102546. configurable: true
  102547. });
  102548. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102549. get: function () {
  102550. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102551. },
  102552. set: function (value) {
  102553. if (!value) {
  102554. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  102555. }
  102556. if (this.xGizmo) {
  102557. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102558. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102559. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102560. }
  102561. },
  102562. enumerable: true,
  102563. configurable: true
  102564. });
  102565. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  102566. get: function () {
  102567. return this.xGizmo.snapDistance;
  102568. },
  102569. /**
  102570. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102571. */
  102572. set: function (value) {
  102573. if (this.xGizmo) {
  102574. this.xGizmo.snapDistance = value;
  102575. this.yGizmo.snapDistance = value;
  102576. this.zGizmo.snapDistance = value;
  102577. this.uniformScaleGizmo.snapDistance = value;
  102578. }
  102579. },
  102580. enumerable: true,
  102581. configurable: true
  102582. });
  102583. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  102584. get: function () {
  102585. return this.xGizmo.scaleRatio;
  102586. },
  102587. /**
  102588. * Ratio for the scale of the gizmo (Default: 1)
  102589. */
  102590. set: function (value) {
  102591. if (this.xGizmo) {
  102592. this.xGizmo.scaleRatio = value;
  102593. this.yGizmo.scaleRatio = value;
  102594. this.zGizmo.scaleRatio = value;
  102595. this.uniformScaleGizmo.scaleRatio = value;
  102596. }
  102597. },
  102598. enumerable: true,
  102599. configurable: true
  102600. });
  102601. /**
  102602. * Disposes of the gizmo
  102603. */
  102604. ScaleGizmo.prototype.dispose = function () {
  102605. this.xGizmo.dispose();
  102606. this.yGizmo.dispose();
  102607. this.zGizmo.dispose();
  102608. this.uniformScaleGizmo.dispose();
  102609. this.onDragStartObservable.clear();
  102610. this.onDragEndObservable.clear();
  102611. };
  102612. return ScaleGizmo;
  102613. }(BABYLON.Gizmo));
  102614. BABYLON.ScaleGizmo = ScaleGizmo;
  102615. })(BABYLON || (BABYLON = {}));
  102616. //# sourceMappingURL=babylon.scaleGizmo.js.map
  102617. var BABYLON;
  102618. (function (BABYLON) {
  102619. /**
  102620. * Bounding box gizmo
  102621. */
  102622. var BoundingBoxGizmo = /** @class */ (function (_super) {
  102623. __extends(BoundingBoxGizmo, _super);
  102624. /**
  102625. * Creates an BoundingBoxGizmo
  102626. * @param gizmoLayer The utility layer the gizmo will be added to
  102627. * @param color The color of the gizmo
  102628. */
  102629. function BoundingBoxGizmo(color, gizmoLayer) {
  102630. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102631. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  102632. var _this = _super.call(this, gizmoLayer) || this;
  102633. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  102634. _this._renderObserver = null;
  102635. _this._pointerObserver = null;
  102636. _this._scaleDragSpeed = 0.2;
  102637. _this._tmpQuaternion = new BABYLON.Quaternion();
  102638. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102639. _this._tmpRotationMatrix = new BABYLON.Matrix();
  102640. /**
  102641. * 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)
  102642. */
  102643. _this.ignoreChildren = false;
  102644. /**
  102645. * 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)
  102646. */
  102647. _this.includeChildPredicate = null;
  102648. /**
  102649. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  102650. */
  102651. _this.rotationSphereSize = 0.1;
  102652. /**
  102653. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  102654. */
  102655. _this.scaleBoxSize = 0.1;
  102656. /**
  102657. * 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)
  102658. */
  102659. _this.fixedDragMeshScreenSize = false;
  102660. /**
  102661. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  102662. */
  102663. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  102664. /**
  102665. * Fired when a rotation sphere or scale box is dragged
  102666. */
  102667. _this.onDragStartObservable = new BABYLON.Observable();
  102668. /**
  102669. * Fired when a scale box is dragged
  102670. */
  102671. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  102672. /**
  102673. * Fired when a scale box drag is ended
  102674. */
  102675. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  102676. /**
  102677. * Fired when a rotation sphere is dragged
  102678. */
  102679. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  102680. /**
  102681. * Fired when a rotation sphere drag is ended
  102682. */
  102683. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  102684. /**
  102685. * 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)
  102686. */
  102687. _this.scalePivot = null;
  102688. _this._existingMeshScale = new BABYLON.Vector3();
  102689. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  102690. _this._updateScale = false;
  102691. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  102692. // Create Materials
  102693. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102694. coloredMaterial.disableLighting = true;
  102695. coloredMaterial.emissiveColor = color;
  102696. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102697. hoverColoredMaterial.disableLighting = true;
  102698. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102699. // Build bounding box out of lines
  102700. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102701. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  102702. var lines = [];
  102703. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  102704. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  102705. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  102706. 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));
  102707. 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));
  102708. 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));
  102709. 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));
  102710. 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));
  102711. 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));
  102712. 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));
  102713. 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));
  102714. 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));
  102715. lines.forEach(function (l) {
  102716. l.color = color;
  102717. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  102718. l.isPickable = false;
  102719. _this._lineBoundingBox.addChild(l);
  102720. });
  102721. _this._rootMesh.addChild(_this._lineBoundingBox);
  102722. // Create rotation spheres
  102723. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102724. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  102725. var _loop_1 = function (i_1) {
  102726. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  102727. sphere.rotationQuaternion = new BABYLON.Quaternion();
  102728. sphere.material = coloredMaterial;
  102729. // Drag behavior
  102730. _dragBehavior = new BABYLON.PointerDragBehavior({});
  102731. _dragBehavior.moveAttached = false;
  102732. _dragBehavior.updateDragPlane = false;
  102733. sphere.addBehavior(_dragBehavior);
  102734. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  102735. var totalTurnAmountOfDrag = 0;
  102736. _dragBehavior.onDragStartObservable.add(function (event) {
  102737. startingTurnDirection.copyFrom(sphere.forward);
  102738. totalTurnAmountOfDrag = 0;
  102739. });
  102740. _dragBehavior.onDragObservable.add(function (event) {
  102741. _this.onRotationSphereDragObservable.notifyObservers({});
  102742. if (_this.attachedMesh) {
  102743. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102744. var worldDragDirection = startingTurnDirection;
  102745. // Project the world right on to the drag plane
  102746. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  102747. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  102748. // project drag delta on to the resulting drag axis and rotate based on that
  102749. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  102750. // Make rotation relative to size of mesh.
  102751. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102752. // Rotate based on axis
  102753. if (!_this.attachedMesh.rotationQuaternion) {
  102754. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102755. }
  102756. if (!_this._anchorMesh.rotationQuaternion) {
  102757. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  102758. }
  102759. // Do not allow the object to turn more than a full circle
  102760. totalTurnAmountOfDrag += projectDist;
  102761. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  102762. if (i_1 >= 8) {
  102763. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  102764. }
  102765. else if (i_1 >= 4) {
  102766. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  102767. }
  102768. else {
  102769. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  102770. }
  102771. // Rotate around center of bounding box
  102772. _this._anchorMesh.addChild(_this.attachedMesh);
  102773. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  102774. _this._anchorMesh.removeChild(_this.attachedMesh);
  102775. }
  102776. _this.updateBoundingBox();
  102777. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102778. }
  102779. });
  102780. // Selection/deselection
  102781. _dragBehavior.onDragStartObservable.add(function () {
  102782. _this.onDragStartObservable.notifyObservers({});
  102783. _this._selectNode(sphere);
  102784. });
  102785. _dragBehavior.onDragEndObservable.add(function () {
  102786. _this.onRotationSphereDragEndObservable.notifyObservers({});
  102787. _this._selectNode(null);
  102788. });
  102789. this_1._rotateSpheresParent.addChild(sphere);
  102790. };
  102791. var this_1 = this, _dragBehavior;
  102792. for (var i_1 = 0; i_1 < 12; i_1++) {
  102793. _loop_1(i_1);
  102794. }
  102795. _this._rootMesh.addChild(_this._rotateSpheresParent);
  102796. // Create scale cubes
  102797. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102798. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  102799. for (var i = 0; i < 2; i++) {
  102800. for (var j = 0; j < 2; j++) {
  102801. var _loop_2 = function () {
  102802. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  102803. box.material = coloredMaterial;
  102804. // Dragging logic
  102805. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  102806. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102807. _dragBehavior.moveAttached = false;
  102808. box.addBehavior(_dragBehavior);
  102809. _dragBehavior.onDragObservable.add(function (event) {
  102810. _this.onScaleBoxDragObservable.notifyObservers({});
  102811. if (_this.attachedMesh) {
  102812. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102813. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102814. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  102815. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  102816. _this.updateBoundingBox();
  102817. if (_this.scalePivot) {
  102818. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  102819. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  102820. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  102821. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102822. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102823. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  102824. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102825. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  102826. }
  102827. else {
  102828. // Scale from the position of the opposite corner
  102829. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  102830. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102831. }
  102832. _this._anchorMesh.addChild(_this.attachedMesh);
  102833. _this._anchorMesh.scaling.addInPlace(deltaScale);
  102834. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  102835. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  102836. }
  102837. _this._anchorMesh.removeChild(_this.attachedMesh);
  102838. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102839. }
  102840. });
  102841. // Selection/deselection
  102842. _dragBehavior.onDragStartObservable.add(function () {
  102843. _this.onDragStartObservable.notifyObservers({});
  102844. _this._selectNode(box);
  102845. });
  102846. _dragBehavior.onDragEndObservable.add(function () {
  102847. _this.onScaleBoxDragEndObservable.notifyObservers({});
  102848. _this._selectNode(null);
  102849. });
  102850. this_2._scaleBoxesParent.addChild(box);
  102851. };
  102852. var this_2 = this, _dragBehavior;
  102853. for (var k = 0; k < 2; k++) {
  102854. _loop_2();
  102855. }
  102856. }
  102857. }
  102858. _this._rootMesh.addChild(_this._scaleBoxesParent);
  102859. // Hover color change
  102860. var pointerIds = new Array();
  102861. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102862. if (!pointerIds[pointerInfo.event.pointerId]) {
  102863. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  102864. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  102865. pointerIds[pointerInfo.event.pointerId] = mesh;
  102866. mesh.material = hoverColoredMaterial;
  102867. }
  102868. });
  102869. }
  102870. else {
  102871. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  102872. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  102873. delete pointerIds[pointerInfo.event.pointerId];
  102874. }
  102875. }
  102876. });
  102877. // Update bounding box positions
  102878. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  102879. // Only update the bouding box if scaling has changed
  102880. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  102881. _this.updateBoundingBox();
  102882. }
  102883. });
  102884. _this.updateBoundingBox();
  102885. return _this;
  102886. }
  102887. /** @hidden */
  102888. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  102889. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  102890. // Save old pivot and set pivot to 0,0,0
  102891. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  102892. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  102893. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  102894. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  102895. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102896. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102897. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102898. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  102899. }
  102900. }
  102901. BoundingBoxGizmo._PivotCached++;
  102902. };
  102903. /** @hidden */
  102904. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  102905. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  102906. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  102907. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102908. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102909. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102910. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  102911. }
  102912. this._PivotCached--;
  102913. };
  102914. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  102915. if (value) {
  102916. // Reset anchor mesh to match attached mesh's scale
  102917. // This is needed to avoid invalid box/sphere position on first drag
  102918. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  102919. this._anchorMesh.addChild(value);
  102920. this._anchorMesh.removeChild(value);
  102921. BoundingBoxGizmo._RestorePivotPoint(value);
  102922. this.updateBoundingBox();
  102923. }
  102924. };
  102925. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  102926. this._rotateSpheresParent.getChildMeshes()
  102927. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  102928. m.isVisible = (!selectedMesh || m == selectedMesh);
  102929. });
  102930. };
  102931. /**
  102932. * Updates the bounding box information for the Gizmo
  102933. */
  102934. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  102935. if (this.attachedMesh) {
  102936. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  102937. this._update();
  102938. // Rotate based on axis
  102939. if (!this.attachedMesh.rotationQuaternion) {
  102940. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  102941. }
  102942. if (!this._anchorMesh.rotationQuaternion) {
  102943. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  102944. }
  102945. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  102946. // Store original position and reset mesh to origin before computing the bounding box
  102947. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  102948. this._tmpVector.copyFrom(this.attachedMesh.position);
  102949. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  102950. this.attachedMesh.position.set(0, 0, 0);
  102951. // Update bounding dimensions/positions
  102952. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  102953. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  102954. // Update gizmo to match bounding box scaling and rotation
  102955. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  102956. 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);
  102957. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  102958. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  102959. this._lineBoundingBox.computeWorldMatrix();
  102960. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  102961. // restore position/rotation values
  102962. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  102963. this.attachedMesh.position.copyFrom(this._tmpVector);
  102964. }
  102965. // Update rotation sphere locations
  102966. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  102967. for (var i = 0; i < 3; i++) {
  102968. for (var j = 0; j < 2; j++) {
  102969. for (var k = 0; k < 2; k++) {
  102970. var index = ((i * 4) + (j * 2)) + k;
  102971. if (i == 0) {
  102972. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  102973. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102974. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102975. }
  102976. if (i == 1) {
  102977. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  102978. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102979. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102980. }
  102981. if (i == 2) {
  102982. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  102983. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102984. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102985. }
  102986. if (this.fixedDragMeshScreenSize) {
  102987. this._rootMesh.computeWorldMatrix();
  102988. this._rotateSpheresParent.computeWorldMatrix();
  102989. rotateSpheres[index].computeWorldMatrix();
  102990. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  102991. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  102992. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  102993. }
  102994. else {
  102995. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  102996. }
  102997. }
  102998. }
  102999. }
  103000. // Update scale box locations
  103001. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103002. for (var i = 0; i < 2; i++) {
  103003. for (var j = 0; j < 2; j++) {
  103004. for (var k = 0; k < 2; k++) {
  103005. var index = ((i * 4) + (j * 2)) + k;
  103006. if (scaleBoxes[index]) {
  103007. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103008. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103009. if (this.fixedDragMeshScreenSize) {
  103010. this._rootMesh.computeWorldMatrix();
  103011. this._scaleBoxesParent.computeWorldMatrix();
  103012. scaleBoxes[index].computeWorldMatrix();
  103013. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103014. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103015. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103016. }
  103017. else {
  103018. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103019. }
  103020. }
  103021. }
  103022. }
  103023. }
  103024. if (this.attachedMesh) {
  103025. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103026. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103027. }
  103028. };
  103029. /**
  103030. * Enables rotation on the specified axis and disables rotation on the others
  103031. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103032. */
  103033. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103034. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103035. if (i < 4) {
  103036. m.setEnabled(axis.indexOf("x") != -1);
  103037. }
  103038. else if (i < 8) {
  103039. m.setEnabled(axis.indexOf("y") != -1);
  103040. }
  103041. else {
  103042. m.setEnabled(axis.indexOf("z") != -1);
  103043. }
  103044. });
  103045. };
  103046. /**
  103047. * Disposes of the gizmo
  103048. */
  103049. BoundingBoxGizmo.prototype.dispose = function () {
  103050. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103051. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103052. this._lineBoundingBox.dispose();
  103053. this._rotateSpheresParent.dispose();
  103054. this._scaleBoxesParent.dispose();
  103055. _super.prototype.dispose.call(this);
  103056. };
  103057. /**
  103058. * 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)
  103059. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103060. * @returns the bounding box mesh with the passed in mesh as a child
  103061. */
  103062. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103063. var makeNotPickable = function (root) {
  103064. root.isPickable = false;
  103065. root.getChildMeshes().forEach(function (c) {
  103066. makeNotPickable(c);
  103067. });
  103068. };
  103069. makeNotPickable(mesh);
  103070. // Reset position to get boudning box from origin with no rotation
  103071. if (!mesh.rotationQuaternion) {
  103072. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103073. }
  103074. var oldPos = mesh.position.clone();
  103075. var oldRot = mesh.rotationQuaternion.clone();
  103076. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103077. mesh.position.set(0, 0, 0);
  103078. // Update bounding dimensions/positions
  103079. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103080. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103081. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103082. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103083. // Restore original positions
  103084. mesh.addChild(box);
  103085. mesh.rotationQuaternion.copyFrom(oldRot);
  103086. mesh.position.copyFrom(oldPos);
  103087. // Reverse parenting
  103088. mesh.removeChild(box);
  103089. box.addChild(mesh);
  103090. box.visibility = 0;
  103091. return box;
  103092. };
  103093. /**
  103094. * CustomMeshes are not supported by this gizmo
  103095. * @param mesh The mesh to replace the default mesh of the gizmo
  103096. */
  103097. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103098. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103099. };
  103100. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103101. // store/remove pivot point should only be applied during their outermost calls
  103102. BoundingBoxGizmo._PivotCached = 0;
  103103. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103104. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103105. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103106. return BoundingBoxGizmo;
  103107. }(BABYLON.Gizmo));
  103108. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103109. })(BABYLON || (BABYLON = {}));
  103110. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  103111. var BABYLON;
  103112. (function (BABYLON) {
  103113. /**
  103114. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103115. */
  103116. var GizmoManager = /** @class */ (function () {
  103117. /**
  103118. * Instatiates a gizmo manager
  103119. * @param scene the scene to overlay the gizmos on top of
  103120. */
  103121. function GizmoManager(scene) {
  103122. var _this = this;
  103123. this.scene = scene;
  103124. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103125. this._pointerObserver = null;
  103126. this._attachedMesh = null;
  103127. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103128. /**
  103129. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103130. */
  103131. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103132. /**
  103133. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103134. */
  103135. this.attachableMeshes = null;
  103136. /**
  103137. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103138. */
  103139. this.usePointerToAttachGizmos = true;
  103140. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103141. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103142. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103143. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103144. // Instatiate/dispose gizmos based on pointer actions
  103145. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103146. if (!_this.usePointerToAttachGizmos) {
  103147. return;
  103148. }
  103149. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103150. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103151. var node = pointerInfo.pickInfo.pickedMesh;
  103152. if (_this.attachableMeshes == null) {
  103153. // Attach to the most parent node
  103154. while (node && node.parent != null) {
  103155. node = node.parent;
  103156. }
  103157. }
  103158. else {
  103159. // Attach to the parent node that is an attachableMesh
  103160. var found = false;
  103161. _this.attachableMeshes.forEach(function (mesh) {
  103162. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103163. node = mesh;
  103164. found = true;
  103165. }
  103166. });
  103167. if (!found) {
  103168. node = null;
  103169. }
  103170. }
  103171. if (node instanceof BABYLON.AbstractMesh) {
  103172. if (_this._attachedMesh != node) {
  103173. _this.attachToMesh(node);
  103174. }
  103175. }
  103176. else {
  103177. _this.attachToMesh(null);
  103178. }
  103179. }
  103180. else {
  103181. _this.attachToMesh(null);
  103182. }
  103183. }
  103184. });
  103185. }
  103186. /**
  103187. * Attaches a set of gizmos to the specified mesh
  103188. * @param mesh The mesh the gizmo's should be attached to
  103189. */
  103190. GizmoManager.prototype.attachToMesh = function (mesh) {
  103191. if (this._attachedMesh) {
  103192. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103193. }
  103194. this._attachedMesh = mesh;
  103195. for (var key in this.gizmos) {
  103196. var gizmo = (this.gizmos[key]);
  103197. if (gizmo && this._gizmosEnabled[key]) {
  103198. gizmo.attachedMesh = mesh;
  103199. }
  103200. }
  103201. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103202. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103203. }
  103204. };
  103205. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103206. get: function () {
  103207. return this._gizmosEnabled.positionGizmo;
  103208. },
  103209. /**
  103210. * If the position gizmo is enabled
  103211. */
  103212. set: function (value) {
  103213. if (value) {
  103214. if (!this.gizmos.positionGizmo) {
  103215. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103216. }
  103217. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103218. }
  103219. else if (this.gizmos.positionGizmo) {
  103220. this.gizmos.positionGizmo.attachedMesh = null;
  103221. }
  103222. this._gizmosEnabled.positionGizmo = value;
  103223. },
  103224. enumerable: true,
  103225. configurable: true
  103226. });
  103227. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103228. get: function () {
  103229. return this._gizmosEnabled.rotationGizmo;
  103230. },
  103231. /**
  103232. * If the rotation gizmo is enabled
  103233. */
  103234. set: function (value) {
  103235. if (value) {
  103236. if (!this.gizmos.rotationGizmo) {
  103237. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103238. }
  103239. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103240. }
  103241. else if (this.gizmos.rotationGizmo) {
  103242. this.gizmos.rotationGizmo.attachedMesh = null;
  103243. }
  103244. this._gizmosEnabled.rotationGizmo = value;
  103245. },
  103246. enumerable: true,
  103247. configurable: true
  103248. });
  103249. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103250. get: function () {
  103251. return this._gizmosEnabled.scaleGizmo;
  103252. },
  103253. /**
  103254. * If the scale gizmo is enabled
  103255. */
  103256. set: function (value) {
  103257. if (value) {
  103258. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103259. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103260. }
  103261. else if (this.gizmos.scaleGizmo) {
  103262. this.gizmos.scaleGizmo.attachedMesh = null;
  103263. }
  103264. this._gizmosEnabled.scaleGizmo = value;
  103265. },
  103266. enumerable: true,
  103267. configurable: true
  103268. });
  103269. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103270. get: function () {
  103271. return this._gizmosEnabled.boundingBoxGizmo;
  103272. },
  103273. /**
  103274. * If the boundingBox gizmo is enabled
  103275. */
  103276. set: function (value) {
  103277. if (value) {
  103278. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103279. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103280. if (this._attachedMesh) {
  103281. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103282. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103283. }
  103284. }
  103285. else if (this.gizmos.boundingBoxGizmo) {
  103286. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103287. }
  103288. this._gizmosEnabled.boundingBoxGizmo = value;
  103289. },
  103290. enumerable: true,
  103291. configurable: true
  103292. });
  103293. /**
  103294. * Disposes of the gizmo manager
  103295. */
  103296. GizmoManager.prototype.dispose = function () {
  103297. this.scene.onPointerObservable.remove(this._pointerObserver);
  103298. for (var key in this.gizmos) {
  103299. var gizmo = (this.gizmos[key]);
  103300. if (gizmo) {
  103301. gizmo.dispose();
  103302. }
  103303. }
  103304. this._defaultKeepDepthUtilityLayer.dispose();
  103305. this._defaultUtilityLayer.dispose();
  103306. this.boundingBoxDragBehavior.detach();
  103307. };
  103308. return GizmoManager;
  103309. }());
  103310. BABYLON.GizmoManager = GizmoManager;
  103311. })(BABYLON || (BABYLON = {}));
  103312. //# sourceMappingURL=babylon.gizmoManager.js.map
  103313. var BABYLON;
  103314. (function (BABYLON) {
  103315. /**
  103316. * Defines a target to use with MorphTargetManager
  103317. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103318. */
  103319. var MorphTarget = /** @class */ (function () {
  103320. /**
  103321. * Creates a new MorphTarget
  103322. * @param name defines the name of the target
  103323. * @param influence defines the influence to use
  103324. */
  103325. function MorphTarget(
  103326. /** defines the name of the target */
  103327. name, influence, scene) {
  103328. if (influence === void 0) { influence = 0; }
  103329. if (scene === void 0) { scene = null; }
  103330. this.name = name;
  103331. /**
  103332. * Gets or sets the list of animations
  103333. */
  103334. this.animations = new Array();
  103335. this._positions = null;
  103336. this._normals = null;
  103337. this._tangents = null;
  103338. /**
  103339. * Observable raised when the influence changes
  103340. */
  103341. this.onInfluenceChanged = new BABYLON.Observable();
  103342. /** @hidden */
  103343. this._onDataLayoutChanged = new BABYLON.Observable();
  103344. this._animationPropertiesOverride = null;
  103345. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103346. this.influence = influence;
  103347. }
  103348. Object.defineProperty(MorphTarget.prototype, "influence", {
  103349. /**
  103350. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103351. */
  103352. get: function () {
  103353. return this._influence;
  103354. },
  103355. set: function (influence) {
  103356. if (this._influence === influence) {
  103357. return;
  103358. }
  103359. var previous = this._influence;
  103360. this._influence = influence;
  103361. if (this.onInfluenceChanged.hasObservers) {
  103362. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103363. }
  103364. },
  103365. enumerable: true,
  103366. configurable: true
  103367. });
  103368. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103369. /**
  103370. * Gets or sets the animation properties override
  103371. */
  103372. get: function () {
  103373. if (!this._animationPropertiesOverride && this._scene) {
  103374. return this._scene.animationPropertiesOverride;
  103375. }
  103376. return this._animationPropertiesOverride;
  103377. },
  103378. set: function (value) {
  103379. this._animationPropertiesOverride = value;
  103380. },
  103381. enumerable: true,
  103382. configurable: true
  103383. });
  103384. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103385. /**
  103386. * Gets a boolean defining if the target contains position data
  103387. */
  103388. get: function () {
  103389. return !!this._positions;
  103390. },
  103391. enumerable: true,
  103392. configurable: true
  103393. });
  103394. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  103395. /**
  103396. * Gets a boolean defining if the target contains normal data
  103397. */
  103398. get: function () {
  103399. return !!this._normals;
  103400. },
  103401. enumerable: true,
  103402. configurable: true
  103403. });
  103404. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  103405. /**
  103406. * Gets a boolean defining if the target contains tangent data
  103407. */
  103408. get: function () {
  103409. return !!this._tangents;
  103410. },
  103411. enumerable: true,
  103412. configurable: true
  103413. });
  103414. /**
  103415. * Affects position data to this target
  103416. * @param data defines the position data to use
  103417. */
  103418. MorphTarget.prototype.setPositions = function (data) {
  103419. var hadPositions = this.hasPositions;
  103420. this._positions = data;
  103421. if (hadPositions !== this.hasPositions) {
  103422. this._onDataLayoutChanged.notifyObservers(undefined);
  103423. }
  103424. };
  103425. /**
  103426. * Gets the position data stored in this target
  103427. * @returns a FloatArray containing the position data (or null if not present)
  103428. */
  103429. MorphTarget.prototype.getPositions = function () {
  103430. return this._positions;
  103431. };
  103432. /**
  103433. * Affects normal data to this target
  103434. * @param data defines the normal data to use
  103435. */
  103436. MorphTarget.prototype.setNormals = function (data) {
  103437. var hadNormals = this.hasNormals;
  103438. this._normals = data;
  103439. if (hadNormals !== this.hasNormals) {
  103440. this._onDataLayoutChanged.notifyObservers(undefined);
  103441. }
  103442. };
  103443. /**
  103444. * Gets the normal data stored in this target
  103445. * @returns a FloatArray containing the normal data (or null if not present)
  103446. */
  103447. MorphTarget.prototype.getNormals = function () {
  103448. return this._normals;
  103449. };
  103450. /**
  103451. * Affects tangent data to this target
  103452. * @param data defines the tangent data to use
  103453. */
  103454. MorphTarget.prototype.setTangents = function (data) {
  103455. var hadTangents = this.hasTangents;
  103456. this._tangents = data;
  103457. if (hadTangents !== this.hasTangents) {
  103458. this._onDataLayoutChanged.notifyObservers(undefined);
  103459. }
  103460. };
  103461. /**
  103462. * Gets the tangent data stored in this target
  103463. * @returns a FloatArray containing the tangent data (or null if not present)
  103464. */
  103465. MorphTarget.prototype.getTangents = function () {
  103466. return this._tangents;
  103467. };
  103468. /**
  103469. * Serializes the current target into a Serialization object
  103470. * @returns the serialized object
  103471. */
  103472. MorphTarget.prototype.serialize = function () {
  103473. var serializationObject = {};
  103474. serializationObject.name = this.name;
  103475. serializationObject.influence = this.influence;
  103476. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  103477. if (this.hasNormals) {
  103478. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  103479. }
  103480. if (this.hasTangents) {
  103481. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  103482. }
  103483. // Animations
  103484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  103485. return serializationObject;
  103486. };
  103487. // Statics
  103488. /**
  103489. * Creates a new target from serialized data
  103490. * @param serializationObject defines the serialized data to use
  103491. * @returns a new MorphTarget
  103492. */
  103493. MorphTarget.Parse = function (serializationObject) {
  103494. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  103495. result.setPositions(serializationObject.positions);
  103496. if (serializationObject.normals) {
  103497. result.setNormals(serializationObject.normals);
  103498. }
  103499. if (serializationObject.tangents) {
  103500. result.setTangents(serializationObject.tangents);
  103501. }
  103502. // Animations
  103503. if (serializationObject.animations) {
  103504. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  103505. var parsedAnimation = serializationObject.animations[animationIndex];
  103506. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  103507. }
  103508. }
  103509. return result;
  103510. };
  103511. /**
  103512. * Creates a MorphTarget from mesh data
  103513. * @param mesh defines the source mesh
  103514. * @param name defines the name to use for the new target
  103515. * @param influence defines the influence to attach to the target
  103516. * @returns a new MorphTarget
  103517. */
  103518. MorphTarget.FromMesh = function (mesh, name, influence) {
  103519. if (!name) {
  103520. name = mesh.name;
  103521. }
  103522. var result = new MorphTarget(name, influence, mesh.getScene());
  103523. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  103524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103525. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  103526. }
  103527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  103528. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  103529. }
  103530. return result;
  103531. };
  103532. return MorphTarget;
  103533. }());
  103534. BABYLON.MorphTarget = MorphTarget;
  103535. })(BABYLON || (BABYLON = {}));
  103536. //# sourceMappingURL=babylon.morphTarget.js.map
  103537. var BABYLON;
  103538. (function (BABYLON) {
  103539. /**
  103540. * This class is used to deform meshes using morphing between different targets
  103541. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103542. */
  103543. var MorphTargetManager = /** @class */ (function () {
  103544. /**
  103545. * Creates a new MorphTargetManager
  103546. * @param scene defines the current scene
  103547. */
  103548. function MorphTargetManager(scene) {
  103549. if (scene === void 0) { scene = null; }
  103550. this._targets = new Array();
  103551. this._targetInfluenceChangedObservers = new Array();
  103552. this._targetDataLayoutChangedObservers = new Array();
  103553. this._activeTargets = new BABYLON.SmartArray(16);
  103554. this._supportsNormals = false;
  103555. this._supportsTangents = false;
  103556. this._vertexCount = 0;
  103557. this._uniqueId = 0;
  103558. this._tempInfluences = new Array();
  103559. if (!scene) {
  103560. scene = BABYLON.Engine.LastCreatedScene;
  103561. }
  103562. this._scene = scene;
  103563. if (this._scene) {
  103564. this._scene.morphTargetManagers.push(this);
  103565. this._uniqueId = this._scene.getUniqueId();
  103566. }
  103567. }
  103568. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  103569. /**
  103570. * Gets the unique ID of this manager
  103571. */
  103572. get: function () {
  103573. return this._uniqueId;
  103574. },
  103575. enumerable: true,
  103576. configurable: true
  103577. });
  103578. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  103579. /**
  103580. * Gets the number of vertices handled by this manager
  103581. */
  103582. get: function () {
  103583. return this._vertexCount;
  103584. },
  103585. enumerable: true,
  103586. configurable: true
  103587. });
  103588. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  103589. /**
  103590. * Gets a boolean indicating if this manager supports morphing of normals
  103591. */
  103592. get: function () {
  103593. return this._supportsNormals;
  103594. },
  103595. enumerable: true,
  103596. configurable: true
  103597. });
  103598. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  103599. /**
  103600. * Gets a boolean indicating if this manager supports morphing of tangents
  103601. */
  103602. get: function () {
  103603. return this._supportsTangents;
  103604. },
  103605. enumerable: true,
  103606. configurable: true
  103607. });
  103608. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  103609. /**
  103610. * Gets the number of targets stored in this manager
  103611. */
  103612. get: function () {
  103613. return this._targets.length;
  103614. },
  103615. enumerable: true,
  103616. configurable: true
  103617. });
  103618. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  103619. /**
  103620. * Gets the number of influencers (ie. the number of targets with influences > 0)
  103621. */
  103622. get: function () {
  103623. return this._activeTargets.length;
  103624. },
  103625. enumerable: true,
  103626. configurable: true
  103627. });
  103628. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  103629. /**
  103630. * Gets the list of influences (one per target)
  103631. */
  103632. get: function () {
  103633. return this._influences;
  103634. },
  103635. enumerable: true,
  103636. configurable: true
  103637. });
  103638. /**
  103639. * Gets the active target at specified index. An active target is a target with an influence > 0
  103640. * @param index defines the index to check
  103641. * @returns the requested target
  103642. */
  103643. MorphTargetManager.prototype.getActiveTarget = function (index) {
  103644. return this._activeTargets.data[index];
  103645. };
  103646. /**
  103647. * Gets the target at specified index
  103648. * @param index defines the index to check
  103649. * @returns the requested target
  103650. */
  103651. MorphTargetManager.prototype.getTarget = function (index) {
  103652. return this._targets[index];
  103653. };
  103654. /**
  103655. * Add a new target to this manager
  103656. * @param target defines the target to add
  103657. */
  103658. MorphTargetManager.prototype.addTarget = function (target) {
  103659. var _this = this;
  103660. this._targets.push(target);
  103661. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  103662. _this._syncActiveTargets(needUpdate);
  103663. }));
  103664. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  103665. _this._syncActiveTargets(true);
  103666. }));
  103667. this._syncActiveTargets(true);
  103668. };
  103669. /**
  103670. * Removes a target from the manager
  103671. * @param target defines the target to remove
  103672. */
  103673. MorphTargetManager.prototype.removeTarget = function (target) {
  103674. var index = this._targets.indexOf(target);
  103675. if (index >= 0) {
  103676. this._targets.splice(index, 1);
  103677. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  103678. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  103679. this._syncActiveTargets(true);
  103680. }
  103681. };
  103682. /**
  103683. * Serializes the current manager into a Serialization object
  103684. * @returns the serialized object
  103685. */
  103686. MorphTargetManager.prototype.serialize = function () {
  103687. var serializationObject = {};
  103688. serializationObject.id = this.uniqueId;
  103689. serializationObject.targets = [];
  103690. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103691. var target = _a[_i];
  103692. serializationObject.targets.push(target.serialize());
  103693. }
  103694. return serializationObject;
  103695. };
  103696. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  103697. var influenceCount = 0;
  103698. this._activeTargets.reset();
  103699. this._supportsNormals = true;
  103700. this._supportsTangents = true;
  103701. this._vertexCount = 0;
  103702. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103703. var target = _a[_i];
  103704. if (target.influence === 0) {
  103705. continue;
  103706. }
  103707. this._activeTargets.push(target);
  103708. this._tempInfluences[influenceCount++] = target.influence;
  103709. this._supportsNormals = this._supportsNormals && target.hasNormals;
  103710. this._supportsTangents = this._supportsTangents && target.hasTangents;
  103711. var positions = target.getPositions();
  103712. if (positions) {
  103713. var vertexCount = positions.length / 3;
  103714. if (this._vertexCount === 0) {
  103715. this._vertexCount = vertexCount;
  103716. }
  103717. else if (this._vertexCount !== vertexCount) {
  103718. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  103719. return;
  103720. }
  103721. }
  103722. }
  103723. if (!this._influences || this._influences.length !== influenceCount) {
  103724. this._influences = new Float32Array(influenceCount);
  103725. }
  103726. for (var index = 0; index < influenceCount; index++) {
  103727. this._influences[index] = this._tempInfluences[index];
  103728. }
  103729. if (needUpdate) {
  103730. this.synchronize();
  103731. }
  103732. };
  103733. /**
  103734. * Syncrhonize the targets with all the meshes using this morph target manager
  103735. */
  103736. MorphTargetManager.prototype.synchronize = function () {
  103737. if (!this._scene) {
  103738. return;
  103739. }
  103740. // Flag meshes as dirty to resync with the active targets
  103741. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  103742. var mesh = _a[_i];
  103743. if (mesh.morphTargetManager === this) {
  103744. mesh._syncGeometryWithMorphTargetManager();
  103745. }
  103746. }
  103747. };
  103748. // Statics
  103749. /**
  103750. * Creates a new MorphTargetManager from serialized data
  103751. * @param serializationObject defines the serialized data
  103752. * @param scene defines the hosting scene
  103753. * @returns the new MorphTargetManager
  103754. */
  103755. MorphTargetManager.Parse = function (serializationObject, scene) {
  103756. var result = new MorphTargetManager(scene);
  103757. result._uniqueId = serializationObject.id;
  103758. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  103759. var targetData = _a[_i];
  103760. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  103761. }
  103762. return result;
  103763. };
  103764. return MorphTargetManager;
  103765. }());
  103766. BABYLON.MorphTargetManager = MorphTargetManager;
  103767. })(BABYLON || (BABYLON = {}));
  103768. //# sourceMappingURL=babylon.morphTargetManager.js.map
  103769. var BABYLON;
  103770. (function (BABYLON) {
  103771. /**
  103772. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  103773. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103774. */
  103775. var Octree = /** @class */ (function () {
  103776. /**
  103777. * Creates a octree
  103778. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103779. * @param creationFunc function to be used to instatiate the octree
  103780. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  103781. * @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.)
  103782. */
  103783. function Octree(creationFunc, maxBlockCapacity,
  103784. /** 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.) */
  103785. maxDepth) {
  103786. if (maxDepth === void 0) { maxDepth = 2; }
  103787. this.maxDepth = maxDepth;
  103788. /**
  103789. * Content stored in the octree
  103790. */
  103791. this.dynamicContent = new Array();
  103792. this._maxBlockCapacity = maxBlockCapacity || 64;
  103793. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  103794. this._creationFunc = creationFunc;
  103795. }
  103796. // Methods
  103797. /**
  103798. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  103799. * @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);
  103800. * @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);
  103801. * @param entries meshes to be added to the octree blocks
  103802. */
  103803. Octree.prototype.update = function (worldMin, worldMax, entries) {
  103804. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  103805. };
  103806. /**
  103807. * Adds a mesh to the octree
  103808. * @param entry Mesh to add to the octree
  103809. */
  103810. Octree.prototype.addMesh = function (entry) {
  103811. for (var index = 0; index < this.blocks.length; index++) {
  103812. var block = this.blocks[index];
  103813. block.addEntry(entry);
  103814. }
  103815. };
  103816. /**
  103817. * Selects an array of meshes within the frustum
  103818. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  103819. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  103820. * @returns array of meshes within the frustum
  103821. */
  103822. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  103823. this._selectionContent.reset();
  103824. for (var index = 0; index < this.blocks.length; index++) {
  103825. var block = this.blocks[index];
  103826. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  103827. }
  103828. if (allowDuplicate) {
  103829. this._selectionContent.concat(this.dynamicContent);
  103830. }
  103831. else {
  103832. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103833. }
  103834. return this._selectionContent;
  103835. };
  103836. /**
  103837. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  103838. * @param sphereCenter defines the bounding sphere center
  103839. * @param sphereRadius defines the bounding sphere radius
  103840. * @param allowDuplicate defines if the selection array can contains duplicated entries
  103841. * @returns an array of objects that intersect the sphere
  103842. */
  103843. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  103844. this._selectionContent.reset();
  103845. for (var index = 0; index < this.blocks.length; index++) {
  103846. var block = this.blocks[index];
  103847. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  103848. }
  103849. if (allowDuplicate) {
  103850. this._selectionContent.concat(this.dynamicContent);
  103851. }
  103852. else {
  103853. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103854. }
  103855. return this._selectionContent;
  103856. };
  103857. /**
  103858. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  103859. * @param ray defines the ray to test with
  103860. * @returns array of intersected objects
  103861. */
  103862. Octree.prototype.intersectsRay = function (ray) {
  103863. this._selectionContent.reset();
  103864. for (var index = 0; index < this.blocks.length; index++) {
  103865. var block = this.blocks[index];
  103866. block.intersectsRay(ray, this._selectionContent);
  103867. }
  103868. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103869. return this._selectionContent;
  103870. };
  103871. /**
  103872. * @hidden
  103873. */
  103874. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  103875. target.blocks = new Array();
  103876. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103877. // Segmenting space
  103878. for (var x = 0; x < 2; x++) {
  103879. for (var y = 0; y < 2; y++) {
  103880. for (var z = 0; z < 2; z++) {
  103881. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  103882. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  103883. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  103884. block.addEntries(entries);
  103885. target.blocks.push(block);
  103886. }
  103887. }
  103888. }
  103889. };
  103890. /**
  103891. * Adds a mesh into the octree block if it intersects the block
  103892. */
  103893. Octree.CreationFuncForMeshes = function (entry, block) {
  103894. var boundingInfo = entry.getBoundingInfo();
  103895. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103896. block.entries.push(entry);
  103897. }
  103898. };
  103899. /**
  103900. * Adds a submesh into the octree block if it intersects the block
  103901. */
  103902. Octree.CreationFuncForSubMeshes = function (entry, block) {
  103903. var boundingInfo = entry.getBoundingInfo();
  103904. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103905. block.entries.push(entry);
  103906. }
  103907. };
  103908. return Octree;
  103909. }());
  103910. BABYLON.Octree = Octree;
  103911. })(BABYLON || (BABYLON = {}));
  103912. //# sourceMappingURL=babylon.octree.js.map
  103913. var BABYLON;
  103914. (function (BABYLON) {
  103915. /**
  103916. * Class used to store a cell in an octree
  103917. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103918. */
  103919. var OctreeBlock = /** @class */ (function () {
  103920. /**
  103921. * Creates a new block
  103922. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  103923. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  103924. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  103925. * @param depth defines the current depth of this block in the octree
  103926. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  103927. * @param creationFunc defines a callback to call when an element is added to the block
  103928. */
  103929. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  103930. /**
  103931. * Gets the content of the current block
  103932. */
  103933. this.entries = new Array();
  103934. this._boundingVectors = new Array();
  103935. this._capacity = capacity;
  103936. this._depth = depth;
  103937. this._maxDepth = maxDepth;
  103938. this._creationFunc = creationFunc;
  103939. this._minPoint = minPoint;
  103940. this._maxPoint = maxPoint;
  103941. this._boundingVectors.push(minPoint.clone());
  103942. this._boundingVectors.push(maxPoint.clone());
  103943. this._boundingVectors.push(minPoint.clone());
  103944. this._boundingVectors[2].x = maxPoint.x;
  103945. this._boundingVectors.push(minPoint.clone());
  103946. this._boundingVectors[3].y = maxPoint.y;
  103947. this._boundingVectors.push(minPoint.clone());
  103948. this._boundingVectors[4].z = maxPoint.z;
  103949. this._boundingVectors.push(maxPoint.clone());
  103950. this._boundingVectors[5].z = minPoint.z;
  103951. this._boundingVectors.push(maxPoint.clone());
  103952. this._boundingVectors[6].x = minPoint.x;
  103953. this._boundingVectors.push(maxPoint.clone());
  103954. this._boundingVectors[7].y = minPoint.y;
  103955. }
  103956. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  103957. // Property
  103958. /**
  103959. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  103960. */
  103961. get: function () {
  103962. return this._capacity;
  103963. },
  103964. enumerable: true,
  103965. configurable: true
  103966. });
  103967. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  103968. /**
  103969. * Gets the minimum vector (in world space) of the block's bounding box
  103970. */
  103971. get: function () {
  103972. return this._minPoint;
  103973. },
  103974. enumerable: true,
  103975. configurable: true
  103976. });
  103977. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  103978. /**
  103979. * Gets the maximum vector (in world space) of the block's bounding box
  103980. */
  103981. get: function () {
  103982. return this._maxPoint;
  103983. },
  103984. enumerable: true,
  103985. configurable: true
  103986. });
  103987. // Methods
  103988. /**
  103989. * Add a new element to this block
  103990. * @param entry defines the element to add
  103991. */
  103992. OctreeBlock.prototype.addEntry = function (entry) {
  103993. if (this.blocks) {
  103994. for (var index = 0; index < this.blocks.length; index++) {
  103995. var block = this.blocks[index];
  103996. block.addEntry(entry);
  103997. }
  103998. return;
  103999. }
  104000. this._creationFunc(entry, this);
  104001. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104002. this.createInnerBlocks();
  104003. }
  104004. };
  104005. /**
  104006. * Add an array of elements to this block
  104007. * @param entries defines the array of elements to add
  104008. */
  104009. OctreeBlock.prototype.addEntries = function (entries) {
  104010. for (var index = 0; index < entries.length; index++) {
  104011. var mesh = entries[index];
  104012. this.addEntry(mesh);
  104013. }
  104014. };
  104015. /**
  104016. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104017. * @param frustumPlanes defines the frustum planes to test
  104018. * @param selection defines the array to store current content if selection is positive
  104019. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104020. */
  104021. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104022. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104023. if (this.blocks) {
  104024. for (var index = 0; index < this.blocks.length; index++) {
  104025. var block = this.blocks[index];
  104026. block.select(frustumPlanes, selection, allowDuplicate);
  104027. }
  104028. return;
  104029. }
  104030. if (allowDuplicate) {
  104031. selection.concat(this.entries);
  104032. }
  104033. else {
  104034. selection.concatWithNoDuplicate(this.entries);
  104035. }
  104036. }
  104037. };
  104038. /**
  104039. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104040. * @param sphereCenter defines the bounding sphere center
  104041. * @param sphereRadius defines the bounding sphere radius
  104042. * @param selection defines the array to store current content if selection is positive
  104043. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104044. */
  104045. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104046. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104047. if (this.blocks) {
  104048. for (var index = 0; index < this.blocks.length; index++) {
  104049. var block = this.blocks[index];
  104050. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104051. }
  104052. return;
  104053. }
  104054. if (allowDuplicate) {
  104055. selection.concat(this.entries);
  104056. }
  104057. else {
  104058. selection.concatWithNoDuplicate(this.entries);
  104059. }
  104060. }
  104061. };
  104062. /**
  104063. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104064. * @param ray defines the ray to test with
  104065. * @param selection defines the array to store current content if selection is positive
  104066. */
  104067. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104068. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104069. if (this.blocks) {
  104070. for (var index = 0; index < this.blocks.length; index++) {
  104071. var block = this.blocks[index];
  104072. block.intersectsRay(ray, selection);
  104073. }
  104074. return;
  104075. }
  104076. selection.concatWithNoDuplicate(this.entries);
  104077. }
  104078. };
  104079. /**
  104080. * Subdivide the content into child blocks (this block will then be empty)
  104081. */
  104082. OctreeBlock.prototype.createInnerBlocks = function () {
  104083. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104084. };
  104085. return OctreeBlock;
  104086. }());
  104087. BABYLON.OctreeBlock = OctreeBlock;
  104088. })(BABYLON || (BABYLON = {}));
  104089. //# sourceMappingURL=babylon.octreeBlock.js.map
  104090. var BABYLON;
  104091. (function (BABYLON) {
  104092. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104093. if (maxCapacity === void 0) { maxCapacity = 64; }
  104094. if (maxDepth === void 0) { maxDepth = 2; }
  104095. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104096. if (!component) {
  104097. component = new OctreeSceneComponent(this);
  104098. this._addComponent(component);
  104099. }
  104100. if (!this._selectionOctree) {
  104101. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104102. }
  104103. var worldExtends = this.getWorldExtends();
  104104. // Update octree
  104105. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104106. return this._selectionOctree;
  104107. };
  104108. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104109. get: function () {
  104110. return this._selectionOctree;
  104111. },
  104112. enumerable: true,
  104113. configurable: true
  104114. });
  104115. /**
  104116. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104117. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104118. * @param maxCapacity defines the maximum size of each block (64 by default)
  104119. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104120. * @returns the new octree
  104121. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104122. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104123. */
  104124. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104125. if (maxCapacity === void 0) { maxCapacity = 64; }
  104126. if (maxDepth === void 0) { maxDepth = 2; }
  104127. var scene = this.getScene();
  104128. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104129. if (!component) {
  104130. component = new OctreeSceneComponent(scene);
  104131. scene._addComponent(component);
  104132. }
  104133. if (!this._submeshesOctree) {
  104134. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104135. }
  104136. this.computeWorldMatrix(true);
  104137. var boundingInfo = this.getBoundingInfo();
  104138. // Update octree
  104139. var bbox = boundingInfo.boundingBox;
  104140. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104141. return this._submeshesOctree;
  104142. };
  104143. /**
  104144. * Defines the octree scene component responsible to manage any octrees
  104145. * in a given scene.
  104146. */
  104147. var OctreeSceneComponent = /** @class */ (function () {
  104148. /**
  104149. * Creates a new instance of the component for the given scene
  104150. * @param scene Defines the scene to register the component in
  104151. */
  104152. function OctreeSceneComponent(scene) {
  104153. /**
  104154. * The component name helpfull to identify the component in the list of scene components.
  104155. */
  104156. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104157. /**
  104158. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104159. */
  104160. this.checksIsEnabled = true;
  104161. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104162. this.scene = scene;
  104163. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104164. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104165. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104166. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104167. }
  104168. /**
  104169. * Registers the component in a given scene
  104170. */
  104171. OctreeSceneComponent.prototype.register = function () {
  104172. var _this = this;
  104173. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104174. var sceneOctree = _this.scene.selectionOctree;
  104175. if (sceneOctree !== undefined && sceneOctree !== null) {
  104176. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104177. if (index !== -1) {
  104178. sceneOctree.dynamicContent.splice(index, 1);
  104179. }
  104180. }
  104181. });
  104182. this.scene.onMeshImportedObservable.add(function (mesh) {
  104183. var sceneOctree = _this.scene.selectionOctree;
  104184. if (sceneOctree !== undefined && sceneOctree !== null) {
  104185. sceneOctree.addMesh(mesh);
  104186. }
  104187. });
  104188. };
  104189. /**
  104190. * Return the list of active meshes
  104191. * @returns the list of active meshes
  104192. */
  104193. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104194. if (this.scene._selectionOctree) {
  104195. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104196. return selection;
  104197. }
  104198. return this.scene._getDefaultMeshCandidates();
  104199. };
  104200. /**
  104201. * Return the list of active sub meshes
  104202. * @param mesh The mesh to get the candidates sub meshes from
  104203. * @returns the list of active sub meshes
  104204. */
  104205. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104206. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104207. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104208. return intersections;
  104209. }
  104210. return this.scene._getDefaultSubMeshCandidates(mesh);
  104211. };
  104212. /**
  104213. * Return the list of sub meshes intersecting with a given local ray
  104214. * @param mesh defines the mesh to find the submesh for
  104215. * @param localRay defines the ray in local space
  104216. * @returns the list of intersecting sub meshes
  104217. */
  104218. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104219. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104220. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104221. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104222. return intersections;
  104223. }
  104224. return this.scene._getDefaultSubMeshCandidates(mesh);
  104225. };
  104226. /**
  104227. * Return the list of sub meshes colliding with a collider
  104228. * @param mesh defines the mesh to find the submesh for
  104229. * @param collider defines the collider to evaluate the collision against
  104230. * @returns the list of colliding sub meshes
  104231. */
  104232. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104233. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104234. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104235. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104236. return intersections;
  104237. }
  104238. return this.scene._getDefaultSubMeshCandidates(mesh);
  104239. };
  104240. /**
  104241. * Rebuilds the elements related to this component in case of
  104242. * context lost for instance.
  104243. */
  104244. OctreeSceneComponent.prototype.rebuild = function () {
  104245. // Nothing to do here.
  104246. };
  104247. /**
  104248. * Disposes the component and the associated ressources.
  104249. */
  104250. OctreeSceneComponent.prototype.dispose = function () {
  104251. // Nothing to do here.
  104252. };
  104253. return OctreeSceneComponent;
  104254. }());
  104255. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104256. })(BABYLON || (BABYLON = {}));
  104257. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  104258. var BABYLON;
  104259. (function (BABYLON) {
  104260. /**
  104261. * Postprocess used to generate anaglyphic rendering
  104262. */
  104263. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104264. __extends(AnaglyphPostProcess, _super);
  104265. /**
  104266. * Creates a new AnaglyphPostProcess
  104267. * @param name defines postprocess name
  104268. * @param options defines creation options or target ratio scale
  104269. * @param rigCameras defines cameras using this postprocess
  104270. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104271. * @param engine defines hosting engine
  104272. * @param reusable defines if the postprocess will be reused multiple times per frame
  104273. */
  104274. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104275. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104276. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104277. _this.onApplyObservable.add(function (effect) {
  104278. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104279. });
  104280. return _this;
  104281. }
  104282. return AnaglyphPostProcess;
  104283. }(BABYLON.PostProcess));
  104284. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104285. })(BABYLON || (BABYLON = {}));
  104286. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  104287. var BABYLON;
  104288. (function (BABYLON) {
  104289. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104290. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104291. });
  104292. /**
  104293. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104294. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104295. */
  104296. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104297. __extends(AnaglyphArcRotateCamera, _super);
  104298. /**
  104299. * Creates a new AnaglyphArcRotateCamera
  104300. * @param name defines camera name
  104301. * @param alpha defines alpha angle (in radians)
  104302. * @param beta defines beta angle (in radians)
  104303. * @param radius defines radius
  104304. * @param target defines camera target
  104305. * @param interaxialDistance defines distance between each color axis
  104306. * @param scene defines the hosting scene
  104307. */
  104308. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104309. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104310. _this.interaxialDistance = interaxialDistance;
  104311. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104312. return _this;
  104313. }
  104314. /**
  104315. * Gets camera class name
  104316. * @returns AnaglyphArcRotateCamera
  104317. */
  104318. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104319. return "AnaglyphArcRotateCamera";
  104320. };
  104321. return AnaglyphArcRotateCamera;
  104322. }(BABYLON.ArcRotateCamera));
  104323. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104324. })(BABYLON || (BABYLON = {}));
  104325. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  104326. var BABYLON;
  104327. (function (BABYLON) {
  104328. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104329. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104330. });
  104331. /**
  104332. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104333. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104334. */
  104335. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104336. __extends(AnaglyphFreeCamera, _super);
  104337. /**
  104338. * Creates a new AnaglyphFreeCamera
  104339. * @param name defines camera name
  104340. * @param position defines initial position
  104341. * @param interaxialDistance defines distance between each color axis
  104342. * @param scene defines the hosting scene
  104343. */
  104344. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104345. var _this = _super.call(this, name, position, scene) || this;
  104346. _this.interaxialDistance = interaxialDistance;
  104347. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104348. return _this;
  104349. }
  104350. /**
  104351. * Gets camera class name
  104352. * @returns AnaglyphFreeCamera
  104353. */
  104354. AnaglyphFreeCamera.prototype.getClassName = function () {
  104355. return "AnaglyphFreeCamera";
  104356. };
  104357. return AnaglyphFreeCamera;
  104358. }(BABYLON.FreeCamera));
  104359. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104360. })(BABYLON || (BABYLON = {}));
  104361. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  104362. var BABYLON;
  104363. (function (BABYLON) {
  104364. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104365. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104366. });
  104367. /**
  104368. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104369. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104370. */
  104371. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104372. __extends(AnaglyphGamepadCamera, _super);
  104373. /**
  104374. * Creates a new AnaglyphGamepadCamera
  104375. * @param name defines camera name
  104376. * @param position defines initial position
  104377. * @param interaxialDistance defines distance between each color axis
  104378. * @param scene defines the hosting scene
  104379. */
  104380. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  104381. var _this = _super.call(this, name, position, scene) || this;
  104382. _this.interaxialDistance = interaxialDistance;
  104383. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104384. return _this;
  104385. }
  104386. /**
  104387. * Gets camera class name
  104388. * @returns AnaglyphGamepadCamera
  104389. */
  104390. AnaglyphGamepadCamera.prototype.getClassName = function () {
  104391. return "AnaglyphGamepadCamera";
  104392. };
  104393. return AnaglyphGamepadCamera;
  104394. }(BABYLON.GamepadCamera));
  104395. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  104396. })(BABYLON || (BABYLON = {}));
  104397. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  104398. var BABYLON;
  104399. (function (BABYLON) {
  104400. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  104401. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104402. });
  104403. /**
  104404. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  104405. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104406. */
  104407. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  104408. __extends(AnaglyphUniversalCamera, _super);
  104409. /**
  104410. * Creates a new AnaglyphUniversalCamera
  104411. * @param name defines camera name
  104412. * @param position defines initial position
  104413. * @param interaxialDistance defines distance between each color axis
  104414. * @param scene defines the hosting scene
  104415. */
  104416. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  104417. var _this = _super.call(this, name, position, scene) || this;
  104418. _this.interaxialDistance = interaxialDistance;
  104419. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104420. return _this;
  104421. }
  104422. /**
  104423. * Gets camera class name
  104424. * @returns AnaglyphUniversalCamera
  104425. */
  104426. AnaglyphUniversalCamera.prototype.getClassName = function () {
  104427. return "AnaglyphUniversalCamera";
  104428. };
  104429. return AnaglyphUniversalCamera;
  104430. }(BABYLON.UniversalCamera));
  104431. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  104432. })(BABYLON || (BABYLON = {}));
  104433. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  104434. var BABYLON;
  104435. (function (BABYLON) {
  104436. /**
  104437. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  104438. */
  104439. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  104440. __extends(StereoscopicInterlacePostProcess, _super);
  104441. /**
  104442. * Initializes a StereoscopicInterlacePostProcess
  104443. * @param name The name of the effect.
  104444. * @param rigCameras The rig cameras to be appled to the post process
  104445. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  104446. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  104447. * @param engine The engine which the post process will be applied. (default: current engine)
  104448. * @param reusable If the post process can be reused on the same frame. (default: false)
  104449. */
  104450. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  104451. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  104452. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104453. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104454. _this.onSizeChangedObservable.add(function () {
  104455. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104456. });
  104457. _this.onApplyObservable.add(function (effect) {
  104458. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  104459. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  104460. });
  104461. return _this;
  104462. }
  104463. return StereoscopicInterlacePostProcess;
  104464. }(BABYLON.PostProcess));
  104465. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  104466. })(BABYLON || (BABYLON = {}));
  104467. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  104468. var BABYLON;
  104469. (function (BABYLON) {
  104470. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  104471. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104472. });
  104473. /**
  104474. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  104475. * @see http://doc.babylonjs.com/features/cameras
  104476. */
  104477. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  104478. __extends(StereoscopicArcRotateCamera, _super);
  104479. /**
  104480. * Creates a new StereoscopicArcRotateCamera
  104481. * @param name defines camera name
  104482. * @param alpha defines alpha angle (in radians)
  104483. * @param beta defines beta angle (in radians)
  104484. * @param radius defines radius
  104485. * @param target defines camera target
  104486. * @param interaxialDistance defines distance between each color axis
  104487. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104488. * @param scene defines the hosting scene
  104489. */
  104490. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  104491. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104492. _this.interaxialDistance = interaxialDistance;
  104493. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104494. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104495. return _this;
  104496. }
  104497. /**
  104498. * Gets camera class name
  104499. * @returns StereoscopicArcRotateCamera
  104500. */
  104501. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  104502. return "StereoscopicArcRotateCamera";
  104503. };
  104504. return StereoscopicArcRotateCamera;
  104505. }(BABYLON.ArcRotateCamera));
  104506. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  104507. })(BABYLON || (BABYLON = {}));
  104508. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  104509. var BABYLON;
  104510. (function (BABYLON) {
  104511. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104512. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104513. });
  104514. /**
  104515. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  104516. * @see http://doc.babylonjs.com/features/cameras
  104517. */
  104518. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  104519. __extends(StereoscopicFreeCamera, _super);
  104520. /**
  104521. * Creates a new StereoscopicFreeCamera
  104522. * @param name defines camera name
  104523. * @param position defines initial position
  104524. * @param interaxialDistance defines distance between each color axis
  104525. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104526. * @param scene defines the hosting scene
  104527. */
  104528. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104529. var _this = _super.call(this, name, position, scene) || this;
  104530. _this.interaxialDistance = interaxialDistance;
  104531. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104532. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104533. return _this;
  104534. }
  104535. /**
  104536. * Gets camera class name
  104537. * @returns StereoscopicFreeCamera
  104538. */
  104539. StereoscopicFreeCamera.prototype.getClassName = function () {
  104540. return "StereoscopicFreeCamera";
  104541. };
  104542. return StereoscopicFreeCamera;
  104543. }(BABYLON.FreeCamera));
  104544. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  104545. })(BABYLON || (BABYLON = {}));
  104546. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  104547. var BABYLON;
  104548. (function (BABYLON) {
  104549. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  104550. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104551. });
  104552. /**
  104553. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  104554. * @see http://doc.babylonjs.com/features/cameras
  104555. */
  104556. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  104557. __extends(StereoscopicGamepadCamera, _super);
  104558. /**
  104559. * Creates a new StereoscopicGamepadCamera
  104560. * @param name defines camera name
  104561. * @param position defines initial position
  104562. * @param interaxialDistance defines distance between each color axis
  104563. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104564. * @param scene defines the hosting scene
  104565. */
  104566. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104567. var _this = _super.call(this, name, position, scene) || this;
  104568. _this.interaxialDistance = interaxialDistance;
  104569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104571. return _this;
  104572. }
  104573. /**
  104574. * Gets camera class name
  104575. * @returns StereoscopicGamepadCamera
  104576. */
  104577. StereoscopicGamepadCamera.prototype.getClassName = function () {
  104578. return "StereoscopicGamepadCamera";
  104579. };
  104580. return StereoscopicGamepadCamera;
  104581. }(BABYLON.GamepadCamera));
  104582. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  104583. })(BABYLON || (BABYLON = {}));
  104584. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  104585. var BABYLON;
  104586. (function (BABYLON) {
  104587. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104588. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104589. });
  104590. /**
  104591. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  104592. * @see http://doc.babylonjs.com/features/cameras
  104593. */
  104594. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  104595. __extends(StereoscopicUniversalCamera, _super);
  104596. /**
  104597. * Creates a new StereoscopicUniversalCamera
  104598. * @param name defines camera name
  104599. * @param position defines initial position
  104600. * @param interaxialDistance defines distance between each color axis
  104601. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104602. * @param scene defines the hosting scene
  104603. */
  104604. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104605. var _this = _super.call(this, name, position, scene) || this;
  104606. _this.interaxialDistance = interaxialDistance;
  104607. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104608. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104609. return _this;
  104610. }
  104611. /**
  104612. * Gets camera class name
  104613. * @returns StereoscopicUniversalCamera
  104614. */
  104615. StereoscopicUniversalCamera.prototype.getClassName = function () {
  104616. return "StereoscopicUniversalCamera";
  104617. };
  104618. return StereoscopicUniversalCamera;
  104619. }(BABYLON.UniversalCamera));
  104620. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  104621. })(BABYLON || (BABYLON = {}));
  104622. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  104623. var BABYLON;
  104624. (function (BABYLON) {
  104625. /**
  104626. * VRDistortionCorrectionPostProcess used for mobile VR
  104627. */
  104628. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  104629. __extends(VRDistortionCorrectionPostProcess, _super);
  104630. /**
  104631. * Initializes the VRDistortionCorrectionPostProcess
  104632. * @param name The name of the effect.
  104633. * @param camera The camera to apply the render pass to.
  104634. * @param isRightEye If this is for the right eye distortion
  104635. * @param vrMetrics All the required metrics for the VR camera
  104636. */
  104637. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  104638. var _this = _super.call(this, name, "vrDistortionCorrection", [
  104639. 'LensCenter',
  104640. 'Scale',
  104641. 'ScaleIn',
  104642. 'HmdWarpParam'
  104643. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  104644. _this._isRightEye = isRightEye;
  104645. _this._distortionFactors = vrMetrics.distortionK;
  104646. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  104647. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  104648. _this.adaptScaleToCurrentViewport = true;
  104649. _this.onSizeChangedObservable.add(function () {
  104650. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  104651. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  104652. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  104653. });
  104654. _this.onApplyObservable.add(function (effect) {
  104655. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  104656. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  104657. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  104658. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  104659. });
  104660. return _this;
  104661. }
  104662. return VRDistortionCorrectionPostProcess;
  104663. }(BABYLON.PostProcess));
  104664. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  104665. })(BABYLON || (BABYLON = {}));
  104666. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  104667. var BABYLON;
  104668. (function (BABYLON) {
  104669. /**
  104670. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  104671. * Screen rotation is taken into account.
  104672. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104673. */
  104674. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  104675. /**
  104676. * Instantiates a new input
  104677. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104678. */
  104679. function FreeCameraDeviceOrientationInput() {
  104680. var _this = this;
  104681. this._screenOrientationAngle = 0;
  104682. this._screenQuaternion = new BABYLON.Quaternion();
  104683. this._alpha = 0;
  104684. this._beta = 0;
  104685. this._gamma = 0;
  104686. this._orientationChanged = function () {
  104687. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  104688. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  104689. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  104690. };
  104691. this._deviceOrientation = function (evt) {
  104692. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  104693. _this._beta = evt.beta !== null ? evt.beta : 0;
  104694. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  104695. };
  104696. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  104697. this._orientationChanged();
  104698. }
  104699. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  104700. /**
  104701. * Define the camera controlled by the input.
  104702. */
  104703. get: function () {
  104704. return this._camera;
  104705. },
  104706. set: function (camera) {
  104707. this._camera = camera;
  104708. if (this._camera != null && !this._camera.rotationQuaternion) {
  104709. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  104710. }
  104711. },
  104712. enumerable: true,
  104713. configurable: true
  104714. });
  104715. /**
  104716. * Attach the input controls to a specific dom element to get the input from.
  104717. * @param element Defines the element the controls should be listened from
  104718. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104719. */
  104720. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104721. window.addEventListener("orientationchange", this._orientationChanged);
  104722. window.addEventListener("deviceorientation", this._deviceOrientation);
  104723. //In certain cases, the attach control is called AFTER orientation was changed,
  104724. //So this is needed.
  104725. this._orientationChanged();
  104726. };
  104727. /**
  104728. * Detach the current controls from the specified dom element.
  104729. * @param element Defines the element to stop listening the inputs from
  104730. */
  104731. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  104732. window.removeEventListener("orientationchange", this._orientationChanged);
  104733. window.removeEventListener("deviceorientation", this._deviceOrientation);
  104734. };
  104735. /**
  104736. * Update the current camera state depending on the inputs that have been used this frame.
  104737. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104738. */
  104739. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  104740. //if no device orientation provided, don't update the rotation.
  104741. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  104742. if (!this._alpha) {
  104743. return;
  104744. }
  104745. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  104746. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  104747. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  104748. //Mirror on XY Plane
  104749. this._camera.rotationQuaternion.z *= -1;
  104750. this._camera.rotationQuaternion.w *= -1;
  104751. };
  104752. /**
  104753. * Gets the class name of the current intput.
  104754. * @returns the class name
  104755. */
  104756. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  104757. return "FreeCameraDeviceOrientationInput";
  104758. };
  104759. /**
  104760. * Get the friendly name associated with the input class.
  104761. * @returns the input friendly name
  104762. */
  104763. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  104764. return "deviceOrientation";
  104765. };
  104766. return FreeCameraDeviceOrientationInput;
  104767. }());
  104768. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  104769. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  104770. })(BABYLON || (BABYLON = {}));
  104771. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  104772. var BABYLON;
  104773. (function (BABYLON) {
  104774. /**
  104775. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  104776. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104777. */
  104778. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  104779. /**
  104780. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  104781. */
  104782. function ArcRotateCameraVRDeviceOrientationInput() {
  104783. /**
  104784. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  104785. */
  104786. this.alphaCorrection = 1;
  104787. /**
  104788. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  104789. */
  104790. this.betaCorrection = 1;
  104791. /**
  104792. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  104793. */
  104794. this.gammaCorrection = 1;
  104795. this._alpha = 0;
  104796. this._gamma = 0;
  104797. this._dirty = false;
  104798. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  104799. }
  104800. /**
  104801. * Attach the input controls to a specific dom element to get the input from.
  104802. * @param element Defines the element the controls should be listened from
  104803. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104804. */
  104805. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104806. this.camera.attachControl(element, noPreventDefault);
  104807. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  104808. };
  104809. /** @hidden */
  104810. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  104811. if (evt.alpha !== null) {
  104812. this._alpha = +evt.alpha | 0;
  104813. }
  104814. if (evt.gamma !== null) {
  104815. this._gamma = +evt.gamma | 0;
  104816. }
  104817. this._dirty = true;
  104818. };
  104819. /**
  104820. * Update the current camera state depending on the inputs that have been used this frame.
  104821. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104822. */
  104823. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  104824. if (this._dirty) {
  104825. this._dirty = false;
  104826. if (this._gamma < 0) {
  104827. this._gamma = 180 + this._gamma;
  104828. }
  104829. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  104830. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  104831. }
  104832. };
  104833. /**
  104834. * Detach the current controls from the specified dom element.
  104835. * @param element Defines the element to stop listening the inputs from
  104836. */
  104837. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  104838. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  104839. };
  104840. /**
  104841. * Gets the class name of the current intput.
  104842. * @returns the class name
  104843. */
  104844. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  104845. return "ArcRotateCameraVRDeviceOrientationInput";
  104846. };
  104847. /**
  104848. * Get the friendly name associated with the input class.
  104849. * @returns the input friendly name
  104850. */
  104851. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  104852. return "VRDeviceOrientation";
  104853. };
  104854. return ArcRotateCameraVRDeviceOrientationInput;
  104855. }());
  104856. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  104857. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  104858. })(BABYLON || (BABYLON = {}));
  104859. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  104860. var BABYLON;
  104861. (function (BABYLON) {
  104862. /**
  104863. * This represents all the required metrics to create a VR camera.
  104864. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  104865. */
  104866. var VRCameraMetrics = /** @class */ (function () {
  104867. function VRCameraMetrics() {
  104868. /**
  104869. * Define if the current vr camera should compensate the distortion of the lense or not.
  104870. */
  104871. this.compensateDistortion = true;
  104872. }
  104873. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  104874. /**
  104875. * Gets the rendering aspect ratio based on the provided resolutions.
  104876. */
  104877. get: function () {
  104878. return this.hResolution / (2 * this.vResolution);
  104879. },
  104880. enumerable: true,
  104881. configurable: true
  104882. });
  104883. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  104884. /**
  104885. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  104886. */
  104887. get: function () {
  104888. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  104889. },
  104890. enumerable: true,
  104891. configurable: true
  104892. });
  104893. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  104894. /**
  104895. * @hidden
  104896. */
  104897. get: function () {
  104898. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104899. var h = (4 * meters) / this.hScreenSize;
  104900. return BABYLON.Matrix.Translation(h, 0, 0);
  104901. },
  104902. enumerable: true,
  104903. configurable: true
  104904. });
  104905. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  104906. /**
  104907. * @hidden
  104908. */
  104909. get: function () {
  104910. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104911. var h = (4 * meters) / this.hScreenSize;
  104912. return BABYLON.Matrix.Translation(-h, 0, 0);
  104913. },
  104914. enumerable: true,
  104915. configurable: true
  104916. });
  104917. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  104918. /**
  104919. * @hidden
  104920. */
  104921. get: function () {
  104922. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  104923. },
  104924. enumerable: true,
  104925. configurable: true
  104926. });
  104927. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  104928. /**
  104929. * @hidden
  104930. */
  104931. get: function () {
  104932. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  104933. },
  104934. enumerable: true,
  104935. configurable: true
  104936. });
  104937. /**
  104938. * Get the default VRMetrics based on the most generic setup.
  104939. * @returns the default vr metrics
  104940. */
  104941. VRCameraMetrics.GetDefault = function () {
  104942. var result = new VRCameraMetrics();
  104943. result.hResolution = 1280;
  104944. result.vResolution = 800;
  104945. result.hScreenSize = 0.149759993;
  104946. result.vScreenSize = 0.0935999975;
  104947. result.vScreenCenter = 0.0467999987;
  104948. result.eyeToScreenDistance = 0.0410000011;
  104949. result.lensSeparationDistance = 0.0635000020;
  104950. result.interpupillaryDistance = 0.0640000030;
  104951. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  104952. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  104953. result.postProcessScaleFactor = 1.714605507808412;
  104954. result.lensCenterOffset = 0.151976421;
  104955. return result;
  104956. };
  104957. return VRCameraMetrics;
  104958. }());
  104959. BABYLON.VRCameraMetrics = VRCameraMetrics;
  104960. })(BABYLON || (BABYLON = {}));
  104961. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  104962. var BABYLON;
  104963. (function (BABYLON) {
  104964. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  104965. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104966. });
  104967. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  104968. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104969. });
  104970. /**
  104971. * This represents a WebVR camera.
  104972. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  104973. * @example http://doc.babylonjs.com/how_to/webvr_camera
  104974. */
  104975. var WebVRFreeCamera = /** @class */ (function (_super) {
  104976. __extends(WebVRFreeCamera, _super);
  104977. /**
  104978. * Instantiates a WebVRFreeCamera.
  104979. * @param name The name of the WebVRFreeCamera
  104980. * @param position The starting anchor position for the camera
  104981. * @param scene The scene the camera belongs to
  104982. * @param webVROptions a set of customizable options for the webVRCamera
  104983. */
  104984. function WebVRFreeCamera(name, position, scene, webVROptions) {
  104985. if (webVROptions === void 0) { webVROptions = {}; }
  104986. var _this = _super.call(this, name, position, scene) || this;
  104987. _this.webVROptions = webVROptions;
  104988. /**
  104989. * @hidden
  104990. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  104991. */
  104992. _this._vrDevice = null;
  104993. /**
  104994. * The rawPose of the vrDevice.
  104995. */
  104996. _this.rawPose = null;
  104997. _this._specsVersion = "1.1";
  104998. _this._attached = false;
  104999. _this._descendants = [];
  105000. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105001. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105002. /** @hidden */
  105003. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105004. _this._standingMatrix = null;
  105005. /**
  105006. * Represents device position in babylon space.
  105007. */
  105008. _this.devicePosition = BABYLON.Vector3.Zero();
  105009. /**
  105010. * Represents device rotation in babylon space.
  105011. */
  105012. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105013. /**
  105014. * The scale of the device to be used when translating from device space to babylon space.
  105015. */
  105016. _this.deviceScaleFactor = 1;
  105017. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105018. _this._worldToDevice = BABYLON.Matrix.Identity();
  105019. /**
  105020. * References to the webVR controllers for the vrDevice.
  105021. */
  105022. _this.controllers = [];
  105023. /**
  105024. * Emits an event when a controller is attached.
  105025. */
  105026. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105027. /**
  105028. * Emits an event when a controller's mesh has been loaded;
  105029. */
  105030. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105031. /**
  105032. * Emits an event when the HMD's pose has been updated.
  105033. */
  105034. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105035. _this._poseSet = false;
  105036. /**
  105037. * If the rig cameras be used as parent instead of this camera.
  105038. */
  105039. _this.rigParenting = true;
  105040. _this._defaultHeight = undefined;
  105041. _this._htmlElementAttached = null;
  105042. _this._detachIfAttached = function () {
  105043. var vrDisplay = _this.getEngine().getVRDevice();
  105044. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105045. _this.detachControl(_this._htmlElementAttached);
  105046. }
  105047. };
  105048. _this._workingVector = BABYLON.Vector3.Zero();
  105049. _this._oneVector = BABYLON.Vector3.One();
  105050. _this._workingMatrix = BABYLON.Matrix.Identity();
  105051. _this._tmpMatrix = new BABYLON.Matrix();
  105052. _this._cache.position = BABYLON.Vector3.Zero();
  105053. if (webVROptions.defaultHeight) {
  105054. _this._defaultHeight = webVROptions.defaultHeight;
  105055. _this.position.y = _this._defaultHeight;
  105056. }
  105057. _this.minZ = 0.1;
  105058. //legacy support - the compensation boolean was removed.
  105059. if (arguments.length === 5) {
  105060. _this.webVROptions = arguments[4];
  105061. }
  105062. // default webVR options
  105063. if (_this.webVROptions.trackPosition == undefined) {
  105064. _this.webVROptions.trackPosition = true;
  105065. }
  105066. if (_this.webVROptions.controllerMeshes == undefined) {
  105067. _this.webVROptions.controllerMeshes = true;
  105068. }
  105069. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105070. _this.webVROptions.defaultLightingOnControllers = true;
  105071. }
  105072. _this.rotationQuaternion = new BABYLON.Quaternion();
  105073. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105074. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105075. }
  105076. //enable VR
  105077. var engine = _this.getEngine();
  105078. _this._onVREnabled = function (success) { if (success) {
  105079. _this.initControllers();
  105080. } };
  105081. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105082. engine.initWebVR().add(function (event) {
  105083. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105084. return;
  105085. }
  105086. _this._vrDevice = event.vrDisplay;
  105087. //reset the rig parameters.
  105088. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105089. if (_this._attached) {
  105090. _this.getEngine().enableVR();
  105091. }
  105092. });
  105093. if (typeof (VRFrameData) !== "undefined") {
  105094. _this._frameData = new VRFrameData();
  105095. }
  105096. /**
  105097. * The idea behind the following lines:
  105098. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105099. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105100. * the second will not show it correctly.
  105101. *
  105102. * To solve this - each object that has the camera as parent will be added to a protected array.
  105103. * When the rig camera renders, it will take this array and set all of those to be its children.
  105104. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105105. * Amazing!
  105106. */
  105107. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105108. if (camera.parent === _this && _this.rigParenting) {
  105109. _this._descendants = _this.getDescendants(true, function (n) {
  105110. // don't take the cameras or the controllers!
  105111. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105112. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105113. return !isController && !isRigCamera;
  105114. });
  105115. _this._descendants.forEach(function (node) {
  105116. node.parent = camera;
  105117. });
  105118. }
  105119. });
  105120. scene.onAfterCameraRenderObservable.add(function (camera) {
  105121. if (camera.parent === _this && _this.rigParenting) {
  105122. _this._descendants.forEach(function (node) {
  105123. node.parent = _this;
  105124. });
  105125. }
  105126. });
  105127. return _this;
  105128. }
  105129. /**
  105130. * Gets the device distance from the ground in meters.
  105131. * @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.
  105132. */
  105133. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105134. if (this._standingMatrix) {
  105135. // Add standing matrix offset to get real offset from ground in room
  105136. this._standingMatrix.getTranslationToRef(this._workingVector);
  105137. return this._deviceRoomPosition.y + this._workingVector.y;
  105138. }
  105139. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105140. return this._defaultHeight || 0;
  105141. };
  105142. /**
  105143. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105144. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105145. */
  105146. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105147. var _this = this;
  105148. if (callback === void 0) { callback = function (bool) { }; }
  105149. // Use standing matrix if available
  105150. this.getEngine().initWebVRAsync().then(function (result) {
  105151. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105152. callback(false);
  105153. }
  105154. else {
  105155. _this._standingMatrix = new BABYLON.Matrix();
  105156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105157. if (!_this.getScene().useRightHandedSystem) {
  105158. [2, 6, 8, 9, 14].forEach(function (num) {
  105159. if (_this._standingMatrix) {
  105160. _this._standingMatrix.m[num] *= -1;
  105161. }
  105162. });
  105163. }
  105164. callback(true);
  105165. }
  105166. });
  105167. };
  105168. /**
  105169. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105170. * @returns A promise with a boolean set to if the standing matrix is supported.
  105171. */
  105172. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105173. var _this = this;
  105174. return new Promise(function (res, rej) {
  105175. _this.useStandingMatrix(function (supported) {
  105176. res(supported);
  105177. });
  105178. });
  105179. };
  105180. /**
  105181. * Disposes the camera
  105182. */
  105183. WebVRFreeCamera.prototype.dispose = function () {
  105184. this._detachIfAttached();
  105185. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105186. if (this._updateCacheWhenTrackingDisabledObserver) {
  105187. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105188. }
  105189. _super.prototype.dispose.call(this);
  105190. };
  105191. /**
  105192. * Gets a vrController by name.
  105193. * @param name The name of the controller to retreive
  105194. * @returns the controller matching the name specified or null if not found
  105195. */
  105196. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105197. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105198. var gp = _a[_i];
  105199. if (gp.hand === name) {
  105200. return gp;
  105201. }
  105202. }
  105203. return null;
  105204. };
  105205. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105206. /**
  105207. * The controller corrisponding to the users left hand.
  105208. */
  105209. get: function () {
  105210. if (!this._leftController) {
  105211. this._leftController = this.getControllerByName("left");
  105212. }
  105213. return this._leftController;
  105214. },
  105215. enumerable: true,
  105216. configurable: true
  105217. });
  105218. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105219. /**
  105220. * The controller corrisponding to the users right hand.
  105221. */
  105222. get: function () {
  105223. if (!this._rightController) {
  105224. this._rightController = this.getControllerByName("right");
  105225. }
  105226. return this._rightController;
  105227. },
  105228. enumerable: true,
  105229. configurable: true
  105230. });
  105231. /**
  105232. * Casts a ray forward from the vrCamera's gaze.
  105233. * @param length Length of the ray (default: 100)
  105234. * @returns the ray corrisponding to the gaze
  105235. */
  105236. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105237. if (length === void 0) { length = 100; }
  105238. if (this.leftCamera) {
  105239. // Use left eye to avoid computation to compute center on every call
  105240. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105241. }
  105242. else {
  105243. return _super.prototype.getForwardRay.call(this, length);
  105244. }
  105245. };
  105246. /**
  105247. * @hidden
  105248. * Updates the camera based on device's frame data
  105249. */
  105250. WebVRFreeCamera.prototype._checkInputs = function () {
  105251. if (this._vrDevice && this._vrDevice.isPresenting) {
  105252. this._vrDevice.getFrameData(this._frameData);
  105253. this.updateFromDevice(this._frameData.pose);
  105254. }
  105255. _super.prototype._checkInputs.call(this);
  105256. };
  105257. /**
  105258. * Updates the poseControlled values based on the input device pose.
  105259. * @param poseData Pose coming from the device
  105260. */
  105261. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105262. if (poseData && poseData.orientation) {
  105263. this.rawPose = poseData;
  105264. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105265. if (this.getScene().useRightHandedSystem) {
  105266. this._deviceRoomRotationQuaternion.z *= -1;
  105267. this._deviceRoomRotationQuaternion.w *= -1;
  105268. }
  105269. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105270. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105271. if (this.getScene().useRightHandedSystem) {
  105272. this._deviceRoomPosition.z *= -1;
  105273. }
  105274. }
  105275. this._poseSet = true;
  105276. }
  105277. };
  105278. /**
  105279. * WebVR's attach control will start broadcasting frames to the device.
  105280. * Note that in certain browsers (chrome for example) this function must be called
  105281. * within a user-interaction callback. Example:
  105282. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105283. *
  105284. * @param element html element to attach the vrDevice to
  105285. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105286. */
  105287. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105288. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105289. this._attached = true;
  105290. this._htmlElementAttached = element;
  105291. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105292. if (this._vrDevice) {
  105293. this.getEngine().enableVR();
  105294. }
  105295. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105296. };
  105297. /**
  105298. * Detaches the camera from the html element and disables VR
  105299. *
  105300. * @param element html element to detach from
  105301. */
  105302. WebVRFreeCamera.prototype.detachControl = function (element) {
  105303. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105304. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105305. _super.prototype.detachControl.call(this, element);
  105306. this._attached = false;
  105307. this.getEngine().disableVR();
  105308. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105309. };
  105310. /**
  105311. * @returns the name of this class
  105312. */
  105313. WebVRFreeCamera.prototype.getClassName = function () {
  105314. return "WebVRFreeCamera";
  105315. };
  105316. /**
  105317. * Calls resetPose on the vrDisplay
  105318. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105319. */
  105320. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105321. //uses the vrDisplay's "resetPose()".
  105322. //pitch and roll won't be affected.
  105323. this._vrDevice.resetPose();
  105324. };
  105325. /**
  105326. * @hidden
  105327. * Updates the rig cameras (left and right eye)
  105328. */
  105329. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105330. var camLeft = this._rigCameras[0];
  105331. var camRight = this._rigCameras[1];
  105332. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105333. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105334. camLeft.position.copyFrom(this._deviceRoomPosition);
  105335. camRight.position.copyFrom(this._deviceRoomPosition);
  105336. };
  105337. // Remove translation from 6dof headset if trackposition is set to false
  105338. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105339. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105340. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105341. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105342. if (!isViewMatrix) {
  105343. this._tmpMatrix.invert();
  105344. }
  105345. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105346. }
  105347. };
  105348. /**
  105349. * @hidden
  105350. * Updates the cached values of the camera
  105351. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105352. */
  105353. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105354. var _this = this;
  105355. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105356. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105357. if (!this.updateCacheCalled) {
  105358. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105359. this.updateCacheCalled = true;
  105360. this.update();
  105361. }
  105362. // Set working vector to the device position in room space rotated by the new rotation
  105363. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105364. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105365. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105366. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105367. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105368. // Add translation from anchor position
  105369. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105370. this._workingVector.addInPlace(this.position);
  105371. this._workingVector.subtractInPlace(this._cache.position);
  105372. this._deviceToWorld.setTranslation(this._workingVector);
  105373. // Set an inverted matrix to be used when updating the camera
  105374. this._deviceToWorld.invertToRef(this._worldToDevice);
  105375. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105376. this.controllers.forEach(function (controller) {
  105377. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105378. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  105379. controller.update();
  105380. });
  105381. }
  105382. if (!ignoreParentClass) {
  105383. _super.prototype._updateCache.call(this);
  105384. }
  105385. this.updateCacheCalled = false;
  105386. };
  105387. /**
  105388. * @hidden
  105389. * Get current device position in babylon world
  105390. */
  105391. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  105392. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  105393. };
  105394. /**
  105395. * Updates the current device position and rotation in the babylon world
  105396. */
  105397. WebVRFreeCamera.prototype.update = function () {
  105398. this._computeDevicePosition();
  105399. // Get current device rotation in babylon world
  105400. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  105401. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  105402. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  105403. if (this._poseSet) {
  105404. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  105405. }
  105406. _super.prototype.update.call(this);
  105407. };
  105408. /**
  105409. * @hidden
  105410. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  105411. * @returns an identity matrix
  105412. */
  105413. WebVRFreeCamera.prototype._getViewMatrix = function () {
  105414. return BABYLON.Matrix.Identity();
  105415. };
  105416. /**
  105417. * This function is called by the two RIG cameras.
  105418. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  105419. */
  105420. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  105421. var _this = this;
  105422. // Update the parent camera prior to using a child camera to avoid desynchronization
  105423. var parentCamera = this._cameraRigParams["parentCamera"];
  105424. parentCamera._updateCache();
  105425. //WebVR 1.1
  105426. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  105427. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  105428. if (!this.getScene().useRightHandedSystem) {
  105429. [2, 6, 8, 9, 14].forEach(function (num) {
  105430. _this._webvrViewMatrix.m[num] *= -1;
  105431. });
  105432. }
  105433. // update the camera rotation matrix
  105434. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  105435. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  105436. // Computing target and final matrix
  105437. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  105438. // should the view matrix be updated with scale and position offset?
  105439. if (parentCamera.deviceScaleFactor !== 1) {
  105440. this._webvrViewMatrix.invert();
  105441. // scale the position, if set
  105442. if (parentCamera.deviceScaleFactor) {
  105443. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  105444. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  105445. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  105446. }
  105447. this._webvrViewMatrix.invert();
  105448. }
  105449. // Remove translation from 6dof headset if trackposition is set to false
  105450. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  105451. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  105452. // Compute global position
  105453. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  105454. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  105455. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  105456. this._workingMatrix.getTranslationToRef(this._globalPosition);
  105457. this._markSyncedWithParent();
  105458. return this._webvrViewMatrix;
  105459. };
  105460. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  105461. var _this = this;
  105462. var parentCamera = this.parent;
  105463. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  105464. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  105465. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  105466. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  105467. //babylon compatible matrix
  105468. if (!this.getScene().useRightHandedSystem) {
  105469. [8, 9, 10, 11].forEach(function (num) {
  105470. _this._projectionMatrix.m[num] *= -1;
  105471. });
  105472. }
  105473. return this._projectionMatrix;
  105474. };
  105475. /**
  105476. * Initializes the controllers and their meshes
  105477. */
  105478. WebVRFreeCamera.prototype.initControllers = function () {
  105479. var _this = this;
  105480. this.controllers = [];
  105481. var manager = this.getScene().gamepadManager;
  105482. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  105483. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105484. var webVrController = gamepad;
  105485. if (webVrController.defaultModel) {
  105486. webVrController.defaultModel.setEnabled(false);
  105487. }
  105488. if (webVrController.hand === "right") {
  105489. _this._rightController = null;
  105490. }
  105491. if (webVrController.hand === "left") {
  105492. _this._leftController = null;
  105493. }
  105494. var controllerIndex = _this.controllers.indexOf(webVrController);
  105495. if (controllerIndex !== -1) {
  105496. _this.controllers.splice(controllerIndex, 1);
  105497. }
  105498. }
  105499. });
  105500. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  105501. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105502. var webVrController_1 = gamepad;
  105503. if (!_this.webVROptions.trackPosition) {
  105504. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  105505. // Cache must be updated before rendering controllers to avoid them being one frame behind
  105506. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  105507. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  105508. _this._updateCache();
  105509. });
  105510. }
  105511. }
  105512. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  105513. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  105514. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  105515. if (_this.webVROptions.controllerMeshes) {
  105516. if (webVrController_1.defaultModel) {
  105517. webVrController_1.defaultModel.setEnabled(true);
  105518. }
  105519. else {
  105520. // Load the meshes
  105521. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  105522. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  105523. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  105524. if (_this.webVROptions.defaultLightingOnControllers) {
  105525. if (!_this._lightOnControllers) {
  105526. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  105527. }
  105528. var activateLightOnSubMeshes_1 = function (mesh, light) {
  105529. var children = mesh.getChildren();
  105530. if (children && children.length !== 0) {
  105531. children.forEach(function (mesh) {
  105532. light.includedOnlyMeshes.push(mesh);
  105533. activateLightOnSubMeshes_1(mesh, light);
  105534. });
  105535. }
  105536. };
  105537. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  105538. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  105539. }
  105540. });
  105541. }
  105542. }
  105543. webVrController_1.attachToPoseControlledCamera(_this);
  105544. // since this is async - sanity check. Is the controller already stored?
  105545. if (_this.controllers.indexOf(webVrController_1) === -1) {
  105546. //add to the controllers array
  105547. _this.controllers.push(webVrController_1);
  105548. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  105549. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  105550. // So we're overriding setting left & right manually to be sure
  105551. var firstViveWandDetected = false;
  105552. for (var i = 0; i < _this.controllers.length; i++) {
  105553. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105554. if (!firstViveWandDetected) {
  105555. firstViveWandDetected = true;
  105556. _this.controllers[i].hand = "left";
  105557. }
  105558. else {
  105559. _this.controllers[i].hand = "right";
  105560. }
  105561. }
  105562. }
  105563. //did we find enough controllers? Great! let the developer know.
  105564. if (_this.controllers.length >= 2) {
  105565. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  105566. }
  105567. }
  105568. }
  105569. });
  105570. };
  105571. return WebVRFreeCamera;
  105572. }(BABYLON.FreeCamera));
  105573. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  105574. })(BABYLON || (BABYLON = {}));
  105575. //# sourceMappingURL=babylon.webVRCamera.js.map
  105576. var BABYLON;
  105577. (function (BABYLON) {
  105578. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  105579. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  105580. });
  105581. // We're mainly based on the logic defined into the FreeCamera code
  105582. /**
  105583. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  105584. * being tilted forward or back and left or right.
  105585. */
  105586. var DeviceOrientationCamera = /** @class */ (function (_super) {
  105587. __extends(DeviceOrientationCamera, _super);
  105588. /**
  105589. * Creates a new device orientation camera
  105590. * @param name The name of the camera
  105591. * @param position The start position camera
  105592. * @param scene The scene the camera belongs to
  105593. */
  105594. function DeviceOrientationCamera(name, position, scene) {
  105595. var _this = _super.call(this, name, position, scene) || this;
  105596. _this._quaternionCache = new BABYLON.Quaternion();
  105597. _this.inputs.addDeviceOrientation();
  105598. return _this;
  105599. }
  105600. /**
  105601. * Gets the current instance class name ("DeviceOrientationCamera").
  105602. * This helps avoiding instanceof at run time.
  105603. * @returns the class name
  105604. */
  105605. DeviceOrientationCamera.prototype.getClassName = function () {
  105606. return "DeviceOrientationCamera";
  105607. };
  105608. /**
  105609. * @hidden
  105610. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  105611. */
  105612. DeviceOrientationCamera.prototype._checkInputs = function () {
  105613. _super.prototype._checkInputs.call(this);
  105614. this._quaternionCache.copyFrom(this.rotationQuaternion);
  105615. if (this._initialQuaternion) {
  105616. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105617. }
  105618. };
  105619. /**
  105620. * Reset the camera to its default orientation on the specified axis only.
  105621. * @param axis The axis to reset
  105622. */
  105623. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  105624. var _this = this;
  105625. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  105626. //can only work if this camera has a rotation quaternion already.
  105627. if (!this.rotationQuaternion) {
  105628. return;
  105629. }
  105630. if (!this._initialQuaternion) {
  105631. this._initialQuaternion = new BABYLON.Quaternion();
  105632. }
  105633. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  105634. ['x', 'y', 'z'].forEach(function (axisName) {
  105635. if (!axis[axisName]) {
  105636. _this._initialQuaternion[axisName] = 0;
  105637. }
  105638. else {
  105639. _this._initialQuaternion[axisName] *= -1;
  105640. }
  105641. });
  105642. this._initialQuaternion.normalize();
  105643. //force rotation update
  105644. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105645. };
  105646. return DeviceOrientationCamera;
  105647. }(BABYLON.FreeCamera));
  105648. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  105649. })(BABYLON || (BABYLON = {}));
  105650. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  105651. var BABYLON;
  105652. (function (BABYLON) {
  105653. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105654. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105655. });
  105656. /**
  105657. * Camera used to simulate VR rendering (based on FreeCamera)
  105658. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105659. */
  105660. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  105661. __extends(VRDeviceOrientationFreeCamera, _super);
  105662. /**
  105663. * Creates a new VRDeviceOrientationFreeCamera
  105664. * @param name defines camera name
  105665. * @param position defines the start position of the camera
  105666. * @param scene defines the scene the camera belongs to
  105667. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105668. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105669. */
  105670. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105671. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105672. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105673. var _this = _super.call(this, name, position, scene) || this;
  105674. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105675. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105676. return _this;
  105677. }
  105678. /**
  105679. * Gets camera class name
  105680. * @returns VRDeviceOrientationFreeCamera
  105681. */
  105682. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  105683. return "VRDeviceOrientationFreeCamera";
  105684. };
  105685. return VRDeviceOrientationFreeCamera;
  105686. }(BABYLON.DeviceOrientationCamera));
  105687. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  105688. })(BABYLON || (BABYLON = {}));
  105689. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  105690. var BABYLON;
  105691. (function (BABYLON) {
  105692. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105693. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  105694. });
  105695. /**
  105696. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  105697. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105698. */
  105699. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  105700. __extends(VRDeviceOrientationArcRotateCamera, _super);
  105701. /**
  105702. * Creates a new VRDeviceOrientationArcRotateCamera
  105703. * @param name defines camera name
  105704. * @param alpha defines the camera rotation along the logitudinal axis
  105705. * @param beta defines the camera rotation along the latitudinal axis
  105706. * @param radius defines the camera distance from its target
  105707. * @param target defines the camera target
  105708. * @param scene defines the scene the camera belongs to
  105709. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105710. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105711. */
  105712. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  105713. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105714. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105715. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105716. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105717. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105718. _this.inputs.addVRDeviceOrientation();
  105719. return _this;
  105720. }
  105721. /**
  105722. * Gets camera class name
  105723. * @returns VRDeviceOrientationArcRotateCamera
  105724. */
  105725. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  105726. return "VRDeviceOrientationArcRotateCamera";
  105727. };
  105728. return VRDeviceOrientationArcRotateCamera;
  105729. }(BABYLON.ArcRotateCamera));
  105730. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  105731. })(BABYLON || (BABYLON = {}));
  105732. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  105733. var BABYLON;
  105734. (function (BABYLON) {
  105735. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  105736. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  105737. });
  105738. /**
  105739. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  105740. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105741. */
  105742. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  105743. __extends(VRDeviceOrientationGamepadCamera, _super);
  105744. /**
  105745. * Creates a new VRDeviceOrientationGamepadCamera
  105746. * @param name defines camera name
  105747. * @param position defines the start position of the camera
  105748. * @param scene defines the scene the camera belongs to
  105749. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105750. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105751. */
  105752. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105753. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105754. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105755. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  105756. _this.inputs.addGamepad();
  105757. return _this;
  105758. }
  105759. /**
  105760. * Gets camera class name
  105761. * @returns VRDeviceOrientationGamepadCamera
  105762. */
  105763. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  105764. return "VRDeviceOrientationGamepadCamera";
  105765. };
  105766. return VRDeviceOrientationGamepadCamera;
  105767. }(BABYLON.VRDeviceOrientationFreeCamera));
  105768. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  105769. })(BABYLON || (BABYLON = {}));
  105770. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  105771. var BABYLON;
  105772. (function (BABYLON) {
  105773. var VRExperienceHelperGazer = /** @class */ (function () {
  105774. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  105775. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  105776. this.scene = scene;
  105777. /** @hidden */
  105778. this._pointerDownOnMeshAsked = false;
  105779. /** @hidden */
  105780. this._isActionableMesh = false;
  105781. /** @hidden */
  105782. this._teleportationRequestInitiated = false;
  105783. /** @hidden */
  105784. this._teleportationBackRequestInitiated = false;
  105785. /** @hidden */
  105786. this._rotationRightAsked = false;
  105787. /** @hidden */
  105788. this._rotationLeftAsked = false;
  105789. /** @hidden */
  105790. this._dpadPressed = true;
  105791. /** @hidden */
  105792. this._activePointer = false;
  105793. this._id = VRExperienceHelperGazer._idCounter++;
  105794. // Gaze tracker
  105795. if (!gazeTrackerToClone) {
  105796. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  105797. this._gazeTracker.bakeCurrentTransformIntoVertices();
  105798. this._gazeTracker.isPickable = false;
  105799. this._gazeTracker.isVisible = false;
  105800. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  105801. targetMat.specularColor = BABYLON.Color3.Black();
  105802. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105803. targetMat.backFaceCulling = false;
  105804. this._gazeTracker.material = targetMat;
  105805. }
  105806. else {
  105807. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  105808. }
  105809. }
  105810. /** @hidden */
  105811. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  105812. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  105813. };
  105814. /** @hidden */
  105815. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  105816. this._pointerDownOnMeshAsked = true;
  105817. if (this._currentHit) {
  105818. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  105819. }
  105820. };
  105821. /** @hidden */
  105822. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  105823. if (this._currentHit) {
  105824. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  105825. }
  105826. this._pointerDownOnMeshAsked = false;
  105827. };
  105828. /** @hidden */
  105829. VRExperienceHelperGazer.prototype._activatePointer = function () {
  105830. this._activePointer = true;
  105831. };
  105832. /** @hidden */
  105833. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  105834. this._activePointer = false;
  105835. };
  105836. /** @hidden */
  105837. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  105838. if (distance === void 0) { distance = 100; }
  105839. };
  105840. VRExperienceHelperGazer.prototype.dispose = function () {
  105841. this._interactionsEnabled = false;
  105842. this._teleportationEnabled = false;
  105843. if (this._gazeTracker) {
  105844. this._gazeTracker.dispose();
  105845. }
  105846. };
  105847. VRExperienceHelperGazer._idCounter = 0;
  105848. return VRExperienceHelperGazer;
  105849. }());
  105850. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  105851. __extends(VRExperienceHelperControllerGazer, _super);
  105852. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  105853. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  105854. _this.webVRController = webVRController;
  105855. // Laser pointer
  105856. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  105857. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  105858. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105859. laserPointerMaterial.alpha = 0.6;
  105860. _this._laserPointer.material = laserPointerMaterial;
  105861. _this._laserPointer.rotation.x = Math.PI / 2;
  105862. _this._laserPointer.position.z = -0.5;
  105863. _this._laserPointer.isVisible = false;
  105864. _this._laserPointer.isPickable = false;
  105865. if (!webVRController.mesh) {
  105866. // Create an empty mesh that is used prior to loading the high quality model
  105867. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  105868. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  105869. preloadPointerPose.rotation.x = -0.7;
  105870. preloadMesh.addChild(preloadPointerPose);
  105871. webVRController.attachToMesh(preloadMesh);
  105872. }
  105873. _this._setLaserPointerParent(webVRController.mesh);
  105874. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  105875. _this._setLaserPointerParent(mesh);
  105876. });
  105877. return _this;
  105878. }
  105879. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  105880. return this.webVRController.getForwardRay(length);
  105881. };
  105882. /** @hidden */
  105883. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  105884. _super.prototype._activatePointer.call(this);
  105885. this._laserPointer.isVisible = true;
  105886. };
  105887. /** @hidden */
  105888. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  105889. _super.prototype._deactivatePointer.call(this);
  105890. this._laserPointer.isVisible = false;
  105891. };
  105892. /** @hidden */
  105893. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  105894. this._laserPointer.material.emissiveColor = color;
  105895. };
  105896. /** @hidden */
  105897. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  105898. var makeNotPick = function (root) {
  105899. root.isPickable = false;
  105900. root.getChildMeshes().forEach(function (c) {
  105901. makeNotPick(c);
  105902. });
  105903. };
  105904. makeNotPick(mesh);
  105905. var childMeshes = mesh.getChildMeshes();
  105906. this.webVRController._pointingPoseNode = null;
  105907. for (var i = 0; i < childMeshes.length; i++) {
  105908. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  105909. mesh = childMeshes[i];
  105910. this.webVRController._pointingPoseNode = mesh;
  105911. break;
  105912. }
  105913. }
  105914. this._laserPointer.parent = mesh;
  105915. };
  105916. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  105917. if (distance === void 0) { distance = 100; }
  105918. this._laserPointer.scaling.y = distance;
  105919. this._laserPointer.position.z = -distance / 2;
  105920. };
  105921. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  105922. _super.prototype.dispose.call(this);
  105923. this._laserPointer.dispose();
  105924. if (this._meshAttachedObserver) {
  105925. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  105926. }
  105927. };
  105928. return VRExperienceHelperControllerGazer;
  105929. }(VRExperienceHelperGazer));
  105930. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  105931. __extends(VRExperienceHelperCameraGazer, _super);
  105932. function VRExperienceHelperCameraGazer(getCamera, scene) {
  105933. var _this = _super.call(this, scene) || this;
  105934. _this.getCamera = getCamera;
  105935. return _this;
  105936. }
  105937. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  105938. var camera = this.getCamera();
  105939. if (camera) {
  105940. return camera.getForwardRay(length);
  105941. }
  105942. else {
  105943. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  105944. }
  105945. };
  105946. return VRExperienceHelperCameraGazer;
  105947. }(VRExperienceHelperGazer));
  105948. /**
  105949. * Helps to quickly add VR support to an existing scene.
  105950. * See http://doc.babylonjs.com/how_to/webvr_helper
  105951. */
  105952. var VRExperienceHelper = /** @class */ (function () {
  105953. /**
  105954. * Instantiates a VRExperienceHelper.
  105955. * Helps to quickly add VR support to an existing scene.
  105956. * @param scene The scene the VRExperienceHelper belongs to.
  105957. * @param webVROptions Options to modify the vr experience helper's behavior.
  105958. */
  105959. function VRExperienceHelper(scene,
  105960. /** Options to modify the vr experience helper's behavior. */
  105961. webVROptions) {
  105962. if (webVROptions === void 0) { webVROptions = {}; }
  105963. var _this = this;
  105964. this.webVROptions = webVROptions;
  105965. // Can the system support WebVR, even if a headset isn't plugged in?
  105966. this._webVRsupported = false;
  105967. // If WebVR is supported, is a headset plugged in and are we ready to present?
  105968. this._webVRready = false;
  105969. // Are we waiting for the requestPresent callback to complete?
  105970. this._webVRrequesting = false;
  105971. // Are we presenting to the headset right now? (this is the vrDevice state)
  105972. this._webVRpresenting = false;
  105973. // Are we presenting in the fullscreen fallback?
  105974. this._fullscreenVRpresenting = false;
  105975. /**
  105976. * Observable raised when entering VR.
  105977. */
  105978. this.onEnteringVRObservable = new BABYLON.Observable();
  105979. /**
  105980. * Observable raised when exiting VR.
  105981. */
  105982. this.onExitingVRObservable = new BABYLON.Observable();
  105983. /**
  105984. * Observable raised when controller mesh is loaded.
  105985. */
  105986. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105987. this._useCustomVRButton = false;
  105988. this._teleportationRequested = false;
  105989. this._teleportActive = false;
  105990. this._floorMeshesCollection = [];
  105991. this._rotationAllowed = true;
  105992. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  105993. this._isDefaultTeleportationTarget = true;
  105994. this._teleportationFillColor = "#444444";
  105995. this._teleportationBorderColor = "#FFFFFF";
  105996. this._rotationAngle = 0;
  105997. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  105998. this._padSensibilityUp = 0.65;
  105999. this._padSensibilityDown = 0.35;
  106000. this._leftController = null;
  106001. this._rightController = null;
  106002. /**
  106003. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  106004. */
  106005. this.onNewMeshSelected = new BABYLON.Observable();
  106006. /**
  106007. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106008. */
  106009. this.onNewMeshPicked = new BABYLON.Observable();
  106010. /**
  106011. * Observable raised before camera teleportation
  106012. */
  106013. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106014. /**
  106015. * Observable raised after camera teleportation
  106016. */
  106017. this.onAfterCameraTeleport = new BABYLON.Observable();
  106018. /**
  106019. * Observable raised when current selected mesh gets unselected
  106020. */
  106021. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106022. /**
  106023. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106024. */
  106025. this.teleportationEnabled = true;
  106026. this._teleportationInitialized = false;
  106027. this._interactionsEnabled = false;
  106028. this._interactionsRequested = false;
  106029. this._displayGaze = true;
  106030. this._displayLaserPointer = true;
  106031. /**
  106032. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106033. */
  106034. this.updateGazeTrackerScale = true;
  106035. this._onResize = function () {
  106036. _this.moveButtonToBottomRight();
  106037. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106038. _this.exitVR();
  106039. }
  106040. };
  106041. this._onFullscreenChange = function () {
  106042. if (document.fullscreen !== undefined) {
  106043. _this._fullscreenVRpresenting = document.fullscreen;
  106044. }
  106045. else if (document.mozFullScreen !== undefined) {
  106046. _this._fullscreenVRpresenting = document.mozFullScreen;
  106047. }
  106048. else if (document.webkitIsFullScreen !== undefined) {
  106049. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106050. }
  106051. else if (document.msIsFullScreen !== undefined) {
  106052. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106053. }
  106054. else if (document.msFullscreenElement !== undefined) {
  106055. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106056. }
  106057. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106058. _this.exitVR();
  106059. if (!_this._useCustomVRButton) {
  106060. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106061. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106062. }
  106063. }
  106064. };
  106065. this.beforeRender = function () {
  106066. if (_this._leftController && _this._leftController._activePointer) {
  106067. _this._castRayAndSelectObject(_this._leftController);
  106068. }
  106069. if (_this._rightController && _this._rightController._activePointer) {
  106070. _this._castRayAndSelectObject(_this._rightController);
  106071. }
  106072. if (_this._noControllerIsActive) {
  106073. _this._castRayAndSelectObject(_this._cameraGazer);
  106074. }
  106075. else {
  106076. _this._cameraGazer._gazeTracker.isVisible = false;
  106077. }
  106078. };
  106079. this._onNewGamepadConnected = function (gamepad) {
  106080. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106081. if (gamepad.leftStick) {
  106082. gamepad.onleftstickchanged(function (stickValues) {
  106083. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106084. // Listening to classic/xbox gamepad only if no VR controller is active
  106085. if ((!_this._leftController && !_this._rightController) ||
  106086. ((_this._leftController && !_this._leftController._activePointer) &&
  106087. (_this._rightController && !_this._rightController._activePointer))) {
  106088. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106089. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106090. }
  106091. }
  106092. });
  106093. }
  106094. if (gamepad.rightStick) {
  106095. gamepad.onrightstickchanged(function (stickValues) {
  106096. if (_this._teleportationInitialized) {
  106097. _this._checkRotate(stickValues, _this._cameraGazer);
  106098. }
  106099. });
  106100. }
  106101. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106102. gamepad.onbuttondown(function (buttonPressed) {
  106103. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106104. _this._cameraGazer._selectionPointerDown();
  106105. }
  106106. });
  106107. gamepad.onbuttonup(function (buttonPressed) {
  106108. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106109. _this._cameraGazer._selectionPointerUp();
  106110. }
  106111. });
  106112. }
  106113. }
  106114. else {
  106115. var webVRController = gamepad;
  106116. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106117. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106118. _this._rightController = controller;
  106119. }
  106120. else {
  106121. _this._leftController = controller;
  106122. }
  106123. _this._tryEnableInteractionOnController(controller);
  106124. }
  106125. };
  106126. // 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
  106127. this._tryEnableInteractionOnController = function (controller) {
  106128. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106129. _this._enableInteractionOnController(controller);
  106130. }
  106131. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106132. _this._enableTeleportationOnController(controller);
  106133. }
  106134. };
  106135. this._onNewGamepadDisconnected = function (gamepad) {
  106136. if (gamepad instanceof BABYLON.WebVRController) {
  106137. if (gamepad.hand === "left" && _this._leftController != null) {
  106138. _this._leftController.dispose();
  106139. _this._leftController = null;
  106140. }
  106141. if (gamepad.hand === "right" && _this._rightController != null) {
  106142. _this._rightController.dispose();
  106143. _this._rightController = null;
  106144. }
  106145. }
  106146. };
  106147. this._workingVector = BABYLON.Vector3.Zero();
  106148. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106149. this._workingMatrix = BABYLON.Matrix.Identity();
  106150. this._scene = scene;
  106151. this._canvas = scene.getEngine().getRenderingCanvas();
  106152. // Parse options
  106153. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106154. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106155. }
  106156. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106157. webVROptions.createDeviceOrientationCamera = true;
  106158. }
  106159. if (webVROptions.laserToggle === undefined) {
  106160. webVROptions.laserToggle = true;
  106161. }
  106162. if (webVROptions.defaultHeight === undefined) {
  106163. webVROptions.defaultHeight = 1.7;
  106164. }
  106165. if (webVROptions.useCustomVRButton) {
  106166. this._useCustomVRButton = true;
  106167. if (webVROptions.customVRButton) {
  106168. this._btnVR = webVROptions.customVRButton;
  106169. }
  106170. }
  106171. if (webVROptions.rayLength) {
  106172. this._rayLength = webVROptions.rayLength;
  106173. }
  106174. this._defaultHeight = webVROptions.defaultHeight;
  106175. if (webVROptions.positionScale) {
  106176. this._rayLength *= webVROptions.positionScale;
  106177. this._defaultHeight *= webVROptions.positionScale;
  106178. }
  106179. this._hasEnteredVR = false;
  106180. // Set position
  106181. if (this._scene.activeCamera) {
  106182. this._position = this._scene.activeCamera.position.clone();
  106183. }
  106184. else {
  106185. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106186. }
  106187. // Set non-vr camera
  106188. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106189. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106190. // Copy data from existing camera
  106191. if (this._scene.activeCamera) {
  106192. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106193. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106194. // Set rotation from previous camera
  106195. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106196. var targetCamera = this._scene.activeCamera;
  106197. if (targetCamera.rotationQuaternion) {
  106198. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106199. }
  106200. else {
  106201. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106202. }
  106203. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106204. }
  106205. }
  106206. this._scene.activeCamera = this._deviceOrientationCamera;
  106207. if (this._canvas) {
  106208. this._scene.activeCamera.attachControl(this._canvas);
  106209. }
  106210. }
  106211. else {
  106212. this._existingCamera = this._scene.activeCamera;
  106213. }
  106214. // Create VR cameras
  106215. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106216. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106217. }
  106218. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106219. this._webVRCamera.useStandingMatrix();
  106220. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106221. // Create default button
  106222. if (!this._useCustomVRButton) {
  106223. this._btnVR = document.createElement("BUTTON");
  106224. this._btnVR.className = "babylonVRicon";
  106225. this._btnVR.id = "babylonVRiconbtn";
  106226. this._btnVR.title = "Click to switch to VR";
  106227. 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) }";
  106228. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106229. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106230. // css += ".babylonVRicon.vrdisplaysupported { }";
  106231. // css += ".babylonVRicon.vrdisplayready { }";
  106232. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106233. var style = document.createElement('style');
  106234. style.appendChild(document.createTextNode(css));
  106235. document.getElementsByTagName('head')[0].appendChild(style);
  106236. this.moveButtonToBottomRight();
  106237. }
  106238. // VR button click event
  106239. if (this._btnVR) {
  106240. this._btnVR.addEventListener("click", function () {
  106241. if (!_this.isInVRMode) {
  106242. _this.enterVR();
  106243. }
  106244. else {
  106245. _this.exitVR();
  106246. }
  106247. });
  106248. }
  106249. // Window events
  106250. window.addEventListener("resize", this._onResize);
  106251. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106252. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106253. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106254. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106255. document.onmsfullscreenchange = this._onFullscreenChange;
  106256. // Display vr button when headset is connected
  106257. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106258. this.displayVRButton();
  106259. }
  106260. else {
  106261. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106262. if (e.vrDisplay) {
  106263. _this.displayVRButton();
  106264. }
  106265. });
  106266. }
  106267. // Exiting VR mode using 'ESC' key on desktop
  106268. this._onKeyDown = function (event) {
  106269. if (event.keyCode === 27 && _this.isInVRMode) {
  106270. _this.exitVR();
  106271. }
  106272. };
  106273. document.addEventListener("keydown", this._onKeyDown);
  106274. // Exiting VR mode double tapping the touch screen
  106275. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106276. if (_this.isInVRMode) {
  106277. _this.exitVR();
  106278. if (_this._fullscreenVRpresenting) {
  106279. _this._scene.getEngine().switchFullscreen(true);
  106280. }
  106281. }
  106282. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106283. // Listen for WebVR display changes
  106284. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106285. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106286. this._onVRRequestPresentStart = function () {
  106287. _this._webVRrequesting = true;
  106288. _this.updateButtonVisibility();
  106289. };
  106290. this._onVRRequestPresentComplete = function (success) {
  106291. _this._webVRrequesting = false;
  106292. _this.updateButtonVisibility();
  106293. };
  106294. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106295. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106296. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106297. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106298. scene.onDisposeObservable.add(function () {
  106299. _this.dispose();
  106300. });
  106301. // Gamepad connection events
  106302. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106303. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106304. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106305. this.updateButtonVisibility();
  106306. //create easing functions
  106307. this._circleEase = new BABYLON.CircleEase();
  106308. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106309. if (this.webVROptions.floorMeshes) {
  106310. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106311. }
  106312. }
  106313. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106314. /** Return this.onEnteringVRObservable
  106315. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106316. */
  106317. get: function () {
  106318. return this.onEnteringVRObservable;
  106319. },
  106320. enumerable: true,
  106321. configurable: true
  106322. });
  106323. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106324. /** Return this.onExitingVRObservable
  106325. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106326. */
  106327. get: function () {
  106328. return this.onExitingVRObservable;
  106329. },
  106330. enumerable: true,
  106331. configurable: true
  106332. });
  106333. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106334. /** Return this.onControllerMeshLoadedObservable
  106335. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106336. */
  106337. get: function () {
  106338. return this.onControllerMeshLoadedObservable;
  106339. },
  106340. enumerable: true,
  106341. configurable: true
  106342. });
  106343. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106344. /**
  106345. * The mesh used to display where the user is going to teleport.
  106346. */
  106347. get: function () {
  106348. return this._teleportationTarget;
  106349. },
  106350. /**
  106351. * Sets the mesh to be used to display where the user is going to teleport.
  106352. */
  106353. set: function (value) {
  106354. if (value) {
  106355. value.name = "teleportationTarget";
  106356. this._isDefaultTeleportationTarget = false;
  106357. this._teleportationTarget = value;
  106358. }
  106359. },
  106360. enumerable: true,
  106361. configurable: true
  106362. });
  106363. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106364. /**
  106365. * 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
  106366. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106367. * See http://doc.babylonjs.com/resources/baking_transformations
  106368. */
  106369. get: function () {
  106370. return this._cameraGazer._gazeTracker;
  106371. },
  106372. set: function (value) {
  106373. if (value) {
  106374. // Dispose of existing meshes
  106375. if (this._cameraGazer._gazeTracker) {
  106376. this._cameraGazer._gazeTracker.dispose();
  106377. }
  106378. if (this._leftController && this._leftController._gazeTracker) {
  106379. this._leftController._gazeTracker.dispose();
  106380. }
  106381. if (this._rightController && this._rightController._gazeTracker) {
  106382. this._rightController._gazeTracker.dispose();
  106383. }
  106384. // Set and create gaze trackers on head and controllers
  106385. this._cameraGazer._gazeTracker = value;
  106386. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  106387. this._cameraGazer._gazeTracker.isPickable = false;
  106388. this._cameraGazer._gazeTracker.isVisible = false;
  106389. this._cameraGazer._gazeTracker.name = "gazeTracker";
  106390. if (this._leftController) {
  106391. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106392. }
  106393. if (this._rightController) {
  106394. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106395. }
  106396. }
  106397. },
  106398. enumerable: true,
  106399. configurable: true
  106400. });
  106401. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  106402. /**
  106403. * The gaze tracking mesh corresponding to the left controller
  106404. */
  106405. get: function () {
  106406. if (this._leftController) {
  106407. return this._leftController._gazeTracker;
  106408. }
  106409. return null;
  106410. },
  106411. enumerable: true,
  106412. configurable: true
  106413. });
  106414. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  106415. /**
  106416. * The gaze tracking mesh corresponding to the right controller
  106417. */
  106418. get: function () {
  106419. if (this._rightController) {
  106420. return this._rightController._gazeTracker;
  106421. }
  106422. return null;
  106423. },
  106424. enumerable: true,
  106425. configurable: true
  106426. });
  106427. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  106428. /**
  106429. * If the ray of the gaze should be displayed.
  106430. */
  106431. get: function () {
  106432. return this._displayGaze;
  106433. },
  106434. /**
  106435. * Sets if the ray of the gaze should be displayed.
  106436. */
  106437. set: function (value) {
  106438. this._displayGaze = value;
  106439. if (!value) {
  106440. this._cameraGazer._gazeTracker.isVisible = false;
  106441. if (this._leftController) {
  106442. this._leftController._gazeTracker.isVisible = false;
  106443. }
  106444. if (this._rightController) {
  106445. this._rightController._gazeTracker.isVisible = false;
  106446. }
  106447. }
  106448. },
  106449. enumerable: true,
  106450. configurable: true
  106451. });
  106452. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  106453. /**
  106454. * If the ray of the LaserPointer should be displayed.
  106455. */
  106456. get: function () {
  106457. return this._displayLaserPointer;
  106458. },
  106459. /**
  106460. * Sets if the ray of the LaserPointer should be displayed.
  106461. */
  106462. set: function (value) {
  106463. this._displayLaserPointer = value;
  106464. if (!value) {
  106465. if (this._rightController) {
  106466. this._rightController._deactivatePointer();
  106467. this._rightController._gazeTracker.isVisible = false;
  106468. }
  106469. if (this._leftController) {
  106470. this._leftController._deactivatePointer();
  106471. this._leftController._gazeTracker.isVisible = false;
  106472. }
  106473. }
  106474. else {
  106475. if (this._rightController) {
  106476. this._rightController._activatePointer();
  106477. }
  106478. if (this._leftController) {
  106479. this._leftController._activatePointer();
  106480. }
  106481. }
  106482. },
  106483. enumerable: true,
  106484. configurable: true
  106485. });
  106486. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  106487. /**
  106488. * The deviceOrientationCamera used as the camera when not in VR.
  106489. */
  106490. get: function () {
  106491. return this._deviceOrientationCamera;
  106492. },
  106493. enumerable: true,
  106494. configurable: true
  106495. });
  106496. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  106497. /**
  106498. * Based on the current WebVR support, returns the current VR camera used.
  106499. */
  106500. get: function () {
  106501. if (this._webVRready) {
  106502. return this._webVRCamera;
  106503. }
  106504. else {
  106505. return this._scene.activeCamera;
  106506. }
  106507. },
  106508. enumerable: true,
  106509. configurable: true
  106510. });
  106511. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  106512. /**
  106513. * The webVRCamera which is used when in VR.
  106514. */
  106515. get: function () {
  106516. return this._webVRCamera;
  106517. },
  106518. enumerable: true,
  106519. configurable: true
  106520. });
  106521. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  106522. /**
  106523. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  106524. */
  106525. get: function () {
  106526. return this._vrDeviceOrientationCamera;
  106527. },
  106528. enumerable: true,
  106529. configurable: true
  106530. });
  106531. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  106532. get: function () {
  106533. var result = this._cameraGazer._teleportationRequestInitiated
  106534. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  106535. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  106536. return result;
  106537. },
  106538. enumerable: true,
  106539. configurable: true
  106540. });
  106541. // Raised when one of the controller has loaded successfully its associated default mesh
  106542. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  106543. if (this._leftController && this._leftController.webVRController == webVRController) {
  106544. if (webVRController.mesh) {
  106545. this._leftController._setLaserPointerParent(webVRController.mesh);
  106546. }
  106547. }
  106548. if (this._rightController && this._rightController.webVRController == webVRController) {
  106549. if (webVRController.mesh) {
  106550. this._rightController._setLaserPointerParent(webVRController.mesh);
  106551. }
  106552. }
  106553. try {
  106554. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  106555. }
  106556. catch (err) {
  106557. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  106558. }
  106559. };
  106560. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  106561. /**
  106562. * Gets a value indicating if we are currently in VR mode.
  106563. */
  106564. get: function () {
  106565. return this._webVRpresenting || this._fullscreenVRpresenting;
  106566. },
  106567. enumerable: true,
  106568. configurable: true
  106569. });
  106570. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  106571. var vrDisplay = this._scene.getEngine().getVRDevice();
  106572. if (vrDisplay) {
  106573. var wasPresenting = this._webVRpresenting;
  106574. this._webVRpresenting = vrDisplay.isPresenting;
  106575. if (wasPresenting && !this._webVRpresenting) {
  106576. this.exitVR();
  106577. }
  106578. }
  106579. else {
  106580. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  106581. }
  106582. this.updateButtonVisibility();
  106583. };
  106584. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  106585. this._webVRsupported = eventArgs.vrSupported;
  106586. this._webVRready = !!eventArgs.vrDisplay;
  106587. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  106588. this.updateButtonVisibility();
  106589. };
  106590. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  106591. if (this._canvas && !this._useCustomVRButton) {
  106592. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  106593. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  106594. }
  106595. };
  106596. VRExperienceHelper.prototype.displayVRButton = function () {
  106597. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  106598. document.body.appendChild(this._btnVR);
  106599. this._btnVRDisplayed = true;
  106600. }
  106601. };
  106602. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  106603. if (!this._btnVR || this._useCustomVRButton) {
  106604. return;
  106605. }
  106606. this._btnVR.className = "babylonVRicon";
  106607. if (this.isInVRMode) {
  106608. this._btnVR.className += " vrdisplaypresenting";
  106609. }
  106610. else {
  106611. if (this._webVRready) {
  106612. this._btnVR.className += " vrdisplayready";
  106613. }
  106614. if (this._webVRsupported) {
  106615. this._btnVR.className += " vrdisplaysupported";
  106616. }
  106617. if (this._webVRrequesting) {
  106618. this._btnVR.className += " vrdisplayrequesting";
  106619. }
  106620. }
  106621. };
  106622. /**
  106623. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  106624. * Otherwise, will use the fullscreen API.
  106625. */
  106626. VRExperienceHelper.prototype.enterVR = function () {
  106627. if (this.onEnteringVRObservable) {
  106628. try {
  106629. this.onEnteringVRObservable.notifyObservers(this);
  106630. }
  106631. catch (err) {
  106632. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  106633. }
  106634. }
  106635. if (this._scene.activeCamera) {
  106636. this._position = this._scene.activeCamera.position.clone();
  106637. // make sure that we return to the last active camera
  106638. this._existingCamera = this._scene.activeCamera;
  106639. }
  106640. if (this._webVRrequesting) {
  106641. return;
  106642. }
  106643. // If WebVR is supported and a headset is connected
  106644. if (this._webVRready) {
  106645. if (!this._webVRpresenting) {
  106646. this._webVRCamera.position = this._position;
  106647. this._scene.activeCamera = this._webVRCamera;
  106648. }
  106649. }
  106650. else if (this._vrDeviceOrientationCamera) {
  106651. this._vrDeviceOrientationCamera.position = this._position;
  106652. if (this._scene.activeCamera) {
  106653. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106654. }
  106655. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  106656. this._scene.getEngine().switchFullscreen(true);
  106657. this.updateButtonVisibility();
  106658. }
  106659. if (this._scene.activeCamera && this._canvas) {
  106660. this._scene.activeCamera.attachControl(this._canvas);
  106661. }
  106662. if (this._interactionsEnabled) {
  106663. this._scene.registerBeforeRender(this.beforeRender);
  106664. }
  106665. this._hasEnteredVR = true;
  106666. };
  106667. /**
  106668. * Attempt to exit VR, or fullscreen.
  106669. */
  106670. VRExperienceHelper.prototype.exitVR = function () {
  106671. if (this._hasEnteredVR) {
  106672. if (this.onExitingVRObservable) {
  106673. try {
  106674. this.onExitingVRObservable.notifyObservers(this);
  106675. }
  106676. catch (err) {
  106677. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  106678. }
  106679. }
  106680. if (this._webVRpresenting) {
  106681. this._scene.getEngine().disableVR();
  106682. }
  106683. if (this._scene.activeCamera) {
  106684. this._position = this._scene.activeCamera.position.clone();
  106685. }
  106686. if (this._deviceOrientationCamera) {
  106687. this._deviceOrientationCamera.position = this._position;
  106688. this._scene.activeCamera = this._deviceOrientationCamera;
  106689. if (this._canvas) {
  106690. this._scene.activeCamera.attachControl(this._canvas);
  106691. }
  106692. }
  106693. else if (this._existingCamera) {
  106694. this._existingCamera.position = this._position;
  106695. this._scene.activeCamera = this._existingCamera;
  106696. }
  106697. this.updateButtonVisibility();
  106698. if (this._interactionsEnabled) {
  106699. this._scene.unregisterBeforeRender(this.beforeRender);
  106700. this._cameraGazer._gazeTracker.isVisible = false;
  106701. if (this._leftController) {
  106702. this._leftController._gazeTracker.isVisible = false;
  106703. }
  106704. if (this._rightController) {
  106705. this._rightController._gazeTracker.isVisible = false;
  106706. }
  106707. }
  106708. // resize to update width and height when exiting vr exits fullscreen
  106709. this._scene.getEngine().resize();
  106710. this._hasEnteredVR = false;
  106711. }
  106712. };
  106713. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  106714. /**
  106715. * The position of the vr experience helper.
  106716. */
  106717. get: function () {
  106718. return this._position;
  106719. },
  106720. /**
  106721. * Sets the position of the vr experience helper.
  106722. */
  106723. set: function (value) {
  106724. this._position = value;
  106725. if (this._scene.activeCamera) {
  106726. this._scene.activeCamera.position = value;
  106727. }
  106728. },
  106729. enumerable: true,
  106730. configurable: true
  106731. });
  106732. /**
  106733. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  106734. */
  106735. VRExperienceHelper.prototype.enableInteractions = function () {
  106736. var _this = this;
  106737. if (!this._interactionsEnabled) {
  106738. this._interactionsRequested = true;
  106739. if (this._leftController) {
  106740. this._enableInteractionOnController(this._leftController);
  106741. }
  106742. if (this._rightController) {
  106743. this._enableInteractionOnController(this._rightController);
  106744. }
  106745. this.raySelectionPredicate = function (mesh) {
  106746. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  106747. };
  106748. this.meshSelectionPredicate = function (mesh) {
  106749. return true;
  106750. };
  106751. this._raySelectionPredicate = function (mesh) {
  106752. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  106753. && mesh.name.indexOf("teleportationTarget") === -1
  106754. && mesh.name.indexOf("torusTeleportation") === -1)) {
  106755. return _this.raySelectionPredicate(mesh);
  106756. }
  106757. return false;
  106758. };
  106759. this._interactionsEnabled = true;
  106760. }
  106761. };
  106762. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  106763. get: function () {
  106764. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  106765. },
  106766. enumerable: true,
  106767. configurable: true
  106768. });
  106769. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  106770. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  106771. if (this._floorMeshesCollection[i].id === mesh.id) {
  106772. return true;
  106773. }
  106774. }
  106775. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  106776. return true;
  106777. }
  106778. return false;
  106779. };
  106780. /**
  106781. * Adds a floor mesh to be used for teleportation.
  106782. * @param floorMesh the mesh to be used for teleportation.
  106783. */
  106784. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  106785. if (!this._floorMeshesCollection) {
  106786. return;
  106787. }
  106788. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  106789. return;
  106790. }
  106791. this._floorMeshesCollection.push(floorMesh);
  106792. };
  106793. /**
  106794. * Removes a floor mesh from being used for teleportation.
  106795. * @param floorMesh the mesh to be removed.
  106796. */
  106797. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  106798. if (!this._floorMeshesCollection) {
  106799. return;
  106800. }
  106801. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  106802. if (meshIndex !== -1) {
  106803. this._floorMeshesCollection.splice(meshIndex, 1);
  106804. }
  106805. };
  106806. /**
  106807. * Enables interactions and teleportation using the VR controllers and gaze.
  106808. * @param vrTeleportationOptions options to modify teleportation behavior.
  106809. */
  106810. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  106811. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  106812. if (!this._teleportationInitialized) {
  106813. this._teleportationRequested = true;
  106814. this.enableInteractions();
  106815. if (vrTeleportationOptions.floorMeshName) {
  106816. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  106817. }
  106818. if (vrTeleportationOptions.floorMeshes) {
  106819. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  106820. }
  106821. if (this._leftController != null) {
  106822. this._enableTeleportationOnController(this._leftController);
  106823. }
  106824. if (this._rightController != null) {
  106825. this._enableTeleportationOnController(this._rightController);
  106826. }
  106827. // Creates an image processing post process for the vignette not relying
  106828. // on the main scene configuration for image processing to reduce setup and spaces
  106829. // (gamma/linear) conflicts.
  106830. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  106831. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  106832. imageProcessingConfiguration.vignetteEnabled = true;
  106833. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  106834. this._webVRCamera.detachPostProcess(this._postProcessMove);
  106835. this._teleportationInitialized = true;
  106836. if (this._isDefaultTeleportationTarget) {
  106837. this._createTeleportationCircles();
  106838. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  106839. }
  106840. }
  106841. };
  106842. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  106843. var _this = this;
  106844. var controllerMesh = controller.webVRController.mesh;
  106845. if (controllerMesh) {
  106846. controller._interactionsEnabled = true;
  106847. controller._activatePointer();
  106848. if (this.webVROptions.laserToggle) {
  106849. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  106850. // Enabling / disabling laserPointer
  106851. if (_this._displayLaserPointer && stateObject.value === 1) {
  106852. if (controller._activePointer) {
  106853. controller._deactivatePointer();
  106854. }
  106855. else {
  106856. controller._activatePointer();
  106857. }
  106858. if (_this.displayGaze) {
  106859. controller._gazeTracker.isVisible = controller._activePointer;
  106860. }
  106861. }
  106862. });
  106863. }
  106864. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  106865. var gazer = controller;
  106866. if (_this._noControllerIsActive) {
  106867. gazer = _this._cameraGazer;
  106868. }
  106869. if (!gazer._pointerDownOnMeshAsked) {
  106870. if (stateObject.value > _this._padSensibilityUp) {
  106871. gazer._selectionPointerDown();
  106872. }
  106873. }
  106874. else if (stateObject.value < _this._padSensibilityDown) {
  106875. gazer._selectionPointerUp();
  106876. }
  106877. });
  106878. }
  106879. };
  106880. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  106881. // Dont teleport if another gaze already requested teleportation
  106882. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  106883. return;
  106884. }
  106885. if (!gazer._teleportationRequestInitiated) {
  106886. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  106887. gazer._activatePointer();
  106888. gazer._teleportationRequestInitiated = true;
  106889. }
  106890. }
  106891. else {
  106892. // Listening to the proper controller values changes to confirm teleportation
  106893. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  106894. if (this._teleportActive) {
  106895. this.teleportCamera(this._haloCenter);
  106896. }
  106897. gazer._teleportationRequestInitiated = false;
  106898. }
  106899. }
  106900. };
  106901. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  106902. // Only rotate when user is not currently selecting a teleportation location
  106903. if (gazer._teleportationRequestInitiated) {
  106904. return;
  106905. }
  106906. if (!gazer._rotationLeftAsked) {
  106907. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  106908. gazer._rotationLeftAsked = true;
  106909. if (this._rotationAllowed) {
  106910. this._rotateCamera(false);
  106911. }
  106912. }
  106913. }
  106914. else {
  106915. if (stateObject.x > -this._padSensibilityDown) {
  106916. gazer._rotationLeftAsked = false;
  106917. }
  106918. }
  106919. if (!gazer._rotationRightAsked) {
  106920. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  106921. gazer._rotationRightAsked = true;
  106922. if (this._rotationAllowed) {
  106923. this._rotateCamera(true);
  106924. }
  106925. }
  106926. }
  106927. else {
  106928. if (stateObject.x < this._padSensibilityDown) {
  106929. gazer._rotationRightAsked = false;
  106930. }
  106931. }
  106932. };
  106933. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  106934. // Only teleport backwards when user is not currently selecting a teleportation location
  106935. if (gazer._teleportationRequestInitiated) {
  106936. return;
  106937. }
  106938. // Teleport backwards
  106939. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  106940. if (!gazer._teleportationBackRequestInitiated) {
  106941. if (!this.currentVRCamera) {
  106942. return;
  106943. }
  106944. // Get rotation and position of the current camera
  106945. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  106946. var position = this.currentVRCamera.position;
  106947. // If the camera has device position, use that instead
  106948. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  106949. rotation = this.currentVRCamera.deviceRotationQuaternion;
  106950. position = this.currentVRCamera.devicePosition;
  106951. }
  106952. // Get matrix with only the y rotation of the device rotation
  106953. rotation.toEulerAnglesToRef(this._workingVector);
  106954. this._workingVector.z = 0;
  106955. this._workingVector.x = 0;
  106956. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  106957. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  106958. // Rotate backwards ray by device rotation to cast at the ground behind the user
  106959. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  106960. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  106961. var ray = new BABYLON.Ray(position, this._workingVector);
  106962. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  106963. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  106964. this.teleportCamera(hit.pickedPoint);
  106965. }
  106966. gazer._teleportationBackRequestInitiated = true;
  106967. }
  106968. }
  106969. else {
  106970. gazer._teleportationBackRequestInitiated = false;
  106971. }
  106972. };
  106973. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  106974. var _this = this;
  106975. var controllerMesh = controller.webVRController.mesh;
  106976. if (controllerMesh) {
  106977. if (!controller._interactionsEnabled) {
  106978. this._enableInteractionOnController(controller);
  106979. }
  106980. controller._interactionsEnabled = true;
  106981. controller._teleportationEnabled = true;
  106982. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  106983. controller._dpadPressed = false;
  106984. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  106985. controller._dpadPressed = stateObject.pressed;
  106986. if (!controller._dpadPressed) {
  106987. controller._rotationLeftAsked = false;
  106988. controller._rotationRightAsked = false;
  106989. controller._teleportationBackRequestInitiated = false;
  106990. }
  106991. });
  106992. }
  106993. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  106994. if (_this.teleportationEnabled) {
  106995. _this._checkTeleportBackwards(stateObject, controller);
  106996. _this._checkTeleportWithRay(stateObject, controller);
  106997. }
  106998. _this._checkRotate(stateObject, controller);
  106999. });
  107000. }
  107001. };
  107002. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  107003. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  107004. this._teleportationTarget.isPickable = false;
  107005. var length = 512;
  107006. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107007. dynamicTexture.hasAlpha = true;
  107008. var context = dynamicTexture.getContext();
  107009. var centerX = length / 2;
  107010. var centerY = length / 2;
  107011. var radius = 200;
  107012. context.beginPath();
  107013. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107014. context.fillStyle = this._teleportationFillColor;
  107015. context.fill();
  107016. context.lineWidth = 10;
  107017. context.strokeStyle = this._teleportationBorderColor;
  107018. context.stroke();
  107019. context.closePath();
  107020. dynamicTexture.update();
  107021. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107022. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107023. this._teleportationTarget.material = teleportationCircleMaterial;
  107024. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107025. torus.isPickable = false;
  107026. torus.parent = this._teleportationTarget;
  107027. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107028. var keys = [];
  107029. keys.push({
  107030. frame: 0,
  107031. value: 0
  107032. });
  107033. keys.push({
  107034. frame: 30,
  107035. value: 0.4
  107036. });
  107037. keys.push({
  107038. frame: 60,
  107039. value: 0
  107040. });
  107041. animationInnerCircle.setKeys(keys);
  107042. var easingFunction = new BABYLON.SineEase();
  107043. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107044. animationInnerCircle.setEasingFunction(easingFunction);
  107045. torus.animations = [];
  107046. torus.animations.push(animationInnerCircle);
  107047. this._scene.beginAnimation(torus, 0, 60, true);
  107048. this._hideTeleportationTarget();
  107049. };
  107050. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107051. this._teleportActive = true;
  107052. if (this._teleportationInitialized) {
  107053. this._teleportationTarget.isVisible = true;
  107054. if (this._isDefaultTeleportationTarget) {
  107055. this._teleportationTarget.getChildren()[0].isVisible = true;
  107056. }
  107057. }
  107058. };
  107059. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107060. this._teleportActive = false;
  107061. if (this._teleportationInitialized) {
  107062. this._teleportationTarget.isVisible = false;
  107063. if (this._isDefaultTeleportationTarget) {
  107064. this._teleportationTarget.getChildren()[0].isVisible = false;
  107065. }
  107066. }
  107067. };
  107068. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107069. var _this = this;
  107070. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107071. return;
  107072. }
  107073. if (right) {
  107074. this._rotationAngle++;
  107075. }
  107076. else {
  107077. this._rotationAngle--;
  107078. }
  107079. this.currentVRCamera.animations = [];
  107080. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107081. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107082. var animationRotationKeys = [];
  107083. animationRotationKeys.push({
  107084. frame: 0,
  107085. value: this.currentVRCamera.rotationQuaternion
  107086. });
  107087. animationRotationKeys.push({
  107088. frame: 6,
  107089. value: target
  107090. });
  107091. animationRotation.setKeys(animationRotationKeys);
  107092. animationRotation.setEasingFunction(this._circleEase);
  107093. this.currentVRCamera.animations.push(animationRotation);
  107094. this._postProcessMove.animations = [];
  107095. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107096. var vignetteWeightKeys = [];
  107097. vignetteWeightKeys.push({
  107098. frame: 0,
  107099. value: 0
  107100. });
  107101. vignetteWeightKeys.push({
  107102. frame: 3,
  107103. value: 4
  107104. });
  107105. vignetteWeightKeys.push({
  107106. frame: 6,
  107107. value: 0
  107108. });
  107109. animationPP.setKeys(vignetteWeightKeys);
  107110. animationPP.setEasingFunction(this._circleEase);
  107111. this._postProcessMove.animations.push(animationPP);
  107112. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107113. var vignetteStretchKeys = [];
  107114. vignetteStretchKeys.push({
  107115. frame: 0,
  107116. value: 0
  107117. });
  107118. vignetteStretchKeys.push({
  107119. frame: 3,
  107120. value: 10
  107121. });
  107122. vignetteStretchKeys.push({
  107123. frame: 6,
  107124. value: 0
  107125. });
  107126. animationPP2.setKeys(vignetteStretchKeys);
  107127. animationPP2.setEasingFunction(this._circleEase);
  107128. this._postProcessMove.animations.push(animationPP2);
  107129. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107130. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107131. this._postProcessMove.samples = 4;
  107132. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107133. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107134. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107135. });
  107136. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107137. };
  107138. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107139. if (hit.pickedPoint) {
  107140. if (gazer._teleportationRequestInitiated) {
  107141. this._displayTeleportationTarget();
  107142. this._haloCenter.copyFrom(hit.pickedPoint);
  107143. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107144. }
  107145. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107146. if (pickNormal) {
  107147. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107148. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107149. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107150. }
  107151. this._teleportationTarget.position.y += 0.1;
  107152. }
  107153. };
  107154. /**
  107155. * Teleports the users feet to the desired location
  107156. * @param location The location where the user's feet should be placed
  107157. */
  107158. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107159. var _this = this;
  107160. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107161. return;
  107162. }
  107163. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107164. // offset of the headset from the anchor.
  107165. if (this.webVRCamera.leftCamera) {
  107166. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107167. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107168. location.subtractToRef(this._workingVector, this._workingVector);
  107169. }
  107170. else {
  107171. this._workingVector.copyFrom(location);
  107172. }
  107173. // Add height to account for user's height offset
  107174. if (this.isInVRMode) {
  107175. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107176. }
  107177. else {
  107178. this._workingVector.y += this._defaultHeight;
  107179. }
  107180. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107181. // Create animation from the camera's position to the new location
  107182. this.currentVRCamera.animations = [];
  107183. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107184. var animationCameraTeleportationKeys = [{
  107185. frame: 0,
  107186. value: this.currentVRCamera.position
  107187. },
  107188. {
  107189. frame: 11,
  107190. value: this._workingVector
  107191. }
  107192. ];
  107193. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107194. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107195. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107196. this._postProcessMove.animations = [];
  107197. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107198. var vignetteWeightKeys = [];
  107199. vignetteWeightKeys.push({
  107200. frame: 0,
  107201. value: 0
  107202. });
  107203. vignetteWeightKeys.push({
  107204. frame: 5,
  107205. value: 8
  107206. });
  107207. vignetteWeightKeys.push({
  107208. frame: 11,
  107209. value: 0
  107210. });
  107211. animationPP.setKeys(vignetteWeightKeys);
  107212. this._postProcessMove.animations.push(animationPP);
  107213. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107214. var vignetteStretchKeys = [];
  107215. vignetteStretchKeys.push({
  107216. frame: 0,
  107217. value: 0
  107218. });
  107219. vignetteStretchKeys.push({
  107220. frame: 5,
  107221. value: 10
  107222. });
  107223. vignetteStretchKeys.push({
  107224. frame: 11,
  107225. value: 0
  107226. });
  107227. animationPP2.setKeys(vignetteStretchKeys);
  107228. this._postProcessMove.animations.push(animationPP2);
  107229. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107230. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107231. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107232. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107233. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107234. });
  107235. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107236. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107237. });
  107238. this._hideTeleportationTarget();
  107239. };
  107240. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107241. if (normal) {
  107242. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107243. if (angle < Math.PI / 2) {
  107244. normal.scaleInPlace(-1);
  107245. }
  107246. }
  107247. return normal;
  107248. };
  107249. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107250. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107251. return;
  107252. }
  107253. var ray = gazer._getForwardRay(this._rayLength);
  107254. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107255. if (hit) {
  107256. // Populate the contrllers mesh that can be used for drag/drop
  107257. if (gazer._laserPointer) {
  107258. hit.originMesh = gazer._laserPointer.parent;
  107259. }
  107260. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107261. }
  107262. gazer._currentHit = hit;
  107263. // Moving the gazeTracker on the mesh face targetted
  107264. if (hit && hit.pickedPoint) {
  107265. if (this._displayGaze) {
  107266. var multiplier = 1;
  107267. gazer._gazeTracker.isVisible = true;
  107268. if (gazer._isActionableMesh) {
  107269. multiplier = 3;
  107270. }
  107271. if (this.updateGazeTrackerScale) {
  107272. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107273. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107274. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107275. }
  107276. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107277. // To avoid z-fighting
  107278. var deltaFighting = 0.002;
  107279. if (pickNormal) {
  107280. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107281. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107282. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107283. }
  107284. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107285. if (gazer._gazeTracker.position.x < 0) {
  107286. gazer._gazeTracker.position.x += deltaFighting;
  107287. }
  107288. else {
  107289. gazer._gazeTracker.position.x -= deltaFighting;
  107290. }
  107291. if (gazer._gazeTracker.position.y < 0) {
  107292. gazer._gazeTracker.position.y += deltaFighting;
  107293. }
  107294. else {
  107295. gazer._gazeTracker.position.y -= deltaFighting;
  107296. }
  107297. if (gazer._gazeTracker.position.z < 0) {
  107298. gazer._gazeTracker.position.z += deltaFighting;
  107299. }
  107300. else {
  107301. gazer._gazeTracker.position.z -= deltaFighting;
  107302. }
  107303. }
  107304. // Changing the size of the laser pointer based on the distance from the targetted point
  107305. gazer._updatePointerDistance(hit.distance);
  107306. }
  107307. else {
  107308. gazer._updatePointerDistance();
  107309. gazer._gazeTracker.isVisible = false;
  107310. }
  107311. if (hit && hit.pickedMesh) {
  107312. // The object selected is the floor, we're in a teleportation scenario
  107313. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107314. // Moving the teleportation area to this targetted point
  107315. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107316. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107317. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107318. }
  107319. gazer._currentMeshSelected = null;
  107320. if (gazer._teleportationRequestInitiated) {
  107321. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107322. }
  107323. return;
  107324. }
  107325. // If not, we're in a selection scenario
  107326. //this._teleportationAllowed = false;
  107327. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107328. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  107329. this.onNewMeshPicked.notifyObservers(hit);
  107330. gazer._currentMeshSelected = hit.pickedMesh;
  107331. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  107332. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  107333. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  107334. gazer._isActionableMesh = true;
  107335. }
  107336. else {
  107337. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107338. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107339. gazer._isActionableMesh = false;
  107340. }
  107341. try {
  107342. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  107343. }
  107344. catch (err) {
  107345. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  107346. }
  107347. }
  107348. else {
  107349. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107350. gazer._currentMeshSelected = null;
  107351. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107352. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107353. }
  107354. }
  107355. }
  107356. else {
  107357. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107358. gazer._currentMeshSelected = null;
  107359. //this._teleportationAllowed = false;
  107360. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107361. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107362. }
  107363. };
  107364. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  107365. if (mesh) {
  107366. this.onSelectedMeshUnselected.notifyObservers(mesh);
  107367. }
  107368. };
  107369. /**
  107370. * Sets the color of the laser ray from the vr controllers.
  107371. * @param color new color for the ray.
  107372. */
  107373. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  107374. if (this._leftController) {
  107375. this._leftController._setLaserPointerColor(color);
  107376. }
  107377. if (this._rightController) {
  107378. this._rightController._setLaserPointerColor(color);
  107379. }
  107380. };
  107381. /**
  107382. * Sets the color of the ray from the vr headsets gaze.
  107383. * @param color new color for the ray.
  107384. */
  107385. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  107386. if (!this._cameraGazer._gazeTracker.material) {
  107387. return;
  107388. }
  107389. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  107390. if (this._leftController) {
  107391. this._leftController._gazeTracker.material.emissiveColor = color;
  107392. }
  107393. if (this._rightController) {
  107394. this._rightController._gazeTracker.material.emissiveColor = color;
  107395. }
  107396. };
  107397. /**
  107398. * Exits VR and disposes of the vr experience helper
  107399. */
  107400. VRExperienceHelper.prototype.dispose = function () {
  107401. if (this.isInVRMode) {
  107402. this.exitVR();
  107403. }
  107404. if (this._postProcessMove) {
  107405. this._postProcessMove.dispose();
  107406. }
  107407. if (this._webVRCamera) {
  107408. this._webVRCamera.dispose();
  107409. }
  107410. if (this._vrDeviceOrientationCamera) {
  107411. this._vrDeviceOrientationCamera.dispose();
  107412. }
  107413. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  107414. document.body.removeChild(this._btnVR);
  107415. }
  107416. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  107417. this._deviceOrientationCamera.dispose();
  107418. }
  107419. if (this._cameraGazer) {
  107420. this._cameraGazer.dispose();
  107421. }
  107422. if (this._leftController) {
  107423. this._leftController.dispose();
  107424. }
  107425. if (this._rightController) {
  107426. this._rightController.dispose();
  107427. }
  107428. if (this._teleportationTarget) {
  107429. this._teleportationTarget.dispose();
  107430. }
  107431. this._floorMeshesCollection = [];
  107432. document.removeEventListener("keydown", this._onKeyDown);
  107433. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107434. window.removeEventListener("resize", this._onResize);
  107435. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  107436. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  107437. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  107438. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  107439. document.onmsfullscreenchange = null;
  107440. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  107441. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  107442. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  107443. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107444. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  107445. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  107446. this._scene.unregisterBeforeRender(this.beforeRender);
  107447. };
  107448. /**
  107449. * Gets the name of the VRExperienceHelper class
  107450. * @returns "VRExperienceHelper"
  107451. */
  107452. VRExperienceHelper.prototype.getClassName = function () {
  107453. return "VRExperienceHelper";
  107454. };
  107455. return VRExperienceHelper;
  107456. }());
  107457. BABYLON.VRExperienceHelper = VRExperienceHelper;
  107458. })(BABYLON || (BABYLON = {}));
  107459. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  107460. var BABYLON;
  107461. (function (BABYLON) {
  107462. /**
  107463. * WebXR Camera which holds the views for the xrSession
  107464. * @see https://doc.babylonjs.com/how_to/webxr
  107465. */
  107466. var WebXRCamera = /** @class */ (function (_super) {
  107467. __extends(WebXRCamera, _super);
  107468. /**
  107469. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  107470. * @param name the name of the camera
  107471. * @param scene the scene to add the camera to
  107472. */
  107473. function WebXRCamera(name, scene) {
  107474. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  107475. // Initial camera configuration
  107476. _this.minZ = 0;
  107477. _this.rotationQuaternion = new BABYLON.Quaternion();
  107478. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  107479. _this._updateNumberOfRigCameras(1);
  107480. return _this;
  107481. }
  107482. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  107483. if (viewCount === void 0) { viewCount = 1; }
  107484. while (this.rigCameras.length < viewCount) {
  107485. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  107486. newCamera.minZ = 0;
  107487. newCamera.parent = this;
  107488. this.rigCameras.push(newCamera);
  107489. }
  107490. while (this.rigCameras.length > viewCount) {
  107491. var removedCamera = this.rigCameras.pop();
  107492. if (removedCamera) {
  107493. removedCamera.dispose();
  107494. }
  107495. }
  107496. };
  107497. /** @hidden */
  107498. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  107499. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  107500. // Create initial camera rigs
  107501. this._updateNumberOfRigCameras(2);
  107502. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  107503. this.rigCameras[0].position.x = -pupilDistance / 2;
  107504. this.rigCameras[0].customDefaultRenderTarget = null;
  107505. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  107506. this.rigCameras[1].position.x = pupilDistance / 2;
  107507. this.rigCameras[1].customDefaultRenderTarget = null;
  107508. };
  107509. return WebXRCamera;
  107510. }(BABYLON.FreeCamera));
  107511. BABYLON.WebXRCamera = WebXRCamera;
  107512. })(BABYLON || (BABYLON = {}));
  107513. //# sourceMappingURL=babylon.webXRCamera.js.map
  107514. // Mainly based on these 2 articles :
  107515. // 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
  107516. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  107517. var BABYLON;
  107518. (function (BABYLON) {
  107519. /**
  107520. * Defines the potential axis of a Joystick
  107521. */
  107522. var JoystickAxis;
  107523. (function (JoystickAxis) {
  107524. /** X axis */
  107525. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  107526. /** Y axis */
  107527. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  107528. /** Z axis */
  107529. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  107530. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  107531. /**
  107532. * Class used to define virtual joystick (used in touch mode)
  107533. */
  107534. var VirtualJoystick = /** @class */ (function () {
  107535. /**
  107536. * Creates a new virtual joystick
  107537. * @param leftJoystick defines that the joystick is for left hand (false by default)
  107538. */
  107539. function VirtualJoystick(leftJoystick) {
  107540. var _this = this;
  107541. if (leftJoystick) {
  107542. this._leftJoystick = true;
  107543. }
  107544. else {
  107545. this._leftJoystick = false;
  107546. }
  107547. VirtualJoystick._globalJoystickIndex++;
  107548. // By default left & right arrow keys are moving the X
  107549. // and up & down keys are moving the Y
  107550. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  107551. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  107552. this.reverseLeftRight = false;
  107553. this.reverseUpDown = false;
  107554. // collections of pointers
  107555. this._touches = new BABYLON.StringDictionary();
  107556. this.deltaPosition = BABYLON.Vector3.Zero();
  107557. this._joystickSensibility = 25;
  107558. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  107559. this._onResize = function (evt) {
  107560. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  107561. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  107562. if (VirtualJoystick.vjCanvas) {
  107563. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  107564. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  107565. }
  107566. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  107567. };
  107568. // injecting a canvas element on top of the canvas 3D game
  107569. if (!VirtualJoystick.vjCanvas) {
  107570. window.addEventListener("resize", this._onResize, false);
  107571. VirtualJoystick.vjCanvas = document.createElement("canvas");
  107572. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  107573. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  107574. VirtualJoystick.vjCanvas.width = window.innerWidth;
  107575. VirtualJoystick.vjCanvas.height = window.innerHeight;
  107576. VirtualJoystick.vjCanvas.style.width = "100%";
  107577. VirtualJoystick.vjCanvas.style.height = "100%";
  107578. VirtualJoystick.vjCanvas.style.position = "absolute";
  107579. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  107580. VirtualJoystick.vjCanvas.style.top = "0px";
  107581. VirtualJoystick.vjCanvas.style.left = "0px";
  107582. VirtualJoystick.vjCanvas.style.zIndex = "5";
  107583. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  107584. // Support for jQuery PEP polyfill
  107585. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  107586. var context = VirtualJoystick.vjCanvas.getContext('2d');
  107587. if (!context) {
  107588. throw new Error("Unable to create canvas for virtual joystick");
  107589. }
  107590. VirtualJoystick.vjCanvasContext = context;
  107591. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  107592. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  107593. document.body.appendChild(VirtualJoystick.vjCanvas);
  107594. }
  107595. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  107596. this.pressed = false;
  107597. // default joystick color
  107598. this._joystickColor = "cyan";
  107599. this._joystickPointerID = -1;
  107600. // current joystick position
  107601. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  107602. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  107603. // origin joystick position
  107604. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  107605. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  107606. this._onPointerDownHandlerRef = function (evt) {
  107607. _this._onPointerDown(evt);
  107608. };
  107609. this._onPointerMoveHandlerRef = function (evt) {
  107610. _this._onPointerMove(evt);
  107611. };
  107612. this._onPointerUpHandlerRef = function (evt) {
  107613. _this._onPointerUp(evt);
  107614. };
  107615. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  107616. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  107617. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  107618. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  107619. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  107620. evt.preventDefault(); // Disables system menu
  107621. }, false);
  107622. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  107623. }
  107624. /**
  107625. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  107626. * @param newJoystickSensibility defines the new sensibility
  107627. */
  107628. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  107629. this._joystickSensibility = newJoystickSensibility;
  107630. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  107631. };
  107632. VirtualJoystick.prototype._onPointerDown = function (e) {
  107633. var positionOnScreenCondition;
  107634. e.preventDefault();
  107635. if (this._leftJoystick === true) {
  107636. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  107637. }
  107638. else {
  107639. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  107640. }
  107641. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  107642. // First contact will be dedicated to the virtual joystick
  107643. this._joystickPointerID = e.pointerId;
  107644. this._joystickPointerStartPos.x = e.clientX;
  107645. this._joystickPointerStartPos.y = e.clientY;
  107646. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  107647. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  107648. this._deltaJoystickVector.x = 0;
  107649. this._deltaJoystickVector.y = 0;
  107650. this.pressed = true;
  107651. this._touches.add(e.pointerId.toString(), e);
  107652. }
  107653. else {
  107654. // You can only trigger the action buttons with a joystick declared
  107655. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  107656. this._action();
  107657. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  107658. }
  107659. }
  107660. };
  107661. VirtualJoystick.prototype._onPointerMove = function (e) {
  107662. // If the current pointer is the one associated to the joystick (first touch contact)
  107663. if (this._joystickPointerID == e.pointerId) {
  107664. this._joystickPointerPos.x = e.clientX;
  107665. this._joystickPointerPos.y = e.clientY;
  107666. this._deltaJoystickVector = this._joystickPointerPos.clone();
  107667. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  107668. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  107669. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  107670. switch (this._axisTargetedByLeftAndRight) {
  107671. case JoystickAxis.X:
  107672. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  107673. break;
  107674. case JoystickAxis.Y:
  107675. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  107676. break;
  107677. case JoystickAxis.Z:
  107678. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  107679. break;
  107680. }
  107681. var directionUpDown = this.reverseUpDown ? 1 : -1;
  107682. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  107683. switch (this._axisTargetedByUpAndDown) {
  107684. case JoystickAxis.X:
  107685. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  107686. break;
  107687. case JoystickAxis.Y:
  107688. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  107689. break;
  107690. case JoystickAxis.Z:
  107691. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  107692. break;
  107693. }
  107694. }
  107695. else {
  107696. var data = this._touches.get(e.pointerId.toString());
  107697. if (data) {
  107698. data.x = e.clientX;
  107699. data.y = e.clientY;
  107700. }
  107701. }
  107702. };
  107703. VirtualJoystick.prototype._onPointerUp = function (e) {
  107704. if (this._joystickPointerID == e.pointerId) {
  107705. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  107706. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  107707. this._joystickPointerID = -1;
  107708. this.pressed = false;
  107709. }
  107710. else {
  107711. var touch = this._touches.get(e.pointerId.toString());
  107712. if (touch) {
  107713. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  107714. }
  107715. }
  107716. this._deltaJoystickVector.x = 0;
  107717. this._deltaJoystickVector.y = 0;
  107718. this._touches.remove(e.pointerId.toString());
  107719. };
  107720. /**
  107721. * Change the color of the virtual joystick
  107722. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  107723. */
  107724. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  107725. this._joystickColor = newColor;
  107726. };
  107727. /**
  107728. * Defines a callback to call when the joystick is touched
  107729. * @param action defines the callback
  107730. */
  107731. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  107732. this._action = action;
  107733. };
  107734. /**
  107735. * Defines which axis you'd like to control for left & right
  107736. * @param axis defines the axis to use
  107737. */
  107738. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  107739. switch (axis) {
  107740. case JoystickAxis.X:
  107741. case JoystickAxis.Y:
  107742. case JoystickAxis.Z:
  107743. this._axisTargetedByLeftAndRight = axis;
  107744. break;
  107745. default:
  107746. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  107747. break;
  107748. }
  107749. };
  107750. /**
  107751. * Defines which axis you'd like to control for up & down
  107752. * @param axis defines the axis to use
  107753. */
  107754. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  107755. switch (axis) {
  107756. case JoystickAxis.X:
  107757. case JoystickAxis.Y:
  107758. case JoystickAxis.Z:
  107759. this._axisTargetedByUpAndDown = axis;
  107760. break;
  107761. default:
  107762. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  107763. break;
  107764. }
  107765. };
  107766. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  107767. var _this = this;
  107768. if (this.pressed) {
  107769. this._touches.forEach(function (key, touch) {
  107770. if (touch.pointerId === _this._joystickPointerID) {
  107771. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  107772. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  107773. VirtualJoystick.vjCanvasContext.beginPath();
  107774. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  107775. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  107776. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  107777. VirtualJoystick.vjCanvasContext.stroke();
  107778. VirtualJoystick.vjCanvasContext.closePath();
  107779. VirtualJoystick.vjCanvasContext.beginPath();
  107780. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  107781. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  107782. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  107783. VirtualJoystick.vjCanvasContext.stroke();
  107784. VirtualJoystick.vjCanvasContext.closePath();
  107785. VirtualJoystick.vjCanvasContext.beginPath();
  107786. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  107787. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  107788. VirtualJoystick.vjCanvasContext.stroke();
  107789. VirtualJoystick.vjCanvasContext.closePath();
  107790. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  107791. }
  107792. else {
  107793. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  107794. VirtualJoystick.vjCanvasContext.beginPath();
  107795. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  107796. VirtualJoystick.vjCanvasContext.beginPath();
  107797. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  107798. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  107799. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  107800. VirtualJoystick.vjCanvasContext.stroke();
  107801. VirtualJoystick.vjCanvasContext.closePath();
  107802. touch.prevX = touch.x;
  107803. touch.prevY = touch.y;
  107804. }
  107805. });
  107806. }
  107807. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  107808. };
  107809. /**
  107810. * Release internal HTML canvas
  107811. */
  107812. VirtualJoystick.prototype.releaseCanvas = function () {
  107813. if (VirtualJoystick.vjCanvas) {
  107814. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  107815. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  107816. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  107817. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  107818. window.removeEventListener("resize", this._onResize);
  107819. document.body.removeChild(VirtualJoystick.vjCanvas);
  107820. VirtualJoystick.vjCanvas = null;
  107821. }
  107822. };
  107823. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  107824. VirtualJoystick._globalJoystickIndex = 0;
  107825. return VirtualJoystick;
  107826. }());
  107827. BABYLON.VirtualJoystick = VirtualJoystick;
  107828. })(BABYLON || (BABYLON = {}));
  107829. //# sourceMappingURL=babylon.virtualJoystick.js.map
  107830. var BABYLON;
  107831. (function (BABYLON) {
  107832. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  107833. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  107834. });
  107835. /**
  107836. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  107837. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  107838. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  107839. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  107840. */
  107841. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  107842. __extends(VirtualJoysticksCamera, _super);
  107843. /**
  107844. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  107845. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  107846. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  107847. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  107848. * @param name Define the name of the camera in the scene
  107849. * @param position Define the start position of the camera in the scene
  107850. * @param scene Define the scene the camera belongs to
  107851. */
  107852. function VirtualJoysticksCamera(name, position, scene) {
  107853. var _this = _super.call(this, name, position, scene) || this;
  107854. _this.inputs.addVirtualJoystick();
  107855. return _this;
  107856. }
  107857. /**
  107858. * Gets the current object class name.
  107859. * @return the class name
  107860. */
  107861. VirtualJoysticksCamera.prototype.getClassName = function () {
  107862. return "VirtualJoysticksCamera";
  107863. };
  107864. return VirtualJoysticksCamera;
  107865. }(BABYLON.FreeCamera));
  107866. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  107867. })(BABYLON || (BABYLON = {}));
  107868. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  107869. var BABYLON;
  107870. (function (BABYLON) {
  107871. /**
  107872. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  107873. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  107874. */
  107875. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  107876. function FreeCameraVirtualJoystickInput() {
  107877. }
  107878. /**
  107879. * Gets the left stick of the virtual joystick.
  107880. * @returns The virtual Joystick
  107881. */
  107882. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  107883. return this._leftjoystick;
  107884. };
  107885. /**
  107886. * Gets the right stick of the virtual joystick.
  107887. * @returns The virtual Joystick
  107888. */
  107889. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  107890. return this._rightjoystick;
  107891. };
  107892. /**
  107893. * Update the current camera state depending on the inputs that have been used this frame.
  107894. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  107895. */
  107896. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  107897. if (this._leftjoystick) {
  107898. var camera = this.camera;
  107899. var speed = camera._computeLocalCameraSpeed() * 50;
  107900. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  107901. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  107902. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  107903. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  107904. if (!this._leftjoystick.pressed) {
  107905. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  107906. }
  107907. if (!this._rightjoystick.pressed) {
  107908. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  107909. }
  107910. }
  107911. };
  107912. /**
  107913. * Attach the input controls to a specific dom element to get the input from.
  107914. * @param element Defines the element the controls should be listened from
  107915. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  107916. */
  107917. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  107918. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  107919. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  107920. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  107921. this._leftjoystick.setJoystickSensibility(0.15);
  107922. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  107923. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  107924. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  107925. this._rightjoystick.reverseUpDown = true;
  107926. this._rightjoystick.setJoystickSensibility(0.05);
  107927. this._rightjoystick.setJoystickColor("yellow");
  107928. };
  107929. /**
  107930. * Detach the current controls from the specified dom element.
  107931. * @param element Defines the element to stop listening the inputs from
  107932. */
  107933. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  107934. this._leftjoystick.releaseCanvas();
  107935. this._rightjoystick.releaseCanvas();
  107936. };
  107937. /**
  107938. * Gets the class name of the current intput.
  107939. * @returns the class name
  107940. */
  107941. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  107942. return "FreeCameraVirtualJoystickInput";
  107943. };
  107944. /**
  107945. * Get the friendly name associated with the input class.
  107946. * @returns the input friendly name
  107947. */
  107948. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  107949. return "virtualJoystick";
  107950. };
  107951. return FreeCameraVirtualJoystickInput;
  107952. }());
  107953. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  107954. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  107955. })(BABYLON || (BABYLON = {}));
  107956. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  107957. var BABYLON;
  107958. (function (BABYLON) {
  107959. /**
  107960. * Class used to specify simplification options
  107961. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  107962. */
  107963. var SimplificationSettings = /** @class */ (function () {
  107964. /**
  107965. * Creates a SimplificationSettings
  107966. * @param quality expected quality
  107967. * @param distance distance when this optimized version should be used
  107968. * @param optimizeMesh already optimized mesh
  107969. */
  107970. function SimplificationSettings(
  107971. /** expected quality */
  107972. quality,
  107973. /** distance when this optimized version should be used */
  107974. distance,
  107975. /** already optimized mesh */
  107976. optimizeMesh) {
  107977. this.quality = quality;
  107978. this.distance = distance;
  107979. this.optimizeMesh = optimizeMesh;
  107980. }
  107981. return SimplificationSettings;
  107982. }());
  107983. BABYLON.SimplificationSettings = SimplificationSettings;
  107984. /**
  107985. * Queue used to order the simplification tasks
  107986. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  107987. */
  107988. var SimplificationQueue = /** @class */ (function () {
  107989. /**
  107990. * Creates a new queue
  107991. */
  107992. function SimplificationQueue() {
  107993. this.running = false;
  107994. this._simplificationArray = [];
  107995. }
  107996. /**
  107997. * Adds a new simplification task
  107998. * @param task defines a task to add
  107999. */
  108000. SimplificationQueue.prototype.addTask = function (task) {
  108001. this._simplificationArray.push(task);
  108002. };
  108003. /**
  108004. * Execute next task
  108005. */
  108006. SimplificationQueue.prototype.executeNext = function () {
  108007. var task = this._simplificationArray.pop();
  108008. if (task) {
  108009. this.running = true;
  108010. this.runSimplification(task);
  108011. }
  108012. else {
  108013. this.running = false;
  108014. }
  108015. };
  108016. /**
  108017. * Execute a simplification task
  108018. * @param task defines the task to run
  108019. */
  108020. SimplificationQueue.prototype.runSimplification = function (task) {
  108021. var _this = this;
  108022. if (task.parallelProcessing) {
  108023. //parallel simplifier
  108024. task.settings.forEach(function (setting) {
  108025. var simplifier = _this.getSimplifier(task);
  108026. simplifier.simplify(setting, function (newMesh) {
  108027. task.mesh.addLODLevel(setting.distance, newMesh);
  108028. newMesh.isVisible = true;
  108029. //check if it is the last
  108030. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  108031. //all done, run the success callback.
  108032. task.successCallback();
  108033. }
  108034. _this.executeNext();
  108035. });
  108036. });
  108037. }
  108038. else {
  108039. //single simplifier.
  108040. var simplifier = this.getSimplifier(task);
  108041. var runDecimation = function (setting, callback) {
  108042. simplifier.simplify(setting, function (newMesh) {
  108043. task.mesh.addLODLevel(setting.distance, newMesh);
  108044. newMesh.isVisible = true;
  108045. //run the next quality level
  108046. callback();
  108047. });
  108048. };
  108049. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  108050. runDecimation(task.settings[loop.index], function () {
  108051. loop.executeNext();
  108052. });
  108053. }, function () {
  108054. //execution ended, run the success callback.
  108055. if (task.successCallback) {
  108056. task.successCallback();
  108057. }
  108058. _this.executeNext();
  108059. });
  108060. }
  108061. };
  108062. SimplificationQueue.prototype.getSimplifier = function (task) {
  108063. switch (task.simplificationType) {
  108064. case SimplificationType.QUADRATIC:
  108065. default:
  108066. return new QuadraticErrorSimplification(task.mesh);
  108067. }
  108068. };
  108069. return SimplificationQueue;
  108070. }());
  108071. BABYLON.SimplificationQueue = SimplificationQueue;
  108072. /**
  108073. * The implemented types of simplification
  108074. * At the moment only Quadratic Error Decimation is implemented
  108075. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108076. */
  108077. var SimplificationType;
  108078. (function (SimplificationType) {
  108079. /** Quadratic error decimation */
  108080. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  108081. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  108082. var DecimationTriangle = /** @class */ (function () {
  108083. function DecimationTriangle(vertices) {
  108084. this.vertices = vertices;
  108085. this.error = new Array(4);
  108086. this.deleted = false;
  108087. this.isDirty = false;
  108088. this.deletePending = false;
  108089. this.borderFactor = 0;
  108090. }
  108091. return DecimationTriangle;
  108092. }());
  108093. var DecimationVertex = /** @class */ (function () {
  108094. function DecimationVertex(position, id) {
  108095. this.position = position;
  108096. this.id = id;
  108097. this.isBorder = true;
  108098. this.q = new QuadraticMatrix();
  108099. this.triangleCount = 0;
  108100. this.triangleStart = 0;
  108101. this.originalOffsets = [];
  108102. }
  108103. DecimationVertex.prototype.updatePosition = function (newPosition) {
  108104. this.position.copyFrom(newPosition);
  108105. };
  108106. return DecimationVertex;
  108107. }());
  108108. var QuadraticMatrix = /** @class */ (function () {
  108109. function QuadraticMatrix(data) {
  108110. this.data = new Array(10);
  108111. for (var i = 0; i < 10; ++i) {
  108112. if (data && data[i]) {
  108113. this.data[i] = data[i];
  108114. }
  108115. else {
  108116. this.data[i] = 0;
  108117. }
  108118. }
  108119. }
  108120. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  108121. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  108122. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  108123. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  108124. return det;
  108125. };
  108126. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  108127. for (var i = 0; i < 10; ++i) {
  108128. this.data[i] += matrix.data[i];
  108129. }
  108130. };
  108131. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  108132. for (var i = 0; i < 10; ++i) {
  108133. this.data[i] += data[i];
  108134. }
  108135. };
  108136. QuadraticMatrix.prototype.add = function (matrix) {
  108137. var m = new QuadraticMatrix();
  108138. for (var i = 0; i < 10; ++i) {
  108139. m.data[i] = this.data[i] + matrix.data[i];
  108140. }
  108141. return m;
  108142. };
  108143. QuadraticMatrix.FromData = function (a, b, c, d) {
  108144. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  108145. };
  108146. //returning an array to avoid garbage collection
  108147. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  108148. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  108149. };
  108150. return QuadraticMatrix;
  108151. }());
  108152. var Reference = /** @class */ (function () {
  108153. function Reference(vertexId, triangleId) {
  108154. this.vertexId = vertexId;
  108155. this.triangleId = triangleId;
  108156. }
  108157. return Reference;
  108158. }());
  108159. /**
  108160. * An implementation of the Quadratic Error simplification algorithm.
  108161. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  108162. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  108163. * @author RaananW
  108164. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108165. */
  108166. var QuadraticErrorSimplification = /** @class */ (function () {
  108167. function QuadraticErrorSimplification(_mesh) {
  108168. this._mesh = _mesh;
  108169. this.syncIterations = 5000;
  108170. this.aggressiveness = 7;
  108171. this.decimationIterations = 100;
  108172. this.boundingBoxEpsilon = BABYLON.Epsilon;
  108173. }
  108174. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  108175. var _this = this;
  108176. this.initDecimatedMesh();
  108177. //iterating through the submeshes array, one after the other.
  108178. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  108179. _this.initWithMesh(loop.index, function () {
  108180. _this.runDecimation(settings, loop.index, function () {
  108181. loop.executeNext();
  108182. });
  108183. }, settings.optimizeMesh);
  108184. }, function () {
  108185. setTimeout(function () {
  108186. successCallback(_this._reconstructedMesh);
  108187. }, 0);
  108188. });
  108189. };
  108190. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  108191. var _this = this;
  108192. var targetCount = ~~(this.triangles.length * settings.quality);
  108193. var deletedTriangles = 0;
  108194. var triangleCount = this.triangles.length;
  108195. var iterationFunction = function (iteration, callback) {
  108196. setTimeout(function () {
  108197. if (iteration % 5 === 0) {
  108198. _this.updateMesh(iteration === 0);
  108199. }
  108200. for (var i = 0; i < _this.triangles.length; ++i) {
  108201. _this.triangles[i].isDirty = false;
  108202. }
  108203. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  108204. var trianglesIterator = function (i) {
  108205. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  108206. var t = _this.triangles[tIdx];
  108207. if (!t) {
  108208. return;
  108209. }
  108210. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  108211. return;
  108212. }
  108213. for (var j = 0; j < 3; ++j) {
  108214. if (t.error[j] < threshold) {
  108215. var deleted0 = [];
  108216. var deleted1 = [];
  108217. var v0 = t.vertices[j];
  108218. var v1 = t.vertices[(j + 1) % 3];
  108219. if (v0.isBorder || v1.isBorder) {
  108220. continue;
  108221. }
  108222. var p = BABYLON.Vector3.Zero();
  108223. var n = BABYLON.Vector3.Zero();
  108224. var uv = BABYLON.Vector2.Zero();
  108225. var color = new BABYLON.Color4(0, 0, 0, 1);
  108226. _this.calculateError(v0, v1, p, n, uv, color);
  108227. var delTr = new Array();
  108228. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  108229. continue;
  108230. }
  108231. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  108232. continue;
  108233. }
  108234. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  108235. continue;
  108236. }
  108237. var uniqueArray = new Array();
  108238. delTr.forEach(function (deletedT) {
  108239. if (uniqueArray.indexOf(deletedT) === -1) {
  108240. deletedT.deletePending = true;
  108241. uniqueArray.push(deletedT);
  108242. }
  108243. });
  108244. if (uniqueArray.length % 2 !== 0) {
  108245. continue;
  108246. }
  108247. v0.q = v1.q.add(v0.q);
  108248. v0.updatePosition(p);
  108249. var tStart = _this.references.length;
  108250. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  108251. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  108252. var tCount = _this.references.length - tStart;
  108253. if (tCount <= v0.triangleCount) {
  108254. if (tCount) {
  108255. for (var c = 0; c < tCount; c++) {
  108256. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  108257. }
  108258. }
  108259. }
  108260. else {
  108261. v0.triangleStart = tStart;
  108262. }
  108263. v0.triangleCount = tCount;
  108264. break;
  108265. }
  108266. }
  108267. };
  108268. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  108269. }, 0);
  108270. };
  108271. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  108272. if (triangleCount - deletedTriangles <= targetCount) {
  108273. loop.breakLoop();
  108274. }
  108275. else {
  108276. iterationFunction(loop.index, function () {
  108277. loop.executeNext();
  108278. });
  108279. }
  108280. }, function () {
  108281. setTimeout(function () {
  108282. //reconstruct this part of the mesh
  108283. _this.reconstructMesh(submeshIndex);
  108284. successCallback();
  108285. }, 0);
  108286. });
  108287. };
  108288. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  108289. var _this = this;
  108290. this.vertices = [];
  108291. this.triangles = [];
  108292. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108293. var indices = this._mesh.getIndices();
  108294. var submesh = this._mesh.subMeshes[submeshIndex];
  108295. var findInVertices = function (positionToSearch) {
  108296. if (optimizeMesh) {
  108297. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  108298. if (_this.vertices[ii].position.equals(positionToSearch)) {
  108299. return _this.vertices[ii];
  108300. }
  108301. }
  108302. }
  108303. return null;
  108304. };
  108305. var vertexReferences = [];
  108306. var vertexInit = function (i) {
  108307. if (!positionData) {
  108308. return;
  108309. }
  108310. var offset = i + submesh.verticesStart;
  108311. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  108312. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  108313. vertex.originalOffsets.push(offset);
  108314. if (vertex.id === _this.vertices.length) {
  108315. _this.vertices.push(vertex);
  108316. }
  108317. vertexReferences.push(vertex.id);
  108318. };
  108319. //var totalVertices = mesh.getTotalVertices();
  108320. var totalVertices = submesh.verticesCount;
  108321. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  108322. var indicesInit = function (i) {
  108323. if (!indices) {
  108324. return;
  108325. }
  108326. var offset = (submesh.indexStart / 3) + i;
  108327. var pos = (offset * 3);
  108328. var i0 = indices[pos + 0];
  108329. var i1 = indices[pos + 1];
  108330. var i2 = indices[pos + 2];
  108331. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  108332. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  108333. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  108334. var triangle = new DecimationTriangle([v0, v1, v2]);
  108335. triangle.originalOffset = pos;
  108336. _this.triangles.push(triangle);
  108337. };
  108338. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  108339. _this.init(callback);
  108340. });
  108341. });
  108342. };
  108343. QuadraticErrorSimplification.prototype.init = function (callback) {
  108344. var _this = this;
  108345. var triangleInit1 = function (i) {
  108346. var t = _this.triangles[i];
  108347. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  108348. for (var j = 0; j < 3; j++) {
  108349. 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))));
  108350. }
  108351. };
  108352. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  108353. var triangleInit2 = function (i) {
  108354. var t = _this.triangles[i];
  108355. for (var j = 0; j < 3; ++j) {
  108356. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  108357. }
  108358. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  108359. };
  108360. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  108361. callback();
  108362. });
  108363. });
  108364. };
  108365. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  108366. var newTriangles = [];
  108367. var i;
  108368. for (i = 0; i < this.vertices.length; ++i) {
  108369. this.vertices[i].triangleCount = 0;
  108370. }
  108371. var t;
  108372. var j;
  108373. for (i = 0; i < this.triangles.length; ++i) {
  108374. if (!this.triangles[i].deleted) {
  108375. t = this.triangles[i];
  108376. for (j = 0; j < 3; ++j) {
  108377. t.vertices[j].triangleCount = 1;
  108378. }
  108379. newTriangles.push(t);
  108380. }
  108381. }
  108382. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  108383. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  108384. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  108385. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  108386. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  108387. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  108388. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  108389. var vertexCount = 0;
  108390. for (i = 0; i < this.vertices.length; ++i) {
  108391. var vertex = this.vertices[i];
  108392. vertex.id = vertexCount;
  108393. if (vertex.triangleCount) {
  108394. vertex.originalOffsets.forEach(function (originalOffset) {
  108395. if (!normalData) {
  108396. return;
  108397. }
  108398. newPositionData.push(vertex.position.x);
  108399. newPositionData.push(vertex.position.y);
  108400. newPositionData.push(vertex.position.z);
  108401. newNormalData.push(normalData[originalOffset * 3]);
  108402. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  108403. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  108404. if (uvs && uvs.length) {
  108405. newUVsData.push(uvs[(originalOffset * 2)]);
  108406. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  108407. }
  108408. else if (colorsData && colorsData.length) {
  108409. newColorsData.push(colorsData[(originalOffset * 4)]);
  108410. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  108411. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  108412. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  108413. }
  108414. ++vertexCount;
  108415. });
  108416. }
  108417. }
  108418. var startingIndex = this._reconstructedMesh.getTotalIndices();
  108419. var startingVertex = this._reconstructedMesh.getTotalVertices();
  108420. var submeshesArray = this._reconstructedMesh.subMeshes;
  108421. this._reconstructedMesh.subMeshes = [];
  108422. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  108423. var originalIndices = this._mesh.getIndices();
  108424. for (i = 0; i < newTriangles.length; ++i) {
  108425. t = newTriangles[i]; //now get the new referencing point for each vertex
  108426. [0, 1, 2].forEach(function (idx) {
  108427. var id = originalIndices[t.originalOffset + idx];
  108428. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  108429. if (offset < 0) {
  108430. offset = 0;
  108431. }
  108432. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  108433. });
  108434. }
  108435. //overwriting the old vertex buffers and indices.
  108436. this._reconstructedMesh.setIndices(newIndicesArray);
  108437. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  108438. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  108439. if (newUVsData.length > 0) {
  108440. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  108441. }
  108442. if (newColorsData.length > 0) {
  108443. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  108444. }
  108445. //create submesh
  108446. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  108447. if (submeshIndex > 0) {
  108448. this._reconstructedMesh.subMeshes = [];
  108449. submeshesArray.forEach(function (submesh) {
  108450. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  108451. });
  108452. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  108453. }
  108454. };
  108455. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  108456. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  108457. this._reconstructedMesh.material = this._mesh.material;
  108458. this._reconstructedMesh.parent = this._mesh.parent;
  108459. this._reconstructedMesh.isVisible = false;
  108460. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  108461. };
  108462. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  108463. for (var i = 0; i < vertex1.triangleCount; ++i) {
  108464. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  108465. if (t.deleted) {
  108466. continue;
  108467. }
  108468. var s = this.references[vertex1.triangleStart + i].vertexId;
  108469. var v1 = t.vertices[(s + 1) % 3];
  108470. var v2 = t.vertices[(s + 2) % 3];
  108471. if ((v1 === vertex2 || v2 === vertex2)) {
  108472. deletedArray[i] = true;
  108473. delTr.push(t);
  108474. continue;
  108475. }
  108476. var d1 = v1.position.subtract(point);
  108477. d1 = d1.normalize();
  108478. var d2 = v2.position.subtract(point);
  108479. d2 = d2.normalize();
  108480. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  108481. return true;
  108482. }
  108483. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  108484. deletedArray[i] = false;
  108485. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  108486. return true;
  108487. }
  108488. }
  108489. return false;
  108490. };
  108491. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  108492. var newDeleted = deletedTriangles;
  108493. for (var i = 0; i < vertex.triangleCount; ++i) {
  108494. var ref = this.references[vertex.triangleStart + i];
  108495. var t = this.triangles[ref.triangleId];
  108496. if (t.deleted) {
  108497. continue;
  108498. }
  108499. if (deletedArray[i] && t.deletePending) {
  108500. t.deleted = true;
  108501. newDeleted++;
  108502. continue;
  108503. }
  108504. t.vertices[ref.vertexId] = origVertex;
  108505. t.isDirty = true;
  108506. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  108507. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  108508. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  108509. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  108510. this.references.push(ref);
  108511. }
  108512. return newDeleted;
  108513. };
  108514. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  108515. for (var i = 0; i < this.vertices.length; ++i) {
  108516. var vCount = [];
  108517. var vId = [];
  108518. var v = this.vertices[i];
  108519. var j;
  108520. for (j = 0; j < v.triangleCount; ++j) {
  108521. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  108522. for (var ii = 0; ii < 3; ii++) {
  108523. var ofs = 0;
  108524. var vv = triangle.vertices[ii];
  108525. while (ofs < vCount.length) {
  108526. if (vId[ofs] === vv.id) {
  108527. break;
  108528. }
  108529. ++ofs;
  108530. }
  108531. if (ofs === vCount.length) {
  108532. vCount.push(1);
  108533. vId.push(vv.id);
  108534. }
  108535. else {
  108536. vCount[ofs]++;
  108537. }
  108538. }
  108539. }
  108540. for (j = 0; j < vCount.length; ++j) {
  108541. if (vCount[j] === 1) {
  108542. this.vertices[vId[j]].isBorder = true;
  108543. }
  108544. else {
  108545. this.vertices[vId[j]].isBorder = false;
  108546. }
  108547. }
  108548. }
  108549. };
  108550. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  108551. if (identifyBorders === void 0) { identifyBorders = false; }
  108552. var i;
  108553. if (!identifyBorders) {
  108554. var newTrianglesVector = [];
  108555. for (i = 0; i < this.triangles.length; ++i) {
  108556. if (!this.triangles[i].deleted) {
  108557. newTrianglesVector.push(this.triangles[i]);
  108558. }
  108559. }
  108560. this.triangles = newTrianglesVector;
  108561. }
  108562. for (i = 0; i < this.vertices.length; ++i) {
  108563. this.vertices[i].triangleCount = 0;
  108564. this.vertices[i].triangleStart = 0;
  108565. }
  108566. var t;
  108567. var j;
  108568. var v;
  108569. for (i = 0; i < this.triangles.length; ++i) {
  108570. t = this.triangles[i];
  108571. for (j = 0; j < 3; ++j) {
  108572. v = t.vertices[j];
  108573. v.triangleCount++;
  108574. }
  108575. }
  108576. var tStart = 0;
  108577. for (i = 0; i < this.vertices.length; ++i) {
  108578. this.vertices[i].triangleStart = tStart;
  108579. tStart += this.vertices[i].triangleCount;
  108580. this.vertices[i].triangleCount = 0;
  108581. }
  108582. var newReferences = new Array(this.triangles.length * 3);
  108583. for (i = 0; i < this.triangles.length; ++i) {
  108584. t = this.triangles[i];
  108585. for (j = 0; j < 3; ++j) {
  108586. v = t.vertices[j];
  108587. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  108588. v.triangleCount++;
  108589. }
  108590. }
  108591. this.references = newReferences;
  108592. if (identifyBorders) {
  108593. this.identifyBorder();
  108594. }
  108595. };
  108596. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  108597. var x = point.x;
  108598. var y = point.y;
  108599. var z = point.z;
  108600. 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
  108601. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  108602. };
  108603. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  108604. var q = vertex1.q.add(vertex2.q);
  108605. var border = vertex1.isBorder && vertex2.isBorder;
  108606. var error = 0;
  108607. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  108608. if (qDet !== 0 && !border) {
  108609. if (!pointResult) {
  108610. pointResult = BABYLON.Vector3.Zero();
  108611. }
  108612. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  108613. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  108614. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  108615. error = this.vertexError(q, pointResult);
  108616. }
  108617. else {
  108618. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  108619. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  108620. var error1 = this.vertexError(q, vertex1.position);
  108621. var error2 = this.vertexError(q, vertex2.position);
  108622. var error3 = this.vertexError(q, p3);
  108623. error = Math.min(error1, error2, error3);
  108624. if (error === error1) {
  108625. if (pointResult) {
  108626. pointResult.copyFrom(vertex1.position);
  108627. }
  108628. }
  108629. else if (error === error2) {
  108630. if (pointResult) {
  108631. pointResult.copyFrom(vertex2.position);
  108632. }
  108633. }
  108634. else {
  108635. if (pointResult) {
  108636. pointResult.copyFrom(p3);
  108637. }
  108638. }
  108639. }
  108640. return error;
  108641. };
  108642. return QuadraticErrorSimplification;
  108643. }());
  108644. })(BABYLON || (BABYLON = {}));
  108645. //# sourceMappingURL=babylon.meshSimplification.js.map
  108646. var BABYLON;
  108647. (function (BABYLON) {
  108648. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  108649. get: function () {
  108650. if (!this._simplificationQueue) {
  108651. this._simplificationQueue = new BABYLON.SimplificationQueue();
  108652. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  108653. if (!component) {
  108654. component = new SimplicationQueueSceneComponent(this);
  108655. this._addComponent(component);
  108656. }
  108657. }
  108658. return this._simplificationQueue;
  108659. },
  108660. set: function (value) {
  108661. this._simplificationQueue = value;
  108662. },
  108663. enumerable: true,
  108664. configurable: true
  108665. });
  108666. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  108667. if (parallelProcessing === void 0) { parallelProcessing = true; }
  108668. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  108669. this.getScene().simplificationQueue.addTask({
  108670. settings: settings,
  108671. parallelProcessing: parallelProcessing,
  108672. mesh: this,
  108673. simplificationType: simplificationType,
  108674. successCallback: successCallback
  108675. });
  108676. return this;
  108677. };
  108678. /**
  108679. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  108680. * created in a scene
  108681. */
  108682. var SimplicationQueueSceneComponent = /** @class */ (function () {
  108683. /**
  108684. * Creates a new instance of the component for the given scene
  108685. * @param scene Defines the scene to register the component in
  108686. */
  108687. function SimplicationQueueSceneComponent(scene) {
  108688. /**
  108689. * The component name helpfull to identify the component in the list of scene components.
  108690. */
  108691. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  108692. this.scene = scene;
  108693. }
  108694. /**
  108695. * Registers the component in a given scene
  108696. */
  108697. SimplicationQueueSceneComponent.prototype.register = function () {
  108698. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  108699. };
  108700. /**
  108701. * Rebuilds the elements related to this component in case of
  108702. * context lost for instance.
  108703. */
  108704. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  108705. // Nothing to do for this component
  108706. };
  108707. /**
  108708. * Disposes the component and the associated ressources
  108709. */
  108710. SimplicationQueueSceneComponent.prototype.dispose = function () {
  108711. // Nothing to do for this component
  108712. };
  108713. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  108714. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  108715. this.scene._simplificationQueue.executeNext();
  108716. }
  108717. };
  108718. return SimplicationQueueSceneComponent;
  108719. }());
  108720. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  108721. })(BABYLON || (BABYLON = {}));
  108722. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  108723. var BABYLON;
  108724. (function (BABYLON) {
  108725. /**
  108726. * Class used to represent a specific level of detail of a mesh
  108727. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  108728. */
  108729. var MeshLODLevel = /** @class */ (function () {
  108730. /**
  108731. * Creates a new LOD level
  108732. * @param distance defines the distance where this level should star being displayed
  108733. * @param mesh defines the mesh to use to render this level
  108734. */
  108735. function MeshLODLevel(
  108736. /** Defines the distance where this level should star being displayed */
  108737. distance,
  108738. /** Defines the mesh to use to render this level */
  108739. mesh) {
  108740. this.distance = distance;
  108741. this.mesh = mesh;
  108742. }
  108743. return MeshLODLevel;
  108744. }());
  108745. BABYLON.MeshLODLevel = MeshLODLevel;
  108746. })(BABYLON || (BABYLON = {}));
  108747. //# sourceMappingURL=babylon.meshLODLevel.js.map
  108748. var BABYLON;
  108749. (function (BABYLON) {
  108750. /**
  108751. * Defines the root class used to create scene optimization to use with SceneOptimizer
  108752. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108753. */
  108754. var SceneOptimization = /** @class */ (function () {
  108755. /**
  108756. * Creates the SceneOptimization object
  108757. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  108758. * @param desc defines the description associated with the optimization
  108759. */
  108760. function SceneOptimization(
  108761. /**
  108762. * Defines the priority of this optimization (0 by default which means first in the list)
  108763. */
  108764. priority) {
  108765. if (priority === void 0) { priority = 0; }
  108766. this.priority = priority;
  108767. }
  108768. /**
  108769. * Gets a string describing the action executed by the current optimization
  108770. * @returns description string
  108771. */
  108772. SceneOptimization.prototype.getDescription = function () {
  108773. return "";
  108774. };
  108775. /**
  108776. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108777. * @param scene defines the current scene where to apply this optimization
  108778. * @param optimizer defines the current optimizer
  108779. * @returns true if everything that can be done was applied
  108780. */
  108781. SceneOptimization.prototype.apply = function (scene, optimizer) {
  108782. return true;
  108783. };
  108784. return SceneOptimization;
  108785. }());
  108786. BABYLON.SceneOptimization = SceneOptimization;
  108787. /**
  108788. * Defines an optimization used to reduce the size of render target textures
  108789. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108790. */
  108791. var TextureOptimization = /** @class */ (function (_super) {
  108792. __extends(TextureOptimization, _super);
  108793. /**
  108794. * Creates the TextureOptimization object
  108795. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  108796. * @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
  108797. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  108798. */
  108799. function TextureOptimization(
  108800. /**
  108801. * Defines the priority of this optimization (0 by default which means first in the list)
  108802. */
  108803. priority,
  108804. /**
  108805. * 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
  108806. */
  108807. maximumSize,
  108808. /**
  108809. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  108810. */
  108811. step) {
  108812. if (priority === void 0) { priority = 0; }
  108813. if (maximumSize === void 0) { maximumSize = 1024; }
  108814. if (step === void 0) { step = 0.5; }
  108815. var _this = _super.call(this, priority) || this;
  108816. _this.priority = priority;
  108817. _this.maximumSize = maximumSize;
  108818. _this.step = step;
  108819. return _this;
  108820. }
  108821. /**
  108822. * Gets a string describing the action executed by the current optimization
  108823. * @returns description string
  108824. */
  108825. TextureOptimization.prototype.getDescription = function () {
  108826. return "Reducing render target texture size to " + this.maximumSize;
  108827. };
  108828. /**
  108829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108830. * @param scene defines the current scene where to apply this optimization
  108831. * @param optimizer defines the current optimizer
  108832. * @returns true if everything that can be done was applied
  108833. */
  108834. TextureOptimization.prototype.apply = function (scene, optimizer) {
  108835. var allDone = true;
  108836. for (var index = 0; index < scene.textures.length; index++) {
  108837. var texture = scene.textures[index];
  108838. if (!texture.canRescale || texture.getContext) {
  108839. continue;
  108840. }
  108841. var currentSize = texture.getSize();
  108842. var maxDimension = Math.max(currentSize.width, currentSize.height);
  108843. if (maxDimension > this.maximumSize) {
  108844. texture.scale(this.step);
  108845. allDone = false;
  108846. }
  108847. }
  108848. return allDone;
  108849. };
  108850. return TextureOptimization;
  108851. }(SceneOptimization));
  108852. BABYLON.TextureOptimization = TextureOptimization;
  108853. /**
  108854. * Defines an optimization used to increase or decrease the rendering resolution
  108855. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108856. */
  108857. var HardwareScalingOptimization = /** @class */ (function (_super) {
  108858. __extends(HardwareScalingOptimization, _super);
  108859. /**
  108860. * Creates the HardwareScalingOptimization object
  108861. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  108862. * @param maximumScale defines the maximum scale to use (2 by default)
  108863. * @param step defines the step to use between two passes (0.5 by default)
  108864. */
  108865. function HardwareScalingOptimization(
  108866. /**
  108867. * Defines the priority of this optimization (0 by default which means first in the list)
  108868. */
  108869. priority,
  108870. /**
  108871. * Defines the maximum scale to use (2 by default)
  108872. */
  108873. maximumScale,
  108874. /**
  108875. * Defines the step to use between two passes (0.5 by default)
  108876. */
  108877. step) {
  108878. if (priority === void 0) { priority = 0; }
  108879. if (maximumScale === void 0) { maximumScale = 2; }
  108880. if (step === void 0) { step = 0.25; }
  108881. var _this = _super.call(this, priority) || this;
  108882. _this.priority = priority;
  108883. _this.maximumScale = maximumScale;
  108884. _this.step = step;
  108885. _this._currentScale = -1;
  108886. _this._directionOffset = 1;
  108887. return _this;
  108888. }
  108889. /**
  108890. * Gets a string describing the action executed by the current optimization
  108891. * @return description string
  108892. */
  108893. HardwareScalingOptimization.prototype.getDescription = function () {
  108894. return "Setting hardware scaling level to " + this._currentScale;
  108895. };
  108896. /**
  108897. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108898. * @param scene defines the current scene where to apply this optimization
  108899. * @param optimizer defines the current optimizer
  108900. * @returns true if everything that can be done was applied
  108901. */
  108902. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  108903. if (this._currentScale === -1) {
  108904. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  108905. if (this._currentScale > this.maximumScale) {
  108906. this._directionOffset = -1;
  108907. }
  108908. }
  108909. this._currentScale += this._directionOffset * this.step;
  108910. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  108911. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  108912. };
  108913. return HardwareScalingOptimization;
  108914. }(SceneOptimization));
  108915. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  108916. /**
  108917. * Defines an optimization used to remove shadows
  108918. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108919. */
  108920. var ShadowsOptimization = /** @class */ (function (_super) {
  108921. __extends(ShadowsOptimization, _super);
  108922. function ShadowsOptimization() {
  108923. return _super !== null && _super.apply(this, arguments) || this;
  108924. }
  108925. /**
  108926. * Gets a string describing the action executed by the current optimization
  108927. * @return description string
  108928. */
  108929. ShadowsOptimization.prototype.getDescription = function () {
  108930. return "Turning shadows on/off";
  108931. };
  108932. /**
  108933. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108934. * @param scene defines the current scene where to apply this optimization
  108935. * @param optimizer defines the current optimizer
  108936. * @returns true if everything that can be done was applied
  108937. */
  108938. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  108939. scene.shadowsEnabled = optimizer.isInImprovementMode;
  108940. return true;
  108941. };
  108942. return ShadowsOptimization;
  108943. }(SceneOptimization));
  108944. BABYLON.ShadowsOptimization = ShadowsOptimization;
  108945. /**
  108946. * Defines an optimization used to turn post-processes off
  108947. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108948. */
  108949. var PostProcessesOptimization = /** @class */ (function (_super) {
  108950. __extends(PostProcessesOptimization, _super);
  108951. function PostProcessesOptimization() {
  108952. return _super !== null && _super.apply(this, arguments) || this;
  108953. }
  108954. /**
  108955. * Gets a string describing the action executed by the current optimization
  108956. * @return description string
  108957. */
  108958. PostProcessesOptimization.prototype.getDescription = function () {
  108959. return "Turning post-processes on/off";
  108960. };
  108961. /**
  108962. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108963. * @param scene defines the current scene where to apply this optimization
  108964. * @param optimizer defines the current optimizer
  108965. * @returns true if everything that can be done was applied
  108966. */
  108967. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  108968. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  108969. return true;
  108970. };
  108971. return PostProcessesOptimization;
  108972. }(SceneOptimization));
  108973. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  108974. /**
  108975. * Defines an optimization used to turn lens flares off
  108976. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  108977. */
  108978. var LensFlaresOptimization = /** @class */ (function (_super) {
  108979. __extends(LensFlaresOptimization, _super);
  108980. function LensFlaresOptimization() {
  108981. return _super !== null && _super.apply(this, arguments) || this;
  108982. }
  108983. /**
  108984. * Gets a string describing the action executed by the current optimization
  108985. * @return description string
  108986. */
  108987. LensFlaresOptimization.prototype.getDescription = function () {
  108988. return "Turning lens flares on/off";
  108989. };
  108990. /**
  108991. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  108992. * @param scene defines the current scene where to apply this optimization
  108993. * @param optimizer defines the current optimizer
  108994. * @returns true if everything that can be done was applied
  108995. */
  108996. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  108997. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  108998. return true;
  108999. };
  109000. return LensFlaresOptimization;
  109001. }(SceneOptimization));
  109002. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  109003. /**
  109004. * Defines an optimization based on user defined callback.
  109005. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109006. */
  109007. var CustomOptimization = /** @class */ (function (_super) {
  109008. __extends(CustomOptimization, _super);
  109009. function CustomOptimization() {
  109010. return _super !== null && _super.apply(this, arguments) || this;
  109011. }
  109012. /**
  109013. * Gets a string describing the action executed by the current optimization
  109014. * @returns description string
  109015. */
  109016. CustomOptimization.prototype.getDescription = function () {
  109017. if (this.onGetDescription) {
  109018. return this.onGetDescription();
  109019. }
  109020. return "Running user defined callback";
  109021. };
  109022. /**
  109023. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109024. * @param scene defines the current scene where to apply this optimization
  109025. * @param optimizer defines the current optimizer
  109026. * @returns true if everything that can be done was applied
  109027. */
  109028. CustomOptimization.prototype.apply = function (scene, optimizer) {
  109029. if (this.onApply) {
  109030. return this.onApply(scene, optimizer);
  109031. }
  109032. return true;
  109033. };
  109034. return CustomOptimization;
  109035. }(SceneOptimization));
  109036. BABYLON.CustomOptimization = CustomOptimization;
  109037. /**
  109038. * Defines an optimization used to turn particles off
  109039. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109040. */
  109041. var ParticlesOptimization = /** @class */ (function (_super) {
  109042. __extends(ParticlesOptimization, _super);
  109043. function ParticlesOptimization() {
  109044. return _super !== null && _super.apply(this, arguments) || this;
  109045. }
  109046. /**
  109047. * Gets a string describing the action executed by the current optimization
  109048. * @return description string
  109049. */
  109050. ParticlesOptimization.prototype.getDescription = function () {
  109051. return "Turning particles on/off";
  109052. };
  109053. /**
  109054. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109055. * @param scene defines the current scene where to apply this optimization
  109056. * @param optimizer defines the current optimizer
  109057. * @returns true if everything that can be done was applied
  109058. */
  109059. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  109060. scene.particlesEnabled = optimizer.isInImprovementMode;
  109061. return true;
  109062. };
  109063. return ParticlesOptimization;
  109064. }(SceneOptimization));
  109065. BABYLON.ParticlesOptimization = ParticlesOptimization;
  109066. /**
  109067. * Defines an optimization used to turn render targets off
  109068. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109069. */
  109070. var RenderTargetsOptimization = /** @class */ (function (_super) {
  109071. __extends(RenderTargetsOptimization, _super);
  109072. function RenderTargetsOptimization() {
  109073. return _super !== null && _super.apply(this, arguments) || this;
  109074. }
  109075. /**
  109076. * Gets a string describing the action executed by the current optimization
  109077. * @return description string
  109078. */
  109079. RenderTargetsOptimization.prototype.getDescription = function () {
  109080. return "Turning render targets off";
  109081. };
  109082. /**
  109083. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109084. * @param scene defines the current scene where to apply this optimization
  109085. * @param optimizer defines the current optimizer
  109086. * @returns true if everything that can be done was applied
  109087. */
  109088. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  109089. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  109090. return true;
  109091. };
  109092. return RenderTargetsOptimization;
  109093. }(SceneOptimization));
  109094. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  109095. /**
  109096. * Defines an optimization used to merge meshes with compatible materials
  109097. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109098. */
  109099. var MergeMeshesOptimization = /** @class */ (function (_super) {
  109100. __extends(MergeMeshesOptimization, _super);
  109101. function MergeMeshesOptimization() {
  109102. var _this = _super !== null && _super.apply(this, arguments) || this;
  109103. _this._canBeMerged = function (abstractMesh) {
  109104. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  109105. return false;
  109106. }
  109107. var mesh = abstractMesh;
  109108. if (mesh.isDisposed()) {
  109109. return false;
  109110. }
  109111. if (!mesh.isVisible || !mesh.isEnabled()) {
  109112. return false;
  109113. }
  109114. if (mesh.instances.length > 0) {
  109115. return false;
  109116. }
  109117. if (mesh.skeleton || mesh.hasLODLevels) {
  109118. return false;
  109119. }
  109120. return true;
  109121. };
  109122. return _this;
  109123. }
  109124. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  109125. /**
  109126. * Gets or sets a boolean which defines if optimization octree has to be updated
  109127. */
  109128. get: function () {
  109129. return MergeMeshesOptimization._UpdateSelectionTree;
  109130. },
  109131. /**
  109132. * Gets or sets a boolean which defines if optimization octree has to be updated
  109133. */
  109134. set: function (value) {
  109135. MergeMeshesOptimization._UpdateSelectionTree = value;
  109136. },
  109137. enumerable: true,
  109138. configurable: true
  109139. });
  109140. /**
  109141. * Gets a string describing the action executed by the current optimization
  109142. * @return description string
  109143. */
  109144. MergeMeshesOptimization.prototype.getDescription = function () {
  109145. return "Merging similar meshes together";
  109146. };
  109147. /**
  109148. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109149. * @param scene defines the current scene where to apply this optimization
  109150. * @param optimizer defines the current optimizer
  109151. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  109152. * @returns true if everything that can be done was applied
  109153. */
  109154. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  109155. var globalPool = scene.meshes.slice(0);
  109156. var globalLength = globalPool.length;
  109157. for (var index = 0; index < globalLength; index++) {
  109158. var currentPool = new Array();
  109159. var current = globalPool[index];
  109160. // Checks
  109161. if (!this._canBeMerged(current)) {
  109162. continue;
  109163. }
  109164. currentPool.push(current);
  109165. // Find compatible meshes
  109166. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  109167. var otherMesh = globalPool[subIndex];
  109168. if (!this._canBeMerged(otherMesh)) {
  109169. continue;
  109170. }
  109171. if (otherMesh.material !== current.material) {
  109172. continue;
  109173. }
  109174. if (otherMesh.checkCollisions !== current.checkCollisions) {
  109175. continue;
  109176. }
  109177. currentPool.push(otherMesh);
  109178. globalLength--;
  109179. globalPool.splice(subIndex, 1);
  109180. subIndex--;
  109181. }
  109182. if (currentPool.length < 2) {
  109183. continue;
  109184. }
  109185. // Merge meshes
  109186. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  109187. }
  109188. // Call the octree system optimization if it is defined.
  109189. var sceneAsAny = scene;
  109190. if (sceneAsAny.createOrUpdateSelectionOctree) {
  109191. if (updateSelectionTree != undefined) {
  109192. if (updateSelectionTree) {
  109193. sceneAsAny.createOrUpdateSelectionOctree();
  109194. }
  109195. }
  109196. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  109197. sceneAsAny.createOrUpdateSelectionOctree();
  109198. }
  109199. }
  109200. return true;
  109201. };
  109202. MergeMeshesOptimization._UpdateSelectionTree = false;
  109203. return MergeMeshesOptimization;
  109204. }(SceneOptimization));
  109205. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  109206. /**
  109207. * Defines a list of options used by SceneOptimizer
  109208. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109209. */
  109210. var SceneOptimizerOptions = /** @class */ (function () {
  109211. /**
  109212. * Creates a new list of options used by SceneOptimizer
  109213. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  109214. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  109215. */
  109216. function SceneOptimizerOptions(
  109217. /**
  109218. * Defines the target frame rate to reach (60 by default)
  109219. */
  109220. targetFrameRate,
  109221. /**
  109222. * Defines the interval between two checkes (2000ms by default)
  109223. */
  109224. trackerDuration) {
  109225. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  109226. if (trackerDuration === void 0) { trackerDuration = 2000; }
  109227. this.targetFrameRate = targetFrameRate;
  109228. this.trackerDuration = trackerDuration;
  109229. /**
  109230. * Gets the list of optimizations to apply
  109231. */
  109232. this.optimizations = new Array();
  109233. }
  109234. /**
  109235. * Add a new optimization
  109236. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  109237. * @returns the current SceneOptimizerOptions
  109238. */
  109239. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  109240. this.optimizations.push(optimization);
  109241. return this;
  109242. };
  109243. /**
  109244. * Add a new custom optimization
  109245. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  109246. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  109247. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109248. * @returns the current SceneOptimizerOptions
  109249. */
  109250. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  109251. if (priority === void 0) { priority = 0; }
  109252. var optimization = new CustomOptimization(priority);
  109253. optimization.onApply = onApply;
  109254. optimization.onGetDescription = onGetDescription;
  109255. this.optimizations.push(optimization);
  109256. return this;
  109257. };
  109258. /**
  109259. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  109260. * @param targetFrameRate defines the target frame rate (60 by default)
  109261. * @returns a SceneOptimizerOptions object
  109262. */
  109263. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  109264. var result = new SceneOptimizerOptions(targetFrameRate);
  109265. var priority = 0;
  109266. result.addOptimization(new MergeMeshesOptimization(priority));
  109267. result.addOptimization(new ShadowsOptimization(priority));
  109268. result.addOptimization(new LensFlaresOptimization(priority));
  109269. // Next priority
  109270. priority++;
  109271. result.addOptimization(new PostProcessesOptimization(priority));
  109272. result.addOptimization(new ParticlesOptimization(priority));
  109273. // Next priority
  109274. priority++;
  109275. result.addOptimization(new TextureOptimization(priority, 1024));
  109276. return result;
  109277. };
  109278. /**
  109279. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  109280. * @param targetFrameRate defines the target frame rate (60 by default)
  109281. * @returns a SceneOptimizerOptions object
  109282. */
  109283. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  109284. var result = new SceneOptimizerOptions(targetFrameRate);
  109285. var priority = 0;
  109286. result.addOptimization(new MergeMeshesOptimization(priority));
  109287. result.addOptimization(new ShadowsOptimization(priority));
  109288. result.addOptimization(new LensFlaresOptimization(priority));
  109289. // Next priority
  109290. priority++;
  109291. result.addOptimization(new PostProcessesOptimization(priority));
  109292. result.addOptimization(new ParticlesOptimization(priority));
  109293. // Next priority
  109294. priority++;
  109295. result.addOptimization(new TextureOptimization(priority, 512));
  109296. // Next priority
  109297. priority++;
  109298. result.addOptimization(new RenderTargetsOptimization(priority));
  109299. // Next priority
  109300. priority++;
  109301. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  109302. return result;
  109303. };
  109304. /**
  109305. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  109306. * @param targetFrameRate defines the target frame rate (60 by default)
  109307. * @returns a SceneOptimizerOptions object
  109308. */
  109309. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  109310. var result = new SceneOptimizerOptions(targetFrameRate);
  109311. var priority = 0;
  109312. result.addOptimization(new MergeMeshesOptimization(priority));
  109313. result.addOptimization(new ShadowsOptimization(priority));
  109314. result.addOptimization(new LensFlaresOptimization(priority));
  109315. // Next priority
  109316. priority++;
  109317. result.addOptimization(new PostProcessesOptimization(priority));
  109318. result.addOptimization(new ParticlesOptimization(priority));
  109319. // Next priority
  109320. priority++;
  109321. result.addOptimization(new TextureOptimization(priority, 256));
  109322. // Next priority
  109323. priority++;
  109324. result.addOptimization(new RenderTargetsOptimization(priority));
  109325. // Next priority
  109326. priority++;
  109327. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  109328. return result;
  109329. };
  109330. return SceneOptimizerOptions;
  109331. }());
  109332. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  109333. /**
  109334. * Class used to run optimizations in order to reach a target frame rate
  109335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109336. */
  109337. var SceneOptimizer = /** @class */ (function () {
  109338. /**
  109339. * Creates a new SceneOptimizer
  109340. * @param scene defines the scene to work on
  109341. * @param options defines the options to use with the SceneOptimizer
  109342. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  109343. * @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)
  109344. */
  109345. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  109346. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  109347. if (improvementMode === void 0) { improvementMode = false; }
  109348. var _this = this;
  109349. this._isRunning = false;
  109350. this._currentPriorityLevel = 0;
  109351. this._targetFrameRate = 60;
  109352. this._trackerDuration = 2000;
  109353. this._currentFrameRate = 0;
  109354. this._improvementMode = false;
  109355. /**
  109356. * Defines an observable called when the optimizer reaches the target frame rate
  109357. */
  109358. this.onSuccessObservable = new BABYLON.Observable();
  109359. /**
  109360. * Defines an observable called when the optimizer enables an optimization
  109361. */
  109362. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  109363. /**
  109364. * Defines an observable called when the optimizer is not able to reach the target frame rate
  109365. */
  109366. this.onFailureObservable = new BABYLON.Observable();
  109367. if (!options) {
  109368. this._options = new SceneOptimizerOptions();
  109369. }
  109370. else {
  109371. this._options = options;
  109372. }
  109373. if (this._options.targetFrameRate) {
  109374. this._targetFrameRate = this._options.targetFrameRate;
  109375. }
  109376. if (this._options.trackerDuration) {
  109377. this._trackerDuration = this._options.trackerDuration;
  109378. }
  109379. if (autoGeneratePriorities) {
  109380. var priority = 0;
  109381. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  109382. var optim = _a[_i];
  109383. optim.priority = priority++;
  109384. }
  109385. }
  109386. this._improvementMode = improvementMode;
  109387. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109388. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  109389. _this._sceneDisposeObserver = null;
  109390. _this.dispose();
  109391. });
  109392. }
  109393. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  109394. /**
  109395. * Gets a boolean indicating if the optimizer is in improvement mode
  109396. */
  109397. get: function () {
  109398. return this._improvementMode;
  109399. },
  109400. enumerable: true,
  109401. configurable: true
  109402. });
  109403. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  109404. /**
  109405. * Gets the current priority level (0 at start)
  109406. */
  109407. get: function () {
  109408. return this._currentPriorityLevel;
  109409. },
  109410. enumerable: true,
  109411. configurable: true
  109412. });
  109413. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  109414. /**
  109415. * Gets the current frame rate checked by the SceneOptimizer
  109416. */
  109417. get: function () {
  109418. return this._currentFrameRate;
  109419. },
  109420. enumerable: true,
  109421. configurable: true
  109422. });
  109423. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  109424. /**
  109425. * Gets or sets the current target frame rate (60 by default)
  109426. */
  109427. get: function () {
  109428. return this._targetFrameRate;
  109429. },
  109430. /**
  109431. * Gets or sets the current target frame rate (60 by default)
  109432. */
  109433. set: function (value) {
  109434. this._targetFrameRate = value;
  109435. },
  109436. enumerable: true,
  109437. configurable: true
  109438. });
  109439. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  109440. /**
  109441. * Gets or sets the current interval between two checks (every 2000ms by default)
  109442. */
  109443. get: function () {
  109444. return this._trackerDuration;
  109445. },
  109446. /**
  109447. * Gets or sets the current interval between two checks (every 2000ms by default)
  109448. */
  109449. set: function (value) {
  109450. this._trackerDuration = value;
  109451. },
  109452. enumerable: true,
  109453. configurable: true
  109454. });
  109455. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  109456. /**
  109457. * Gets the list of active optimizations
  109458. */
  109459. get: function () {
  109460. return this._options.optimizations;
  109461. },
  109462. enumerable: true,
  109463. configurable: true
  109464. });
  109465. /**
  109466. * Stops the current optimizer
  109467. */
  109468. SceneOptimizer.prototype.stop = function () {
  109469. this._isRunning = false;
  109470. };
  109471. /**
  109472. * Reset the optimizer to initial step (current priority level = 0)
  109473. */
  109474. SceneOptimizer.prototype.reset = function () {
  109475. this._currentPriorityLevel = 0;
  109476. };
  109477. /**
  109478. * Start the optimizer. By default it will try to reach a specific framerate
  109479. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  109480. */
  109481. SceneOptimizer.prototype.start = function () {
  109482. var _this = this;
  109483. if (this._isRunning) {
  109484. return;
  109485. }
  109486. this._isRunning = true;
  109487. // Let's wait for the scene to be ready before running our check
  109488. this._scene.executeWhenReady(function () {
  109489. setTimeout(function () {
  109490. _this._checkCurrentState();
  109491. }, _this._trackerDuration);
  109492. });
  109493. };
  109494. SceneOptimizer.prototype._checkCurrentState = function () {
  109495. var _this = this;
  109496. if (!this._isRunning) {
  109497. return;
  109498. }
  109499. var scene = this._scene;
  109500. var options = this._options;
  109501. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  109502. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  109503. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  109504. this._isRunning = false;
  109505. this.onSuccessObservable.notifyObservers(this);
  109506. return;
  109507. }
  109508. // Apply current level of optimizations
  109509. var allDone = true;
  109510. var noOptimizationApplied = true;
  109511. for (var index = 0; index < options.optimizations.length; index++) {
  109512. var optimization = options.optimizations[index];
  109513. if (optimization.priority === this._currentPriorityLevel) {
  109514. noOptimizationApplied = false;
  109515. allDone = allDone && optimization.apply(scene, this);
  109516. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  109517. }
  109518. }
  109519. // If no optimization was applied, this is a failure :(
  109520. if (noOptimizationApplied) {
  109521. this._isRunning = false;
  109522. this.onFailureObservable.notifyObservers(this);
  109523. return;
  109524. }
  109525. // If all optimizations were done, move to next level
  109526. if (allDone) {
  109527. this._currentPriorityLevel++;
  109528. }
  109529. // Let's the system running for a specific amount of time before checking FPS
  109530. scene.executeWhenReady(function () {
  109531. setTimeout(function () {
  109532. _this._checkCurrentState();
  109533. }, _this._trackerDuration);
  109534. });
  109535. };
  109536. /**
  109537. * Release all resources
  109538. */
  109539. SceneOptimizer.prototype.dispose = function () {
  109540. this.stop();
  109541. this.onSuccessObservable.clear();
  109542. this.onFailureObservable.clear();
  109543. this.onNewOptimizationAppliedObservable.clear();
  109544. if (this._sceneDisposeObserver) {
  109545. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  109546. }
  109547. };
  109548. /**
  109549. * Helper function to create a SceneOptimizer with one single line of code
  109550. * @param scene defines the scene to work on
  109551. * @param options defines the options to use with the SceneOptimizer
  109552. * @param onSuccess defines a callback to call on success
  109553. * @param onFailure defines a callback to call on failure
  109554. * @returns the new SceneOptimizer object
  109555. */
  109556. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  109557. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  109558. if (onSuccess) {
  109559. optimizer.onSuccessObservable.add(function () {
  109560. onSuccess();
  109561. });
  109562. }
  109563. if (onFailure) {
  109564. optimizer.onFailureObservable.add(function () {
  109565. onFailure();
  109566. });
  109567. }
  109568. optimizer.start();
  109569. return optimizer;
  109570. };
  109571. return SceneOptimizer;
  109572. }());
  109573. BABYLON.SceneOptimizer = SceneOptimizer;
  109574. })(BABYLON || (BABYLON = {}));
  109575. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  109576. var BABYLON;
  109577. (function (BABYLON) {
  109578. /**
  109579. * Gets the outline renderer associated with the scene
  109580. * @returns a OutlineRenderer
  109581. */
  109582. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  109583. if (!this._outlineRenderer) {
  109584. this._outlineRenderer = new OutlineRenderer(this);
  109585. }
  109586. return this._outlineRenderer;
  109587. };
  109588. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  109589. get: function () {
  109590. return this._renderOutline;
  109591. },
  109592. set: function (value) {
  109593. if (value) {
  109594. // Lazy Load the component.
  109595. this.getScene().getOutlineRenderer();
  109596. }
  109597. this._renderOutline = value;
  109598. },
  109599. enumerable: true,
  109600. configurable: true
  109601. });
  109602. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  109603. get: function () {
  109604. return this._renderOverlay;
  109605. },
  109606. set: function (value) {
  109607. if (value) {
  109608. // Lazy Load the component.
  109609. this.getScene().getOutlineRenderer();
  109610. }
  109611. this._renderOverlay = value;
  109612. },
  109613. enumerable: true,
  109614. configurable: true
  109615. });
  109616. /**
  109617. * This class is responsible to draw bothe outline/overlay of meshes.
  109618. * It should not be used directly but through the available method on mesh.
  109619. */
  109620. var OutlineRenderer = /** @class */ (function () {
  109621. /**
  109622. * Instantiates a new outline renderer. (There could be only one per scene).
  109623. * @param scene Defines the scene it belongs to
  109624. */
  109625. function OutlineRenderer(scene) {
  109626. /**
  109627. * The name of the component. Each component must have a unique name.
  109628. */
  109629. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  109630. /**
  109631. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  109632. */
  109633. this.zOffset = 1;
  109634. this.scene = scene;
  109635. this._engine = scene.getEngine();
  109636. this.scene._addComponent(this);
  109637. }
  109638. /**
  109639. * Register the component to one instance of a scene.
  109640. */
  109641. OutlineRenderer.prototype.register = function () {
  109642. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  109643. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  109644. };
  109645. /**
  109646. * Rebuilds the elements related to this component in case of
  109647. * context lost for instance.
  109648. */
  109649. OutlineRenderer.prototype.rebuild = function () {
  109650. // Nothing to do here.
  109651. };
  109652. /**
  109653. * Disposes the component and the associated ressources.
  109654. */
  109655. OutlineRenderer.prototype.dispose = function () {
  109656. // Nothing to do here.
  109657. };
  109658. /**
  109659. * Renders the outline in the canvas.
  109660. * @param subMesh Defines the sumesh to render
  109661. * @param batch Defines the batch of meshes in case of instances
  109662. * @param useOverlay Defines if the rendering is for the overlay or the outline
  109663. */
  109664. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  109665. var _this = this;
  109666. if (useOverlay === void 0) { useOverlay = false; }
  109667. var scene = this.scene;
  109668. var engine = scene.getEngine();
  109669. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109670. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  109671. return;
  109672. }
  109673. var mesh = subMesh.getRenderingMesh();
  109674. var material = subMesh.getMaterial();
  109675. if (!material || !scene.activeCamera) {
  109676. return;
  109677. }
  109678. engine.enableEffect(this._effect);
  109679. // Logarithmic depth
  109680. if (material.useLogarithmicDepth) {
  109681. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  109682. }
  109683. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  109684. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  109685. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  109686. // Bones
  109687. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109688. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109689. }
  109690. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  109691. // Alpha test
  109692. if (material && material.needAlphaTesting()) {
  109693. var alphaTexture = material.getAlphaTestTexture();
  109694. if (alphaTexture) {
  109695. this._effect.setTexture("diffuseSampler", alphaTexture);
  109696. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  109697. }
  109698. }
  109699. engine.setZOffset(-this.zOffset);
  109700. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  109701. engine.setZOffset(0);
  109702. };
  109703. /**
  109704. * Returns whether or not the outline renderer is ready for a given submesh.
  109705. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  109706. * @param subMesh Defines the submesh to check readyness for
  109707. * @param useInstances Defines wheter wee are trying to render instances or not
  109708. * @returns true if ready otherwise false
  109709. */
  109710. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  109711. var defines = [];
  109712. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  109713. var mesh = subMesh.getMesh();
  109714. var material = subMesh.getMaterial();
  109715. if (material) {
  109716. // Alpha test
  109717. if (material.needAlphaTesting()) {
  109718. defines.push("#define ALPHATEST");
  109719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109720. attribs.push(BABYLON.VertexBuffer.UVKind);
  109721. defines.push("#define UV1");
  109722. }
  109723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  109724. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109725. defines.push("#define UV2");
  109726. }
  109727. }
  109728. //Logarithmic depth
  109729. if (material.useLogarithmicDepth) {
  109730. defines.push("#define LOGARITHMICDEPTH");
  109731. }
  109732. }
  109733. // Bones
  109734. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109735. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109736. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109737. if (mesh.numBoneInfluencers > 4) {
  109738. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109739. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109740. }
  109741. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109742. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  109743. }
  109744. else {
  109745. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109746. }
  109747. // Instances
  109748. if (useInstances) {
  109749. defines.push("#define INSTANCES");
  109750. attribs.push("world0");
  109751. attribs.push("world1");
  109752. attribs.push("world2");
  109753. attribs.push("world3");
  109754. }
  109755. // Get correct effect
  109756. var join = defines.join("\n");
  109757. if (this._cachedDefines !== join) {
  109758. this._cachedDefines = join;
  109759. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  109760. }
  109761. return this._effect.isReady();
  109762. };
  109763. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  109764. // Outline - step 1
  109765. this._savedDepthWrite = this._engine.getDepthWrite();
  109766. if (mesh.renderOutline) {
  109767. this._engine.setDepthWrite(false);
  109768. this.render(subMesh, batch);
  109769. this._engine.setDepthWrite(this._savedDepthWrite);
  109770. }
  109771. };
  109772. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  109773. // Outline - step 2
  109774. if (mesh.renderOutline && this._savedDepthWrite) {
  109775. this._engine.setDepthWrite(true);
  109776. this._engine.setColorWrite(false);
  109777. this.render(subMesh, batch);
  109778. this._engine.setColorWrite(true);
  109779. }
  109780. // Overlay
  109781. if (mesh.renderOverlay) {
  109782. var currentMode = this._engine.getAlphaMode();
  109783. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  109784. this.render(subMesh, batch, true);
  109785. this._engine.setAlphaMode(currentMode);
  109786. }
  109787. };
  109788. return OutlineRenderer;
  109789. }());
  109790. BABYLON.OutlineRenderer = OutlineRenderer;
  109791. })(BABYLON || (BABYLON = {}));
  109792. //# sourceMappingURL=babylon.outlineRenderer.js.map
  109793. var BABYLON;
  109794. (function (BABYLON) {
  109795. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  109796. if (this._edgesRenderer) {
  109797. this._edgesRenderer.dispose();
  109798. this._edgesRenderer = null;
  109799. }
  109800. return this;
  109801. };
  109802. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  109803. if (epsilon === void 0) { epsilon = 0.95; }
  109804. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  109805. this.disableEdgesRendering();
  109806. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  109807. return this;
  109808. };
  109809. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  109810. get: function () {
  109811. return this._edgesRenderer;
  109812. },
  109813. enumerable: true,
  109814. configurable: true
  109815. });
  109816. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  109817. if (epsilon === void 0) { epsilon = 0.95; }
  109818. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  109819. this.disableEdgesRendering();
  109820. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  109821. return this;
  109822. };
  109823. /**
  109824. * FaceAdjacencies Helper class to generate edges
  109825. */
  109826. var FaceAdjacencies = /** @class */ (function () {
  109827. function FaceAdjacencies() {
  109828. this.edges = new Array();
  109829. this.edgesConnectedCount = 0;
  109830. }
  109831. return FaceAdjacencies;
  109832. }());
  109833. /**
  109834. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  109835. */
  109836. var EdgesRenderer = /** @class */ (function () {
  109837. /**
  109838. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  109839. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  109840. * @param source Mesh used to create edges
  109841. * @param epsilon sum of angles in adjacency to check for edge
  109842. * @param checkVerticesInsteadOfIndices
  109843. * @param generateEdgesLines - should generate Lines or only prepare resources.
  109844. */
  109845. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  109846. if (epsilon === void 0) { epsilon = 0.95; }
  109847. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  109848. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  109849. var _this = this;
  109850. /**
  109851. * Define the size of the edges with an orthographic camera
  109852. */
  109853. this.edgesWidthScalerForOrthographic = 1000.0;
  109854. /**
  109855. * Define the size of the edges with a perspective camera
  109856. */
  109857. this.edgesWidthScalerForPerspective = 50.0;
  109858. this._linesPositions = new Array();
  109859. this._linesNormals = new Array();
  109860. this._linesIndices = new Array();
  109861. this._buffers = {};
  109862. this._checkVerticesInsteadOfIndices = false;
  109863. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  109864. this.isEnabled = true;
  109865. this._source = source;
  109866. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  109867. this._epsilon = epsilon;
  109868. this._prepareRessources();
  109869. if (generateEdgesLines) {
  109870. this._generateEdgesLines();
  109871. }
  109872. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  109873. _this._rebuild();
  109874. });
  109875. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  109876. _this.dispose();
  109877. });
  109878. }
  109879. EdgesRenderer.prototype._prepareRessources = function () {
  109880. if (this._lineShader) {
  109881. return;
  109882. }
  109883. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  109884. attributes: ["position", "normal"],
  109885. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  109886. });
  109887. this._lineShader.disableDepthWrite = true;
  109888. this._lineShader.backFaceCulling = false;
  109889. };
  109890. /** @hidden */
  109891. EdgesRenderer.prototype._rebuild = function () {
  109892. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  109893. if (buffer) {
  109894. buffer._rebuild();
  109895. }
  109896. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  109897. if (buffer) {
  109898. buffer._rebuild();
  109899. }
  109900. var scene = this._source.getScene();
  109901. var engine = scene.getEngine();
  109902. this._ib = engine.createIndexBuffer(this._linesIndices);
  109903. };
  109904. /**
  109905. * Releases the required resources for the edges renderer
  109906. */
  109907. EdgesRenderer.prototype.dispose = function () {
  109908. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  109909. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  109910. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  109911. if (buffer) {
  109912. buffer.dispose();
  109913. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  109914. }
  109915. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  109916. if (buffer) {
  109917. buffer.dispose();
  109918. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  109919. }
  109920. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  109921. this._lineShader.dispose();
  109922. };
  109923. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  109924. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  109925. return 0;
  109926. }
  109927. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  109928. return 1;
  109929. }
  109930. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  109931. return 2;
  109932. }
  109933. return -1;
  109934. };
  109935. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  109936. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  109937. return 0;
  109938. }
  109939. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  109940. return 1;
  109941. }
  109942. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  109943. return 2;
  109944. }
  109945. return -1;
  109946. };
  109947. /**
  109948. * Checks if the pair of p0 and p1 is en edge
  109949. * @param faceIndex
  109950. * @param edge
  109951. * @param faceNormals
  109952. * @param p0
  109953. * @param p1
  109954. * @private
  109955. */
  109956. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  109957. var needToCreateLine;
  109958. if (edge === undefined) {
  109959. needToCreateLine = true;
  109960. }
  109961. else {
  109962. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  109963. needToCreateLine = dotProduct < this._epsilon;
  109964. }
  109965. if (needToCreateLine) {
  109966. var offset = this._linesPositions.length / 3;
  109967. var normal = p0.subtract(p1);
  109968. normal.normalize();
  109969. // Positions
  109970. this._linesPositions.push(p0.x);
  109971. this._linesPositions.push(p0.y);
  109972. this._linesPositions.push(p0.z);
  109973. this._linesPositions.push(p0.x);
  109974. this._linesPositions.push(p0.y);
  109975. this._linesPositions.push(p0.z);
  109976. this._linesPositions.push(p1.x);
  109977. this._linesPositions.push(p1.y);
  109978. this._linesPositions.push(p1.z);
  109979. this._linesPositions.push(p1.x);
  109980. this._linesPositions.push(p1.y);
  109981. this._linesPositions.push(p1.z);
  109982. // Normals
  109983. this._linesNormals.push(p1.x);
  109984. this._linesNormals.push(p1.y);
  109985. this._linesNormals.push(p1.z);
  109986. this._linesNormals.push(-1);
  109987. this._linesNormals.push(p1.x);
  109988. this._linesNormals.push(p1.y);
  109989. this._linesNormals.push(p1.z);
  109990. this._linesNormals.push(1);
  109991. this._linesNormals.push(p0.x);
  109992. this._linesNormals.push(p0.y);
  109993. this._linesNormals.push(p0.z);
  109994. this._linesNormals.push(-1);
  109995. this._linesNormals.push(p0.x);
  109996. this._linesNormals.push(p0.y);
  109997. this._linesNormals.push(p0.z);
  109998. this._linesNormals.push(1);
  109999. // Indices
  110000. this._linesIndices.push(offset);
  110001. this._linesIndices.push(offset + 1);
  110002. this._linesIndices.push(offset + 2);
  110003. this._linesIndices.push(offset);
  110004. this._linesIndices.push(offset + 2);
  110005. this._linesIndices.push(offset + 3);
  110006. }
  110007. };
  110008. /**
  110009. * Generates lines edges from adjacencjes
  110010. * @private
  110011. */
  110012. EdgesRenderer.prototype._generateEdgesLines = function () {
  110013. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110014. var indices = this._source.getIndices();
  110015. if (!indices || !positions) {
  110016. return;
  110017. }
  110018. // First let's find adjacencies
  110019. var adjacencies = new Array();
  110020. var faceNormals = new Array();
  110021. var index;
  110022. var faceAdjacencies;
  110023. // Prepare faces
  110024. for (index = 0; index < indices.length; index += 3) {
  110025. faceAdjacencies = new FaceAdjacencies();
  110026. var p0Index = indices[index];
  110027. var p1Index = indices[index + 1];
  110028. var p2Index = indices[index + 2];
  110029. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  110030. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  110031. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  110032. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  110033. faceNormal.normalize();
  110034. faceNormals.push(faceNormal);
  110035. adjacencies.push(faceAdjacencies);
  110036. }
  110037. // Scan
  110038. for (index = 0; index < adjacencies.length; index++) {
  110039. faceAdjacencies = adjacencies[index];
  110040. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  110041. var otherFaceAdjacencies = adjacencies[otherIndex];
  110042. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  110043. break;
  110044. }
  110045. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  110046. continue;
  110047. }
  110048. var otherP0 = indices[otherIndex * 3];
  110049. var otherP1 = indices[otherIndex * 3 + 1];
  110050. var otherP2 = indices[otherIndex * 3 + 2];
  110051. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  110052. var otherEdgeIndex = 0;
  110053. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  110054. continue;
  110055. }
  110056. switch (edgeIndex) {
  110057. case 0:
  110058. if (this._checkVerticesInsteadOfIndices) {
  110059. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110060. }
  110061. else {
  110062. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  110063. }
  110064. break;
  110065. case 1:
  110066. if (this._checkVerticesInsteadOfIndices) {
  110067. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110068. }
  110069. else {
  110070. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  110071. }
  110072. break;
  110073. case 2:
  110074. if (this._checkVerticesInsteadOfIndices) {
  110075. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110076. }
  110077. else {
  110078. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  110079. }
  110080. break;
  110081. }
  110082. if (otherEdgeIndex === -1) {
  110083. continue;
  110084. }
  110085. faceAdjacencies.edges[edgeIndex] = otherIndex;
  110086. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  110087. faceAdjacencies.edgesConnectedCount++;
  110088. otherFaceAdjacencies.edgesConnectedCount++;
  110089. if (faceAdjacencies.edgesConnectedCount === 3) {
  110090. break;
  110091. }
  110092. }
  110093. }
  110094. }
  110095. // Create lines
  110096. for (index = 0; index < adjacencies.length; index++) {
  110097. // 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
  110098. var current = adjacencies[index];
  110099. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110100. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  110101. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  110102. }
  110103. // Merge into a single mesh
  110104. var engine = this._source.getScene().getEngine();
  110105. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110106. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110107. this._ib = engine.createIndexBuffer(this._linesIndices);
  110108. this._indicesCount = this._linesIndices.length;
  110109. };
  110110. /**
  110111. * Checks wether or not the edges renderer is ready to render.
  110112. * @return true if ready, otherwise false.
  110113. */
  110114. EdgesRenderer.prototype.isReady = function () {
  110115. return this._lineShader.isReady();
  110116. };
  110117. /**
  110118. * Renders the edges of the attached mesh,
  110119. */
  110120. EdgesRenderer.prototype.render = function () {
  110121. var scene = this._source.getScene();
  110122. if (!this.isReady() || !scene.activeCamera) {
  110123. return;
  110124. }
  110125. var engine = scene.getEngine();
  110126. this._lineShader._preBind();
  110127. if (this._source.edgesColor.a !== 1) {
  110128. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110129. }
  110130. else {
  110131. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110132. }
  110133. // VBOs
  110134. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  110135. scene.resetCachedMaterial();
  110136. this._lineShader.setColor4("color", this._source.edgesColor);
  110137. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  110138. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  110139. }
  110140. else {
  110141. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  110142. }
  110143. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  110144. this._lineShader.bind(this._source.getWorldMatrix());
  110145. // Draw order
  110146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  110147. this._lineShader.unbind();
  110148. };
  110149. return EdgesRenderer;
  110150. }());
  110151. BABYLON.EdgesRenderer = EdgesRenderer;
  110152. })(BABYLON || (BABYLON = {}));
  110153. //# sourceMappingURL=babylon.edgesRenderer.js.map
  110154. var BABYLON;
  110155. (function (BABYLON) {
  110156. /**
  110157. * FaceAdjacencies Helper class to generate edges
  110158. */
  110159. var FaceAdjacencies = /** @class */ (function () {
  110160. function FaceAdjacencies() {
  110161. this.edges = new Array();
  110162. this.edgesConnectedCount = 0;
  110163. }
  110164. return FaceAdjacencies;
  110165. }());
  110166. /**
  110167. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  110168. */
  110169. var LineEdgesRenderer = /** @class */ (function (_super) {
  110170. __extends(LineEdgesRenderer, _super);
  110171. /**
  110172. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  110173. * @param source LineMesh used to generate edges
  110174. * @param epsilon not important (specified angle for edge detection)
  110175. * @param checkVerticesInsteadOfIndices not important for LineMesh
  110176. */
  110177. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  110178. if (epsilon === void 0) { epsilon = 0.95; }
  110179. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110180. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  110181. _this._generateEdgesLines();
  110182. return _this;
  110183. }
  110184. /**
  110185. * Always create the edge since its a line so only important things are p0 and p1
  110186. * @param faceIndex not important for LineMesh
  110187. * @param edge not important for LineMesh
  110188. * @param faceNormals not important for LineMesh
  110189. * @param p0 beginnig of line
  110190. * @param p1 end of line
  110191. */
  110192. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110193. var offset = this._linesPositions.length / 3;
  110194. var normal = p0.subtract(p1);
  110195. normal.normalize();
  110196. // Positions
  110197. this._linesPositions.push(p0.x);
  110198. this._linesPositions.push(p0.y);
  110199. this._linesPositions.push(p0.z);
  110200. this._linesPositions.push(p0.x);
  110201. this._linesPositions.push(p0.y);
  110202. this._linesPositions.push(p0.z);
  110203. this._linesPositions.push(p1.x);
  110204. this._linesPositions.push(p1.y);
  110205. this._linesPositions.push(p1.z);
  110206. this._linesPositions.push(p1.x);
  110207. this._linesPositions.push(p1.y);
  110208. this._linesPositions.push(p1.z);
  110209. // Normals
  110210. this._linesNormals.push(p1.x);
  110211. this._linesNormals.push(p1.y);
  110212. this._linesNormals.push(p1.z);
  110213. this._linesNormals.push(-1);
  110214. this._linesNormals.push(p1.x);
  110215. this._linesNormals.push(p1.y);
  110216. this._linesNormals.push(p1.z);
  110217. this._linesNormals.push(1);
  110218. this._linesNormals.push(p0.x);
  110219. this._linesNormals.push(p0.y);
  110220. this._linesNormals.push(p0.z);
  110221. this._linesNormals.push(-1);
  110222. this._linesNormals.push(p0.x);
  110223. this._linesNormals.push(p0.y);
  110224. this._linesNormals.push(p0.z);
  110225. this._linesNormals.push(1);
  110226. // Indices
  110227. this._linesIndices.push(offset);
  110228. this._linesIndices.push(offset + 1);
  110229. this._linesIndices.push(offset + 2);
  110230. this._linesIndices.push(offset);
  110231. this._linesIndices.push(offset + 2);
  110232. this._linesIndices.push(offset + 3);
  110233. };
  110234. /**
  110235. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  110236. */
  110237. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  110238. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110239. var indices = this._source.getIndices();
  110240. if (!indices || !positions) {
  110241. return;
  110242. }
  110243. // First let's find adjacencies
  110244. var adjacencies = new Array();
  110245. var faceNormals = new Array();
  110246. var index;
  110247. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  110248. var currentAdjecancy = new FaceAdjacencies();
  110249. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  110250. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  110251. adjacencies.push(currentAdjecancy);
  110252. }
  110253. // Create lines
  110254. for (index = 0; index < adjacencies.length; index++) {
  110255. // 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
  110256. var current = adjacencies[index];
  110257. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110258. }
  110259. // Merge into a single mesh
  110260. var engine = this._source.getScene().getEngine();
  110261. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110262. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110263. this._ib = engine.createIndexBuffer(this._linesIndices);
  110264. this._indicesCount = this._linesIndices.length;
  110265. };
  110266. return LineEdgesRenderer;
  110267. }(BABYLON.EdgesRenderer));
  110268. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  110269. })(BABYLON || (BABYLON = {}));
  110270. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  110271. var BABYLON;
  110272. (function (BABYLON) {
  110273. // Adds the parser to the scene parsers.
  110274. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  110275. if (parsedData.effectLayers) {
  110276. if (!container.effectLayers) {
  110277. container.effectLayers = new Array();
  110278. }
  110279. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  110280. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  110281. container.effectLayers.push(effectLayer);
  110282. }
  110283. }
  110284. });
  110285. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  110286. var index = this.effectLayers.indexOf(toRemove);
  110287. if (index !== -1) {
  110288. this.effectLayers.splice(index, 1);
  110289. }
  110290. return index;
  110291. };
  110292. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  110293. this.effectLayers.push(newEffectLayer);
  110294. };
  110295. /**
  110296. * Defines the layer scene component responsible to manage any effect layers
  110297. * in a given scene.
  110298. */
  110299. var EffectLayerSceneComponent = /** @class */ (function () {
  110300. /**
  110301. * Creates a new instance of the component for the given scene
  110302. * @param scene Defines the scene to register the component in
  110303. */
  110304. function EffectLayerSceneComponent(scene) {
  110305. /**
  110306. * The component name helpfull to identify the component in the list of scene components.
  110307. */
  110308. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  110309. this._renderEffects = false;
  110310. this._needStencil = false;
  110311. this._previousStencilState = false;
  110312. this.scene = scene;
  110313. this._engine = scene.getEngine();
  110314. scene.effectLayers = new Array();
  110315. }
  110316. /**
  110317. * Registers the component in a given scene
  110318. */
  110319. EffectLayerSceneComponent.prototype.register = function () {
  110320. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  110321. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  110322. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  110323. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  110324. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  110325. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  110326. };
  110327. /**
  110328. * Rebuilds the elements related to this component in case of
  110329. * context lost for instance.
  110330. */
  110331. EffectLayerSceneComponent.prototype.rebuild = function () {
  110332. var layers = this.scene.effectLayers;
  110333. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110334. var effectLayer = layers_1[_i];
  110335. effectLayer._rebuild();
  110336. }
  110337. };
  110338. /**
  110339. * Serializes the component data to the specified json object
  110340. * @param serializationObject The object to serialize to
  110341. */
  110342. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  110343. // Effect layers
  110344. serializationObject.effectLayers = [];
  110345. var layers = this.scene.effectLayers;
  110346. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110347. var effectLayer = layers_2[_i];
  110348. if (effectLayer.serialize) {
  110349. serializationObject.effectLayers.push(effectLayer.serialize());
  110350. }
  110351. }
  110352. };
  110353. /**
  110354. * Adds all the element from the container to the scene
  110355. * @param container the container holding the elements
  110356. */
  110357. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  110358. var _this = this;
  110359. if (!container.effectLayers) {
  110360. return;
  110361. }
  110362. container.effectLayers.forEach(function (o) {
  110363. _this.scene.addEffectLayer(o);
  110364. });
  110365. };
  110366. /**
  110367. * Removes all the elements in the container from the scene
  110368. * @param container contains the elements to remove
  110369. */
  110370. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  110371. var _this = this;
  110372. if (!container.effectLayers) {
  110373. return;
  110374. }
  110375. container.effectLayers.forEach(function (o) {
  110376. _this.scene.removeEffectLayer(o);
  110377. });
  110378. };
  110379. /**
  110380. * Disposes the component and the associated ressources.
  110381. */
  110382. EffectLayerSceneComponent.prototype.dispose = function () {
  110383. var layers = this.scene.effectLayers;
  110384. while (layers.length) {
  110385. layers[0].dispose();
  110386. }
  110387. };
  110388. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  110389. var layers = this.scene.effectLayers;
  110390. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  110391. var layer = layers_3[_i];
  110392. if (!layer.hasMesh(mesh)) {
  110393. continue;
  110394. }
  110395. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  110396. var subMesh = _b[_a];
  110397. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  110398. return false;
  110399. }
  110400. }
  110401. }
  110402. return true;
  110403. };
  110404. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  110405. this._renderEffects = false;
  110406. this._needStencil = false;
  110407. var layers = this.scene.effectLayers;
  110408. if (layers && layers.length > 0) {
  110409. this._previousStencilState = this._engine.getStencilBuffer();
  110410. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  110411. var effectLayer = layers_4[_i];
  110412. if (effectLayer.shouldRender() &&
  110413. (!effectLayer.camera ||
  110414. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  110415. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  110416. this._renderEffects = true;
  110417. this._needStencil = this._needStencil || effectLayer.needStencil();
  110418. var renderTarget = effectLayer._mainTexture;
  110419. if (renderTarget._shouldRender()) {
  110420. this.scene.incrementRenderId();
  110421. renderTarget.render(false, false);
  110422. }
  110423. }
  110424. }
  110425. this.scene.incrementRenderId();
  110426. }
  110427. };
  110428. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  110429. // Activate effect Layer stencil
  110430. if (this._needStencil) {
  110431. this._engine.setStencilBuffer(true);
  110432. }
  110433. };
  110434. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  110435. // Restore effect Layer stencil
  110436. if (this._needStencil) {
  110437. this._engine.setStencilBuffer(this._previousStencilState);
  110438. }
  110439. };
  110440. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  110441. if (this._renderEffects) {
  110442. this._engine.setDepthBuffer(false);
  110443. var layers = this.scene.effectLayers;
  110444. for (var i = 0; i < layers.length; i++) {
  110445. var effectLayer = layers[i];
  110446. if (effectLayer.renderingGroupId === renderingGroupId) {
  110447. if (effectLayer.shouldRender()) {
  110448. effectLayer.render();
  110449. }
  110450. }
  110451. }
  110452. this._engine.setDepthBuffer(true);
  110453. }
  110454. };
  110455. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  110456. if (this._renderEffects) {
  110457. this._draw(-1);
  110458. }
  110459. };
  110460. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  110461. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  110462. this._draw(index);
  110463. }
  110464. };
  110465. return EffectLayerSceneComponent;
  110466. }());
  110467. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  110468. })(BABYLON || (BABYLON = {}));
  110469. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  110470. var __assign = (this && this.__assign) || function () {
  110471. __assign = Object.assign || function(t) {
  110472. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110473. s = arguments[i];
  110474. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110475. t[p] = s[p];
  110476. }
  110477. return t;
  110478. };
  110479. return __assign.apply(this, arguments);
  110480. };
  110481. var BABYLON;
  110482. (function (BABYLON) {
  110483. /**
  110484. * The effect layer Helps adding post process effect blended with the main pass.
  110485. *
  110486. * This can be for instance use to generate glow or higlight effects on the scene.
  110487. *
  110488. * The effect layer class can not be used directly and is intented to inherited from to be
  110489. * customized per effects.
  110490. */
  110491. var EffectLayer = /** @class */ (function () {
  110492. /**
  110493. * Instantiates a new effect Layer and references it in the scene.
  110494. * @param name The name of the layer
  110495. * @param scene The scene to use the layer in
  110496. */
  110497. function EffectLayer(
  110498. /** The Friendly of the effect in the scene */
  110499. name, scene) {
  110500. this._vertexBuffers = {};
  110501. this._maxSize = 0;
  110502. this._mainTextureDesiredSize = { width: 0, height: 0 };
  110503. this._shouldRender = true;
  110504. this._postProcesses = [];
  110505. this._textures = [];
  110506. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  110507. /**
  110508. * The clear color of the texture used to generate the glow map.
  110509. */
  110510. this.neutralColor = new BABYLON.Color4();
  110511. /**
  110512. * Specifies wether the highlight layer is enabled or not.
  110513. */
  110514. this.isEnabled = true;
  110515. /**
  110516. * An event triggered when the effect layer has been disposed.
  110517. */
  110518. this.onDisposeObservable = new BABYLON.Observable();
  110519. /**
  110520. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  110521. */
  110522. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  110523. /**
  110524. * An event triggered when the generated texture is being merged in the scene.
  110525. */
  110526. this.onBeforeComposeObservable = new BABYLON.Observable();
  110527. /**
  110528. * An event triggered when the generated texture has been merged in the scene.
  110529. */
  110530. this.onAfterComposeObservable = new BABYLON.Observable();
  110531. /**
  110532. * An event triggered when the efffect layer changes its size.
  110533. */
  110534. this.onSizeChangedObservable = new BABYLON.Observable();
  110535. this.name = name;
  110536. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110537. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  110538. if (!component) {
  110539. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  110540. this._scene._addComponent(component);
  110541. }
  110542. this._engine = this._scene.getEngine();
  110543. this._maxSize = this._engine.getCaps().maxTextureSize;
  110544. this._scene.effectLayers.push(this);
  110545. // Generate Buffers
  110546. this._generateIndexBuffer();
  110547. this._genrateVertexBuffer();
  110548. }
  110549. Object.defineProperty(EffectLayer.prototype, "camera", {
  110550. /**
  110551. * Gets the camera attached to the layer.
  110552. */
  110553. get: function () {
  110554. return this._effectLayerOptions.camera;
  110555. },
  110556. enumerable: true,
  110557. configurable: true
  110558. });
  110559. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  110560. /**
  110561. * Gets the rendering group id the layer should render in.
  110562. */
  110563. get: function () {
  110564. return this._effectLayerOptions.renderingGroupId;
  110565. },
  110566. enumerable: true,
  110567. configurable: true
  110568. });
  110569. /**
  110570. * Initializes the effect layer with the required options.
  110571. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  110572. */
  110573. EffectLayer.prototype._init = function (options) {
  110574. // Adapt options
  110575. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  110576. this._setMainTextureSize();
  110577. this._createMainTexture();
  110578. this._createTextureAndPostProcesses();
  110579. this._mergeEffect = this._createMergeEffect();
  110580. };
  110581. /**
  110582. * Generates the index buffer of the full screen quad blending to the main canvas.
  110583. */
  110584. EffectLayer.prototype._generateIndexBuffer = function () {
  110585. // Indices
  110586. var indices = [];
  110587. indices.push(0);
  110588. indices.push(1);
  110589. indices.push(2);
  110590. indices.push(0);
  110591. indices.push(2);
  110592. indices.push(3);
  110593. this._indexBuffer = this._engine.createIndexBuffer(indices);
  110594. };
  110595. /**
  110596. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  110597. */
  110598. EffectLayer.prototype._genrateVertexBuffer = function () {
  110599. // VBO
  110600. var vertices = [];
  110601. vertices.push(1, 1);
  110602. vertices.push(-1, 1);
  110603. vertices.push(-1, -1);
  110604. vertices.push(1, -1);
  110605. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110607. };
  110608. /**
  110609. * Sets the main texture desired size which is the closest power of two
  110610. * of the engine canvas size.
  110611. */
  110612. EffectLayer.prototype._setMainTextureSize = function () {
  110613. if (this._effectLayerOptions.mainTextureFixedSize) {
  110614. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  110615. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  110616. }
  110617. else {
  110618. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  110619. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  110620. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  110621. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  110622. }
  110623. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  110624. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  110625. };
  110626. /**
  110627. * Creates the main texture for the effect layer.
  110628. */
  110629. EffectLayer.prototype._createMainTexture = function () {
  110630. var _this = this;
  110631. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  110632. width: this._mainTextureDesiredSize.width,
  110633. height: this._mainTextureDesiredSize.height
  110634. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110635. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  110636. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110637. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110638. this._mainTexture.anisotropicFilteringLevel = 1;
  110639. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110640. this._mainTexture.renderParticles = false;
  110641. this._mainTexture.renderList = null;
  110642. this._mainTexture.ignoreCameraViewport = true;
  110643. // Custom render function
  110644. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  110645. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  110646. var index;
  110647. var engine = _this._scene.getEngine();
  110648. if (depthOnlySubMeshes.length) {
  110649. engine.setColorWrite(false);
  110650. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  110651. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  110652. }
  110653. engine.setColorWrite(true);
  110654. }
  110655. for (index = 0; index < opaqueSubMeshes.length; index++) {
  110656. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  110657. }
  110658. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  110659. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  110660. }
  110661. for (index = 0; index < transparentSubMeshes.length; index++) {
  110662. _this._renderSubMesh(transparentSubMeshes.data[index]);
  110663. }
  110664. };
  110665. this._mainTexture.onClearObservable.add(function (engine) {
  110666. engine.clear(_this.neutralColor, true, true, true);
  110667. });
  110668. };
  110669. /**
  110670. * Checks for the readiness of the element composing the layer.
  110671. * @param subMesh the mesh to check for
  110672. * @param useInstances specify wether or not to use instances to render the mesh
  110673. * @param emissiveTexture the associated emissive texture used to generate the glow
  110674. * @return true if ready otherwise, false
  110675. */
  110676. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  110677. var material = subMesh.getMaterial();
  110678. if (!material) {
  110679. return false;
  110680. }
  110681. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  110682. return false;
  110683. }
  110684. var defines = [];
  110685. var attribs = [BABYLON.VertexBuffer.PositionKind];
  110686. var mesh = subMesh.getMesh();
  110687. var uv1 = false;
  110688. var uv2 = false;
  110689. // Alpha test
  110690. if (material && material.needAlphaTesting()) {
  110691. var alphaTexture = material.getAlphaTestTexture();
  110692. if (alphaTexture) {
  110693. defines.push("#define ALPHATEST");
  110694. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  110695. alphaTexture.coordinatesIndex === 1) {
  110696. defines.push("#define DIFFUSEUV2");
  110697. uv2 = true;
  110698. }
  110699. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110700. defines.push("#define DIFFUSEUV1");
  110701. uv1 = true;
  110702. }
  110703. }
  110704. }
  110705. // Emissive
  110706. if (emissiveTexture) {
  110707. defines.push("#define EMISSIVE");
  110708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  110709. emissiveTexture.coordinatesIndex === 1) {
  110710. defines.push("#define EMISSIVEUV2");
  110711. uv2 = true;
  110712. }
  110713. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110714. defines.push("#define EMISSIVEUV1");
  110715. uv1 = true;
  110716. }
  110717. }
  110718. if (uv1) {
  110719. attribs.push(BABYLON.VertexBuffer.UVKind);
  110720. defines.push("#define UV1");
  110721. }
  110722. if (uv2) {
  110723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110724. defines.push("#define UV2");
  110725. }
  110726. // Bones
  110727. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  110728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  110729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  110730. if (mesh.numBoneInfluencers > 4) {
  110731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  110732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  110733. }
  110734. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  110735. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  110736. }
  110737. else {
  110738. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110739. }
  110740. // Morph targets
  110741. var manager = mesh.morphTargetManager;
  110742. var morphInfluencers = 0;
  110743. if (manager) {
  110744. if (manager.numInfluencers > 0) {
  110745. defines.push("#define MORPHTARGETS");
  110746. morphInfluencers = manager.numInfluencers;
  110747. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  110748. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  110749. }
  110750. }
  110751. // Instances
  110752. if (useInstances) {
  110753. defines.push("#define INSTANCES");
  110754. attribs.push("world0");
  110755. attribs.push("world1");
  110756. attribs.push("world2");
  110757. attribs.push("world3");
  110758. }
  110759. // Get correct effect
  110760. var join = defines.join("\n");
  110761. if (this._cachedDefines !== join) {
  110762. this._cachedDefines = join;
  110763. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  110764. }
  110765. return this._effectLayerMapGenerationEffect.isReady();
  110766. };
  110767. /**
  110768. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  110769. */
  110770. EffectLayer.prototype.render = function () {
  110771. var currentEffect = this._mergeEffect;
  110772. // Check
  110773. if (!currentEffect.isReady()) {
  110774. return;
  110775. }
  110776. for (var i = 0; i < this._postProcesses.length; i++) {
  110777. if (!this._postProcesses[i].isReady()) {
  110778. return;
  110779. }
  110780. }
  110781. var engine = this._scene.getEngine();
  110782. this.onBeforeComposeObservable.notifyObservers(this);
  110783. // Render
  110784. engine.enableEffect(currentEffect);
  110785. engine.setState(false);
  110786. // VBOs
  110787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  110788. // Cache
  110789. var previousAlphaMode = engine.getAlphaMode();
  110790. // Go Blend.
  110791. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  110792. // Blends the map on the main canvas.
  110793. this._internalRender(currentEffect);
  110794. // Restore Alpha
  110795. engine.setAlphaMode(previousAlphaMode);
  110796. this.onAfterComposeObservable.notifyObservers(this);
  110797. // Handle size changes.
  110798. var size = this._mainTexture.getSize();
  110799. this._setMainTextureSize();
  110800. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  110801. // Recreate RTT and post processes on size change.
  110802. this.onSizeChangedObservable.notifyObservers(this);
  110803. this._disposeTextureAndPostProcesses();
  110804. this._createMainTexture();
  110805. this._createTextureAndPostProcesses();
  110806. }
  110807. };
  110808. /**
  110809. * Determine if a given mesh will be used in the current effect.
  110810. * @param mesh mesh to test
  110811. * @returns true if the mesh will be used
  110812. */
  110813. EffectLayer.prototype.hasMesh = function (mesh) {
  110814. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  110815. return true;
  110816. }
  110817. return false;
  110818. };
  110819. /**
  110820. * Returns true if the layer contains information to display, otherwise false.
  110821. * @returns true if the glow layer should be rendered
  110822. */
  110823. EffectLayer.prototype.shouldRender = function () {
  110824. return this.isEnabled && this._shouldRender;
  110825. };
  110826. /**
  110827. * Returns true if the mesh should render, otherwise false.
  110828. * @param mesh The mesh to render
  110829. * @returns true if it should render otherwise false
  110830. */
  110831. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  110832. return true;
  110833. };
  110834. /**
  110835. * Returns true if the mesh should render, otherwise false.
  110836. * @param mesh The mesh to render
  110837. * @returns true if it should render otherwise false
  110838. */
  110839. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  110840. return true;
  110841. };
  110842. /**
  110843. * Renders the submesh passed in parameter to the generation map.
  110844. */
  110845. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  110846. var _this = this;
  110847. if (!this.shouldRender()) {
  110848. return;
  110849. }
  110850. var material = subMesh.getMaterial();
  110851. var mesh = subMesh.getRenderingMesh();
  110852. var scene = this._scene;
  110853. var engine = scene.getEngine();
  110854. if (!material) {
  110855. return;
  110856. }
  110857. // Do not block in blend mode.
  110858. if (material.needAlphaBlendingForMesh(mesh)) {
  110859. return;
  110860. }
  110861. // Culling
  110862. engine.setState(material.backFaceCulling);
  110863. // Managing instances
  110864. var batch = mesh._getInstancesRenderList(subMesh._id);
  110865. if (batch.mustReturn) {
  110866. return;
  110867. }
  110868. // Early Exit per mesh
  110869. if (!this._shouldRenderMesh(mesh)) {
  110870. return;
  110871. }
  110872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  110873. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  110874. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  110875. engine.enableEffect(this._effectLayerMapGenerationEffect);
  110876. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  110877. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  110878. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  110879. // Alpha test
  110880. if (material && material.needAlphaTesting()) {
  110881. var alphaTexture = material.getAlphaTestTexture();
  110882. if (alphaTexture) {
  110883. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  110884. var textureMatrix = alphaTexture.getTextureMatrix();
  110885. if (textureMatrix) {
  110886. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  110887. }
  110888. }
  110889. }
  110890. // Glow emissive only
  110891. if (this._emissiveTextureAndColor.texture) {
  110892. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  110893. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  110894. }
  110895. // Bones
  110896. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  110897. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  110898. }
  110899. // Morph targets
  110900. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  110901. // Draw
  110902. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  110903. }
  110904. else {
  110905. // Need to reset refresh rate of the main map
  110906. this._mainTexture.resetRefreshCounter();
  110907. }
  110908. };
  110909. /**
  110910. * Rebuild the required buffers.
  110911. * @hidden Internal use only.
  110912. */
  110913. EffectLayer.prototype._rebuild = function () {
  110914. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110915. if (vb) {
  110916. vb._rebuild();
  110917. }
  110918. this._generateIndexBuffer();
  110919. };
  110920. /**
  110921. * Dispose only the render target textures and post process.
  110922. */
  110923. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  110924. this._mainTexture.dispose();
  110925. for (var i = 0; i < this._postProcesses.length; i++) {
  110926. if (this._postProcesses[i]) {
  110927. this._postProcesses[i].dispose();
  110928. }
  110929. }
  110930. this._postProcesses = [];
  110931. for (var i = 0; i < this._textures.length; i++) {
  110932. if (this._textures[i]) {
  110933. this._textures[i].dispose();
  110934. }
  110935. }
  110936. this._textures = [];
  110937. };
  110938. /**
  110939. * Dispose the highlight layer and free resources.
  110940. */
  110941. EffectLayer.prototype.dispose = function () {
  110942. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110943. if (vertexBuffer) {
  110944. vertexBuffer.dispose();
  110945. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  110946. }
  110947. if (this._indexBuffer) {
  110948. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  110949. this._indexBuffer = null;
  110950. }
  110951. // Clean textures and post processes
  110952. this._disposeTextureAndPostProcesses();
  110953. // Remove from scene
  110954. var index = this._scene.effectLayers.indexOf(this, 0);
  110955. if (index > -1) {
  110956. this._scene.effectLayers.splice(index, 1);
  110957. }
  110958. // Callback
  110959. this.onDisposeObservable.notifyObservers(this);
  110960. this.onDisposeObservable.clear();
  110961. this.onBeforeRenderMainTextureObservable.clear();
  110962. this.onBeforeComposeObservable.clear();
  110963. this.onAfterComposeObservable.clear();
  110964. this.onSizeChangedObservable.clear();
  110965. };
  110966. /**
  110967. * Gets the class name of the effect layer
  110968. * @returns the string with the class name of the effect layer
  110969. */
  110970. EffectLayer.prototype.getClassName = function () {
  110971. return "EffectLayer";
  110972. };
  110973. /**
  110974. * Creates an effect layer from parsed effect layer data
  110975. * @param parsedEffectLayer defines effect layer data
  110976. * @param scene defines the current scene
  110977. * @param rootUrl defines the root URL containing the effect layer information
  110978. * @returns a parsed effect Layer
  110979. */
  110980. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  110981. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  110982. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  110983. };
  110984. __decorate([
  110985. BABYLON.serialize()
  110986. ], EffectLayer.prototype, "name", void 0);
  110987. __decorate([
  110988. BABYLON.serializeAsColor4()
  110989. ], EffectLayer.prototype, "neutralColor", void 0);
  110990. __decorate([
  110991. BABYLON.serialize()
  110992. ], EffectLayer.prototype, "isEnabled", void 0);
  110993. __decorate([
  110994. BABYLON.serializeAsCameraReference()
  110995. ], EffectLayer.prototype, "camera", null);
  110996. __decorate([
  110997. BABYLON.serialize()
  110998. ], EffectLayer.prototype, "renderingGroupId", null);
  110999. return EffectLayer;
  111000. }());
  111001. BABYLON.EffectLayer = EffectLayer;
  111002. })(BABYLON || (BABYLON = {}));
  111003. //# sourceMappingURL=babylon.effectLayer.js.map
  111004. var BABYLON;
  111005. (function (BABYLON) {
  111006. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  111007. for (var index = 0; index < this.effectLayers.length; index++) {
  111008. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  111009. return this.effectLayers[index];
  111010. }
  111011. }
  111012. return null;
  111013. };
  111014. /**
  111015. * Special Glow Blur post process only blurring the alpha channel
  111016. * It enforces keeping the most luminous color in the color channel.
  111017. */
  111018. var GlowBlurPostProcess = /** @class */ (function (_super) {
  111019. __extends(GlowBlurPostProcess, _super);
  111020. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  111021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  111022. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  111023. _this.direction = direction;
  111024. _this.kernel = kernel;
  111025. _this.onApplyObservable.add(function (effect) {
  111026. effect.setFloat2("screenSize", _this.width, _this.height);
  111027. effect.setVector2("direction", _this.direction);
  111028. effect.setFloat("blurWidth", _this.kernel);
  111029. });
  111030. return _this;
  111031. }
  111032. return GlowBlurPostProcess;
  111033. }(BABYLON.PostProcess));
  111034. /**
  111035. * The highlight layer Helps adding a glow effect around a mesh.
  111036. *
  111037. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111038. * glowy meshes to your scene.
  111039. *
  111040. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  111041. */
  111042. var HighlightLayer = /** @class */ (function (_super) {
  111043. __extends(HighlightLayer, _super);
  111044. /**
  111045. * Instantiates a new highlight Layer and references it to the scene..
  111046. * @param name The name of the layer
  111047. * @param scene The scene to use the layer in
  111048. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  111049. */
  111050. function HighlightLayer(name, scene, options) {
  111051. var _this = _super.call(this, name, scene) || this;
  111052. _this.name = name;
  111053. /**
  111054. * Specifies whether or not the inner glow is ACTIVE in the layer.
  111055. */
  111056. _this.innerGlow = true;
  111057. /**
  111058. * Specifies whether or not the outer glow is ACTIVE in the layer.
  111059. */
  111060. _this.outerGlow = true;
  111061. /**
  111062. * An event triggered when the highlight layer is being blurred.
  111063. */
  111064. _this.onBeforeBlurObservable = new BABYLON.Observable();
  111065. /**
  111066. * An event triggered when the highlight layer has been blurred.
  111067. */
  111068. _this.onAfterBlurObservable = new BABYLON.Observable();
  111069. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  111070. _this._meshes = {};
  111071. _this._excludedMeshes = {};
  111072. _this.neutralColor = HighlightLayer.NeutralColor;
  111073. // Warn on stencil
  111074. if (!_this._engine.isStencilEnable) {
  111075. 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 }");
  111076. }
  111077. // Adapt options
  111078. _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);
  111079. // Initialize the layer
  111080. _this._init({
  111081. alphaBlendingMode: _this._options.alphaBlendingMode,
  111082. camera: _this._options.camera,
  111083. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111084. mainTextureRatio: _this._options.mainTextureRatio,
  111085. renderingGroupId: _this._options.renderingGroupId
  111086. });
  111087. // Do not render as long as no meshes have been added
  111088. _this._shouldRender = false;
  111089. return _this;
  111090. }
  111091. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  111092. /**
  111093. * Gets the horizontal size of the blur.
  111094. */
  111095. get: function () {
  111096. return this._horizontalBlurPostprocess.kernel;
  111097. },
  111098. /**
  111099. * Specifies the horizontal size of the blur.
  111100. */
  111101. set: function (value) {
  111102. this._horizontalBlurPostprocess.kernel = value;
  111103. },
  111104. enumerable: true,
  111105. configurable: true
  111106. });
  111107. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  111108. /**
  111109. * Gets the vertical size of the blur.
  111110. */
  111111. get: function () {
  111112. return this._verticalBlurPostprocess.kernel;
  111113. },
  111114. /**
  111115. * Specifies the vertical size of the blur.
  111116. */
  111117. set: function (value) {
  111118. this._verticalBlurPostprocess.kernel = value;
  111119. },
  111120. enumerable: true,
  111121. configurable: true
  111122. });
  111123. /**
  111124. * Get the effect name of the layer.
  111125. * @return The effect name
  111126. */
  111127. HighlightLayer.prototype.getEffectName = function () {
  111128. return HighlightLayer.EffectName;
  111129. };
  111130. /**
  111131. * Create the merge effect. This is the shader use to blit the information back
  111132. * to the main canvas at the end of the scene rendering.
  111133. */
  111134. HighlightLayer.prototype._createMergeEffect = function () {
  111135. // Effect
  111136. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  111137. };
  111138. /**
  111139. * Creates the render target textures and post processes used in the highlight layer.
  111140. */
  111141. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  111142. var _this = this;
  111143. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  111144. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  111145. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111146. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111147. var textureType = 0;
  111148. if (this._engine.getCaps().textureHalfFloatRender) {
  111149. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111150. }
  111151. else {
  111152. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111153. }
  111154. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  111155. width: blurTextureWidth,
  111156. height: blurTextureHeight
  111157. }, this._scene, false, true, textureType);
  111158. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111159. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111160. this._blurTexture.anisotropicFilteringLevel = 16;
  111161. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  111162. this._blurTexture.renderParticles = false;
  111163. this._blurTexture.ignoreCameraViewport = true;
  111164. this._textures = [this._blurTexture];
  111165. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  111166. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111167. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  111168. effect.setTexture("textureSampler", _this._mainTexture);
  111169. });
  111170. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111171. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111172. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111173. });
  111174. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111175. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  111176. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111177. });
  111178. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111179. }
  111180. else {
  111181. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  111182. width: blurTextureWidth,
  111183. height: blurTextureHeight
  111184. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111185. this._horizontalBlurPostprocess.width = blurTextureWidth;
  111186. this._horizontalBlurPostprocess.height = blurTextureHeight;
  111187. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111188. effect.setTexture("textureSampler", _this._mainTexture);
  111189. });
  111190. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  111191. width: blurTextureWidth,
  111192. height: blurTextureHeight
  111193. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111194. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111195. }
  111196. this._mainTexture.onAfterUnbindObservable.add(function () {
  111197. _this.onBeforeBlurObservable.notifyObservers(_this);
  111198. var internalTexture = _this._blurTexture.getInternalTexture();
  111199. if (internalTexture) {
  111200. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  111201. }
  111202. _this.onAfterBlurObservable.notifyObservers(_this);
  111203. });
  111204. // Prevent autoClear.
  111205. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  111206. };
  111207. /**
  111208. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  111209. */
  111210. HighlightLayer.prototype.needStencil = function () {
  111211. return true;
  111212. };
  111213. /**
  111214. * Checks for the readiness of the element composing the layer.
  111215. * @param subMesh the mesh to check for
  111216. * @param useInstances specify wether or not to use instances to render the mesh
  111217. * @param emissiveTexture the associated emissive texture used to generate the glow
  111218. * @return true if ready otherwise, false
  111219. */
  111220. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  111221. var material = subMesh.getMaterial();
  111222. var mesh = subMesh.getRenderingMesh();
  111223. if (!material || !mesh || !this._meshes) {
  111224. return false;
  111225. }
  111226. var emissiveTexture = null;
  111227. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111228. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111229. emissiveTexture = material.emissiveTexture;
  111230. }
  111231. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  111232. };
  111233. /**
  111234. * Implementation specific of rendering the generating effect on the main canvas.
  111235. * @param effect The effect used to render through
  111236. */
  111237. HighlightLayer.prototype._internalRender = function (effect) {
  111238. // Texture
  111239. effect.setTexture("textureSampler", this._blurTexture);
  111240. // Cache
  111241. var engine = this._engine;
  111242. var previousStencilBuffer = engine.getStencilBuffer();
  111243. var previousStencilFunction = engine.getStencilFunction();
  111244. var previousStencilMask = engine.getStencilMask();
  111245. var previousStencilOperationPass = engine.getStencilOperationPass();
  111246. var previousStencilOperationFail = engine.getStencilOperationFail();
  111247. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  111248. var previousStencilReference = engine.getStencilFunctionReference();
  111249. // Stencil operations
  111250. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  111251. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  111252. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  111253. // Draw order
  111254. engine.setStencilMask(0x00);
  111255. engine.setStencilBuffer(true);
  111256. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  111257. // 2 passes inner outer
  111258. if (this.outerGlow) {
  111259. effect.setFloat("offset", 0);
  111260. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  111261. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111262. }
  111263. if (this.innerGlow) {
  111264. effect.setFloat("offset", 1);
  111265. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  111266. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111267. }
  111268. // Restore Cache
  111269. engine.setStencilFunction(previousStencilFunction);
  111270. engine.setStencilMask(previousStencilMask);
  111271. engine.setStencilBuffer(previousStencilBuffer);
  111272. engine.setStencilOperationPass(previousStencilOperationPass);
  111273. engine.setStencilOperationFail(previousStencilOperationFail);
  111274. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  111275. engine.setStencilFunctionReference(previousStencilReference);
  111276. };
  111277. /**
  111278. * Returns true if the layer contains information to display, otherwise false.
  111279. */
  111280. HighlightLayer.prototype.shouldRender = function () {
  111281. if (_super.prototype.shouldRender.call(this)) {
  111282. return this._meshes ? true : false;
  111283. }
  111284. return false;
  111285. };
  111286. /**
  111287. * Returns true if the mesh should render, otherwise false.
  111288. * @param mesh The mesh to render
  111289. * @returns true if it should render otherwise false
  111290. */
  111291. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  111292. // Excluded Mesh
  111293. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  111294. return false;
  111295. }
  111296. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111297. return false;
  111298. }
  111299. return true;
  111300. };
  111301. /**
  111302. * Sets the required values for both the emissive texture and and the main color.
  111303. */
  111304. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  111305. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111306. if (highlightLayerMesh) {
  111307. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  111308. }
  111309. else {
  111310. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  111311. }
  111312. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111313. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  111314. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  111315. }
  111316. else {
  111317. this._emissiveTextureAndColor.texture = null;
  111318. }
  111319. };
  111320. /**
  111321. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  111322. * @param mesh The mesh to exclude from the highlight layer
  111323. */
  111324. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  111325. if (!this._excludedMeshes) {
  111326. return;
  111327. }
  111328. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111329. if (!meshExcluded) {
  111330. this._excludedMeshes[mesh.uniqueId] = {
  111331. mesh: mesh,
  111332. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  111333. mesh.getEngine().setStencilBuffer(false);
  111334. }),
  111335. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  111336. mesh.getEngine().setStencilBuffer(true);
  111337. }),
  111338. };
  111339. }
  111340. };
  111341. /**
  111342. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  111343. * @param mesh The mesh to highlight
  111344. */
  111345. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  111346. if (!this._excludedMeshes) {
  111347. return;
  111348. }
  111349. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111350. if (meshExcluded) {
  111351. if (meshExcluded.beforeRender) {
  111352. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  111353. }
  111354. if (meshExcluded.afterRender) {
  111355. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  111356. }
  111357. }
  111358. this._excludedMeshes[mesh.uniqueId] = null;
  111359. };
  111360. /**
  111361. * Determine if a given mesh will be highlighted by the current HighlightLayer
  111362. * @param mesh mesh to test
  111363. * @returns true if the mesh will be highlighted by the current HighlightLayer
  111364. */
  111365. HighlightLayer.prototype.hasMesh = function (mesh) {
  111366. if (!this._meshes) {
  111367. return false;
  111368. }
  111369. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111370. return false;
  111371. }
  111372. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  111373. };
  111374. /**
  111375. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  111376. * @param mesh The mesh to highlight
  111377. * @param color The color of the highlight
  111378. * @param glowEmissiveOnly Extract the glow from the emissive texture
  111379. */
  111380. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  111381. var _this = this;
  111382. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  111383. if (!this._meshes) {
  111384. return;
  111385. }
  111386. var meshHighlight = this._meshes[mesh.uniqueId];
  111387. if (meshHighlight) {
  111388. meshHighlight.color = color;
  111389. }
  111390. else {
  111391. this._meshes[mesh.uniqueId] = {
  111392. mesh: mesh,
  111393. color: color,
  111394. // Lambda required for capture due to Observable this context
  111395. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  111396. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  111397. _this._defaultStencilReference(mesh);
  111398. }
  111399. else {
  111400. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  111401. }
  111402. }),
  111403. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  111404. glowEmissiveOnly: glowEmissiveOnly
  111405. };
  111406. mesh.onDisposeObservable.add(function () {
  111407. _this._disposeMesh(mesh);
  111408. });
  111409. }
  111410. this._shouldRender = true;
  111411. };
  111412. /**
  111413. * Remove a mesh from the highlight layer in order to make it stop glowing.
  111414. * @param mesh The mesh to highlight
  111415. */
  111416. HighlightLayer.prototype.removeMesh = function (mesh) {
  111417. if (!this._meshes) {
  111418. return;
  111419. }
  111420. var meshHighlight = this._meshes[mesh.uniqueId];
  111421. if (meshHighlight) {
  111422. if (meshHighlight.observerHighlight) {
  111423. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  111424. }
  111425. if (meshHighlight.observerDefault) {
  111426. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  111427. }
  111428. delete this._meshes[mesh.uniqueId];
  111429. }
  111430. this._shouldRender = false;
  111431. for (var meshHighlightToCheck in this._meshes) {
  111432. if (this._meshes[meshHighlightToCheck]) {
  111433. this._shouldRender = true;
  111434. break;
  111435. }
  111436. }
  111437. };
  111438. /**
  111439. * Force the stencil to the normal expected value for none glowing parts
  111440. */
  111441. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  111442. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  111443. };
  111444. /**
  111445. * Free any resources and references associated to a mesh.
  111446. * Internal use
  111447. * @param mesh The mesh to free.
  111448. * @hidden
  111449. */
  111450. HighlightLayer.prototype._disposeMesh = function (mesh) {
  111451. this.removeMesh(mesh);
  111452. this.removeExcludedMesh(mesh);
  111453. };
  111454. /**
  111455. * Dispose the highlight layer and free resources.
  111456. */
  111457. HighlightLayer.prototype.dispose = function () {
  111458. if (this._meshes) {
  111459. // Clean mesh references
  111460. for (var id in this._meshes) {
  111461. var meshHighlight = this._meshes[id];
  111462. if (meshHighlight && meshHighlight.mesh) {
  111463. if (meshHighlight.observerHighlight) {
  111464. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  111465. }
  111466. if (meshHighlight.observerDefault) {
  111467. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  111468. }
  111469. }
  111470. }
  111471. this._meshes = null;
  111472. }
  111473. if (this._excludedMeshes) {
  111474. for (var id in this._excludedMeshes) {
  111475. var meshHighlight = this._excludedMeshes[id];
  111476. if (meshHighlight) {
  111477. if (meshHighlight.beforeRender) {
  111478. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  111479. }
  111480. if (meshHighlight.afterRender) {
  111481. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  111482. }
  111483. }
  111484. }
  111485. this._excludedMeshes = null;
  111486. }
  111487. _super.prototype.dispose.call(this);
  111488. };
  111489. /**
  111490. * Gets the class name of the effect layer
  111491. * @returns the string with the class name of the effect layer
  111492. */
  111493. HighlightLayer.prototype.getClassName = function () {
  111494. return "HighlightLayer";
  111495. };
  111496. /**
  111497. * Serializes this Highlight layer
  111498. * @returns a serialized Highlight layer object
  111499. */
  111500. HighlightLayer.prototype.serialize = function () {
  111501. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111502. serializationObject.customType = "BABYLON.HighlightLayer";
  111503. // Highlighted meshes
  111504. serializationObject.meshes = [];
  111505. if (this._meshes) {
  111506. for (var m in this._meshes) {
  111507. var mesh = this._meshes[m];
  111508. if (mesh) {
  111509. serializationObject.meshes.push({
  111510. glowEmissiveOnly: mesh.glowEmissiveOnly,
  111511. color: mesh.color.asArray(),
  111512. meshId: mesh.mesh.id
  111513. });
  111514. }
  111515. }
  111516. }
  111517. // Excluded meshes
  111518. serializationObject.excludedMeshes = [];
  111519. if (this._excludedMeshes) {
  111520. for (var e in this._excludedMeshes) {
  111521. var excludedMesh = this._excludedMeshes[e];
  111522. if (excludedMesh) {
  111523. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  111524. }
  111525. }
  111526. }
  111527. return serializationObject;
  111528. };
  111529. /**
  111530. * Creates a Highlight layer from parsed Highlight layer data
  111531. * @param parsedHightlightLayer defines the Highlight layer data
  111532. * @param scene defines the current scene
  111533. * @param rootUrl defines the root URL containing the Highlight layer information
  111534. * @returns a parsed Highlight layer
  111535. */
  111536. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  111537. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  111538. var index;
  111539. // Excluded meshes
  111540. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  111541. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  111542. if (mesh) {
  111543. hl.addExcludedMesh(mesh);
  111544. }
  111545. }
  111546. // Included meshes
  111547. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  111548. var highlightedMesh = parsedHightlightLayer.meshes[index];
  111549. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  111550. if (mesh) {
  111551. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  111552. }
  111553. }
  111554. return hl;
  111555. };
  111556. /**
  111557. * Effect Name of the highlight layer.
  111558. */
  111559. HighlightLayer.EffectName = "HighlightLayer";
  111560. /**
  111561. * The neutral color used during the preparation of the glow effect.
  111562. * This is black by default as the blend operation is a blend operation.
  111563. */
  111564. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  111565. /**
  111566. * Stencil value used for glowing meshes.
  111567. */
  111568. HighlightLayer.GlowingMeshStencilReference = 0x02;
  111569. /**
  111570. * Stencil value used for the other meshes in the scene.
  111571. */
  111572. HighlightLayer.NormalMeshStencilReference = 0x01;
  111573. __decorate([
  111574. BABYLON.serialize()
  111575. ], HighlightLayer.prototype, "innerGlow", void 0);
  111576. __decorate([
  111577. BABYLON.serialize()
  111578. ], HighlightLayer.prototype, "outerGlow", void 0);
  111579. __decorate([
  111580. BABYLON.serialize()
  111581. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  111582. __decorate([
  111583. BABYLON.serialize()
  111584. ], HighlightLayer.prototype, "blurVerticalSize", null);
  111585. __decorate([
  111586. BABYLON.serialize("options")
  111587. ], HighlightLayer.prototype, "_options", void 0);
  111588. return HighlightLayer;
  111589. }(BABYLON.EffectLayer));
  111590. BABYLON.HighlightLayer = HighlightLayer;
  111591. })(BABYLON || (BABYLON = {}));
  111592. //# sourceMappingURL=babylon.highlightLayer.js.map
  111593. var BABYLON;
  111594. (function (BABYLON) {
  111595. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  111596. for (var index = 0; index < this.effectLayers.length; index++) {
  111597. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  111598. return this.effectLayers[index];
  111599. }
  111600. }
  111601. return null;
  111602. };
  111603. /**
  111604. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  111605. *
  111606. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111607. * glowy meshes to your scene.
  111608. *
  111609. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  111610. */
  111611. var GlowLayer = /** @class */ (function (_super) {
  111612. __extends(GlowLayer, _super);
  111613. /**
  111614. * Instantiates a new glow Layer and references it to the scene.
  111615. * @param name The name of the layer
  111616. * @param scene The scene to use the layer in
  111617. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  111618. */
  111619. function GlowLayer(name, scene, options) {
  111620. var _this = _super.call(this, name, scene) || this;
  111621. _this._intensity = 1.0;
  111622. _this._includedOnlyMeshes = [];
  111623. _this._excludedMeshes = [];
  111624. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  111625. // Adapt options
  111626. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  111627. // Initialize the layer
  111628. _this._init({
  111629. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  111630. camera: _this._options.camera,
  111631. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111632. mainTextureRatio: _this._options.mainTextureRatio,
  111633. renderingGroupId: _this._options.renderingGroupId
  111634. });
  111635. return _this;
  111636. }
  111637. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  111638. /**
  111639. * Gets the kernel size of the blur.
  111640. */
  111641. get: function () {
  111642. return this._horizontalBlurPostprocess1.kernel;
  111643. },
  111644. /**
  111645. * Sets the kernel size of the blur.
  111646. */
  111647. set: function (value) {
  111648. this._horizontalBlurPostprocess1.kernel = value;
  111649. this._verticalBlurPostprocess1.kernel = value;
  111650. this._horizontalBlurPostprocess2.kernel = value;
  111651. this._verticalBlurPostprocess2.kernel = value;
  111652. },
  111653. enumerable: true,
  111654. configurable: true
  111655. });
  111656. Object.defineProperty(GlowLayer.prototype, "intensity", {
  111657. /**
  111658. * Gets the glow intensity.
  111659. */
  111660. get: function () {
  111661. return this._intensity;
  111662. },
  111663. /**
  111664. * Sets the glow intensity.
  111665. */
  111666. set: function (value) {
  111667. this._intensity = value;
  111668. },
  111669. enumerable: true,
  111670. configurable: true
  111671. });
  111672. /**
  111673. * Get the effect name of the layer.
  111674. * @return The effect name
  111675. */
  111676. GlowLayer.prototype.getEffectName = function () {
  111677. return GlowLayer.EffectName;
  111678. };
  111679. /**
  111680. * Create the merge effect. This is the shader use to blit the information back
  111681. * to the main canvas at the end of the scene rendering.
  111682. */
  111683. GlowLayer.prototype._createMergeEffect = function () {
  111684. // Effect
  111685. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  111686. };
  111687. /**
  111688. * Creates the render target textures and post processes used in the glow layer.
  111689. */
  111690. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  111691. var _this = this;
  111692. var blurTextureWidth = this._mainTextureDesiredSize.width;
  111693. var blurTextureHeight = this._mainTextureDesiredSize.height;
  111694. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111695. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111696. var textureType = 0;
  111697. if (this._engine.getCaps().textureHalfFloatRender) {
  111698. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111699. }
  111700. else {
  111701. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111702. }
  111703. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  111704. width: blurTextureWidth,
  111705. height: blurTextureHeight
  111706. }, this._scene, false, true, textureType);
  111707. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111708. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111709. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111710. this._blurTexture1.renderParticles = false;
  111711. this._blurTexture1.ignoreCameraViewport = true;
  111712. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  111713. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  111714. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  111715. width: blurTextureWidth2,
  111716. height: blurTextureHeight2
  111717. }, this._scene, false, true, textureType);
  111718. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111719. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111720. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111721. this._blurTexture2.renderParticles = false;
  111722. this._blurTexture2.ignoreCameraViewport = true;
  111723. this._textures = [this._blurTexture1, this._blurTexture2];
  111724. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  111725. width: blurTextureWidth,
  111726. height: blurTextureHeight
  111727. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111728. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  111729. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  111730. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  111731. effect.setTexture("textureSampler", _this._mainTexture);
  111732. });
  111733. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  111734. width: blurTextureWidth,
  111735. height: blurTextureHeight
  111736. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111737. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  111738. width: blurTextureWidth2,
  111739. height: blurTextureHeight2
  111740. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111741. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  111742. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  111743. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  111744. effect.setTexture("textureSampler", _this._blurTexture1);
  111745. });
  111746. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  111747. width: blurTextureWidth2,
  111748. height: blurTextureHeight2
  111749. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111750. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  111751. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  111752. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  111753. this._mainTexture.samples = this._options.mainTextureSamples;
  111754. this._mainTexture.onAfterUnbindObservable.add(function () {
  111755. var internalTexture = _this._blurTexture1.getInternalTexture();
  111756. if (internalTexture) {
  111757. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  111758. internalTexture = _this._blurTexture2.getInternalTexture();
  111759. if (internalTexture) {
  111760. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  111761. }
  111762. }
  111763. });
  111764. // Prevent autoClear.
  111765. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  111766. };
  111767. /**
  111768. * Checks for the readiness of the element composing the layer.
  111769. * @param subMesh the mesh to check for
  111770. * @param useInstances specify wether or not to use instances to render the mesh
  111771. * @param emissiveTexture the associated emissive texture used to generate the glow
  111772. * @return true if ready otherwise, false
  111773. */
  111774. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  111775. var material = subMesh.getMaterial();
  111776. var mesh = subMesh.getRenderingMesh();
  111777. if (!material || !mesh) {
  111778. return false;
  111779. }
  111780. var emissiveTexture = material.emissiveTexture;
  111781. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  111782. };
  111783. /**
  111784. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  111785. */
  111786. GlowLayer.prototype.needStencil = function () {
  111787. return false;
  111788. };
  111789. /**
  111790. * Implementation specific of rendering the generating effect on the main canvas.
  111791. * @param effect The effect used to render through
  111792. */
  111793. GlowLayer.prototype._internalRender = function (effect) {
  111794. // Texture
  111795. effect.setTexture("textureSampler", this._blurTexture1);
  111796. effect.setTexture("textureSampler2", this._blurTexture2);
  111797. effect.setFloat("offset", this._intensity);
  111798. // Cache
  111799. var engine = this._engine;
  111800. var previousStencilBuffer = engine.getStencilBuffer();
  111801. // Draw order
  111802. engine.setStencilBuffer(false);
  111803. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111804. // Draw order
  111805. engine.setStencilBuffer(previousStencilBuffer);
  111806. };
  111807. /**
  111808. * Sets the required values for both the emissive texture and and the main color.
  111809. */
  111810. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  111811. var textureLevel = 1.0;
  111812. if (this.customEmissiveTextureSelector) {
  111813. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  111814. }
  111815. else {
  111816. if (material) {
  111817. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  111818. if (this._emissiveTextureAndColor.texture) {
  111819. textureLevel = this._emissiveTextureAndColor.texture.level;
  111820. }
  111821. }
  111822. else {
  111823. this._emissiveTextureAndColor.texture = null;
  111824. }
  111825. }
  111826. if (this.customEmissiveColorSelector) {
  111827. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  111828. }
  111829. else {
  111830. if (material.emissiveColor) {
  111831. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  111832. }
  111833. else {
  111834. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  111835. }
  111836. }
  111837. };
  111838. /**
  111839. * Returns true if the mesh should render, otherwise false.
  111840. * @param mesh The mesh to render
  111841. * @returns true if it should render otherwise false
  111842. */
  111843. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  111844. return this.hasMesh(mesh);
  111845. };
  111846. /**
  111847. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  111848. * @param mesh The mesh to exclude from the glow layer
  111849. */
  111850. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  111851. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  111852. this._excludedMeshes.push(mesh.uniqueId);
  111853. }
  111854. };
  111855. /**
  111856. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  111857. * @param mesh The mesh to remove
  111858. */
  111859. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  111860. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  111861. if (index !== -1) {
  111862. this._excludedMeshes.splice(index, 1);
  111863. }
  111864. };
  111865. /**
  111866. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  111867. * @param mesh The mesh to include in the glow layer
  111868. */
  111869. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  111870. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  111871. this._includedOnlyMeshes.push(mesh.uniqueId);
  111872. }
  111873. };
  111874. /**
  111875. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  111876. * @param mesh The mesh to remove
  111877. */
  111878. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  111879. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  111880. if (index !== -1) {
  111881. this._includedOnlyMeshes.splice(index, 1);
  111882. }
  111883. };
  111884. /**
  111885. * Determine if a given mesh will be used in the glow layer
  111886. * @param mesh The mesh to test
  111887. * @returns true if the mesh will be highlighted by the current glow layer
  111888. */
  111889. GlowLayer.prototype.hasMesh = function (mesh) {
  111890. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111891. return false;
  111892. }
  111893. // Included Mesh
  111894. if (this._includedOnlyMeshes.length) {
  111895. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  111896. }
  111897. // Excluded Mesh
  111898. if (this._excludedMeshes.length) {
  111899. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  111900. }
  111901. return true;
  111902. };
  111903. /**
  111904. * Free any resources and references associated to a mesh.
  111905. * Internal use
  111906. * @param mesh The mesh to free.
  111907. * @hidden
  111908. */
  111909. GlowLayer.prototype._disposeMesh = function (mesh) {
  111910. this.removeIncludedOnlyMesh(mesh);
  111911. this.removeExcludedMesh(mesh);
  111912. };
  111913. /**
  111914. * Gets the class name of the effect layer
  111915. * @returns the string with the class name of the effect layer
  111916. */
  111917. GlowLayer.prototype.getClassName = function () {
  111918. return "GlowLayer";
  111919. };
  111920. /**
  111921. * Serializes this glow layer
  111922. * @returns a serialized glow layer object
  111923. */
  111924. GlowLayer.prototype.serialize = function () {
  111925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111926. serializationObject.customType = "BABYLON.GlowLayer";
  111927. var index;
  111928. // Included meshes
  111929. serializationObject.includedMeshes = [];
  111930. if (this._includedOnlyMeshes.length) {
  111931. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  111932. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  111933. if (mesh) {
  111934. serializationObject.includedMeshes.push(mesh.id);
  111935. }
  111936. }
  111937. }
  111938. // Excluded meshes
  111939. serializationObject.excludedMeshes = [];
  111940. if (this._excludedMeshes.length) {
  111941. for (index = 0; index < this._excludedMeshes.length; index++) {
  111942. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  111943. if (mesh) {
  111944. serializationObject.excludedMeshes.push(mesh.id);
  111945. }
  111946. }
  111947. }
  111948. return serializationObject;
  111949. };
  111950. /**
  111951. * Creates a Glow Layer from parsed glow layer data
  111952. * @param parsedGlowLayer defines glow layer data
  111953. * @param scene defines the current scene
  111954. * @param rootUrl defines the root URL containing the glow layer information
  111955. * @returns a parsed Glow Layer
  111956. */
  111957. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  111958. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  111959. var index;
  111960. // Excluded meshes
  111961. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  111962. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  111963. if (mesh) {
  111964. gl.addExcludedMesh(mesh);
  111965. }
  111966. }
  111967. // Included meshes
  111968. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  111969. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  111970. if (mesh) {
  111971. gl.addIncludedOnlyMesh(mesh);
  111972. }
  111973. }
  111974. return gl;
  111975. };
  111976. /**
  111977. * Effect Name of the layer.
  111978. */
  111979. GlowLayer.EffectName = "GlowLayer";
  111980. /**
  111981. * The default blur kernel size used for the glow.
  111982. */
  111983. GlowLayer.DefaultBlurKernelSize = 32;
  111984. /**
  111985. * The default texture size ratio used for the glow.
  111986. */
  111987. GlowLayer.DefaultTextureRatio = 0.5;
  111988. __decorate([
  111989. BABYLON.serialize()
  111990. ], GlowLayer.prototype, "blurKernelSize", null);
  111991. __decorate([
  111992. BABYLON.serialize()
  111993. ], GlowLayer.prototype, "intensity", null);
  111994. __decorate([
  111995. BABYLON.serialize("options")
  111996. ], GlowLayer.prototype, "_options", void 0);
  111997. return GlowLayer;
  111998. }(BABYLON.EffectLayer));
  111999. BABYLON.GlowLayer = GlowLayer;
  112000. })(BABYLON || (BABYLON = {}));
  112001. //# sourceMappingURL=babylon.glowLayer.js.map
  112002. var BABYLON;
  112003. (function (BABYLON) {
  112004. /**
  112005. * Defines the list of states available for a task inside a AssetsManager
  112006. */
  112007. var AssetTaskState;
  112008. (function (AssetTaskState) {
  112009. /**
  112010. * Initialization
  112011. */
  112012. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  112013. /**
  112014. * Running
  112015. */
  112016. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  112017. /**
  112018. * Done
  112019. */
  112020. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  112021. /**
  112022. * Error
  112023. */
  112024. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  112025. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  112026. /**
  112027. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  112028. */
  112029. var AbstractAssetTask = /** @class */ (function () {
  112030. /**
  112031. * Creates a new AssetsManager
  112032. * @param name defines the name of the task
  112033. */
  112034. function AbstractAssetTask(
  112035. /**
  112036. * Task name
  112037. */ name) {
  112038. this.name = name;
  112039. this._isCompleted = false;
  112040. this._taskState = AssetTaskState.INIT;
  112041. }
  112042. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  112043. /**
  112044. * Get if the task is completed
  112045. */
  112046. get: function () {
  112047. return this._isCompleted;
  112048. },
  112049. enumerable: true,
  112050. configurable: true
  112051. });
  112052. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  112053. /**
  112054. * Gets the current state of the task
  112055. */
  112056. get: function () {
  112057. return this._taskState;
  112058. },
  112059. enumerable: true,
  112060. configurable: true
  112061. });
  112062. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  112063. /**
  112064. * Gets the current error object (if task is in error)
  112065. */
  112066. get: function () {
  112067. return this._errorObject;
  112068. },
  112069. enumerable: true,
  112070. configurable: true
  112071. });
  112072. /**
  112073. * Internal only
  112074. * @hidden
  112075. */
  112076. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  112077. if (this._errorObject) {
  112078. return;
  112079. }
  112080. this._errorObject = {
  112081. message: message,
  112082. exception: exception
  112083. };
  112084. };
  112085. /**
  112086. * Execute the current task
  112087. * @param scene defines the scene where you want your assets to be loaded
  112088. * @param onSuccess is a callback called when the task is successfully executed
  112089. * @param onError is a callback called if an error occurs
  112090. */
  112091. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112092. var _this = this;
  112093. this._taskState = AssetTaskState.RUNNING;
  112094. this.runTask(scene, function () {
  112095. _this.onDoneCallback(onSuccess, onError);
  112096. }, function (msg, exception) {
  112097. _this.onErrorCallback(onError, msg, exception);
  112098. });
  112099. };
  112100. /**
  112101. * Execute the current task
  112102. * @param scene defines the scene where you want your assets to be loaded
  112103. * @param onSuccess is a callback called when the task is successfully executed
  112104. * @param onError is a callback called if an error occurs
  112105. */
  112106. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112107. throw new Error("runTask is not implemented");
  112108. };
  112109. /**
  112110. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  112111. * This can be used with failed tasks that have the reason for failure fixed.
  112112. */
  112113. AbstractAssetTask.prototype.reset = function () {
  112114. this._taskState = AssetTaskState.INIT;
  112115. };
  112116. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  112117. this._taskState = AssetTaskState.ERROR;
  112118. this._errorObject = {
  112119. message: message,
  112120. exception: exception
  112121. };
  112122. if (this.onError) {
  112123. this.onError(this, message, exception);
  112124. }
  112125. onError();
  112126. };
  112127. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  112128. try {
  112129. this._taskState = AssetTaskState.DONE;
  112130. this._isCompleted = true;
  112131. if (this.onSuccess) {
  112132. this.onSuccess(this);
  112133. }
  112134. onSuccess();
  112135. }
  112136. catch (e) {
  112137. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  112138. }
  112139. };
  112140. return AbstractAssetTask;
  112141. }());
  112142. BABYLON.AbstractAssetTask = AbstractAssetTask;
  112143. /**
  112144. * Class used to share progress information about assets loading
  112145. */
  112146. var AssetsProgressEvent = /** @class */ (function () {
  112147. /**
  112148. * Creates a AssetsProgressEvent
  112149. * @param remainingCount defines the number of remaining tasks to process
  112150. * @param totalCount defines the total number of tasks
  112151. * @param task defines the task that was just processed
  112152. */
  112153. function AssetsProgressEvent(remainingCount, totalCount, task) {
  112154. this.remainingCount = remainingCount;
  112155. this.totalCount = totalCount;
  112156. this.task = task;
  112157. }
  112158. return AssetsProgressEvent;
  112159. }());
  112160. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  112161. /**
  112162. * Define a task used by AssetsManager to load meshes
  112163. */
  112164. var MeshAssetTask = /** @class */ (function (_super) {
  112165. __extends(MeshAssetTask, _super);
  112166. /**
  112167. * Creates a new MeshAssetTask
  112168. * @param name defines the name of the task
  112169. * @param meshesNames defines the list of mesh's names you want to load
  112170. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  112171. * @param sceneFilename defines the filename of the scene to load from
  112172. */
  112173. function MeshAssetTask(
  112174. /**
  112175. * Defines the name of the task
  112176. */
  112177. name,
  112178. /**
  112179. * Defines the list of mesh's names you want to load
  112180. */
  112181. meshesNames,
  112182. /**
  112183. * Defines the root url to use as a base to load your meshes and associated resources
  112184. */
  112185. rootUrl,
  112186. /**
  112187. * Defines the filename of the scene to load from
  112188. */
  112189. sceneFilename) {
  112190. var _this = _super.call(this, name) || this;
  112191. _this.name = name;
  112192. _this.meshesNames = meshesNames;
  112193. _this.rootUrl = rootUrl;
  112194. _this.sceneFilename = sceneFilename;
  112195. return _this;
  112196. }
  112197. /**
  112198. * Execute the current task
  112199. * @param scene defines the scene where you want your assets to be loaded
  112200. * @param onSuccess is a callback called when the task is successfully executed
  112201. * @param onError is a callback called if an error occurs
  112202. */
  112203. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112204. var _this = this;
  112205. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  112206. _this.loadedMeshes = meshes;
  112207. _this.loadedParticleSystems = particleSystems;
  112208. _this.loadedSkeletons = skeletons;
  112209. onSuccess();
  112210. }, null, function (scene, message, exception) {
  112211. onError(message, exception);
  112212. });
  112213. };
  112214. return MeshAssetTask;
  112215. }(AbstractAssetTask));
  112216. BABYLON.MeshAssetTask = MeshAssetTask;
  112217. /**
  112218. * Define a task used by AssetsManager to load text content
  112219. */
  112220. var TextFileAssetTask = /** @class */ (function (_super) {
  112221. __extends(TextFileAssetTask, _super);
  112222. /**
  112223. * Creates a new TextFileAssetTask object
  112224. * @param name defines the name of the task
  112225. * @param url defines the location of the file to load
  112226. */
  112227. function TextFileAssetTask(
  112228. /**
  112229. * Defines the name of the task
  112230. */
  112231. name,
  112232. /**
  112233. * Defines the location of the file to load
  112234. */
  112235. url) {
  112236. var _this = _super.call(this, name) || this;
  112237. _this.name = name;
  112238. _this.url = url;
  112239. return _this;
  112240. }
  112241. /**
  112242. * Execute the current task
  112243. * @param scene defines the scene where you want your assets to be loaded
  112244. * @param onSuccess is a callback called when the task is successfully executed
  112245. * @param onError is a callback called if an error occurs
  112246. */
  112247. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112248. var _this = this;
  112249. scene._loadFile(this.url, function (data) {
  112250. _this.text = data;
  112251. onSuccess();
  112252. }, undefined, false, false, function (request, exception) {
  112253. if (request) {
  112254. onError(request.status + " " + request.statusText, exception);
  112255. }
  112256. });
  112257. };
  112258. return TextFileAssetTask;
  112259. }(AbstractAssetTask));
  112260. BABYLON.TextFileAssetTask = TextFileAssetTask;
  112261. /**
  112262. * Define a task used by AssetsManager to load binary data
  112263. */
  112264. var BinaryFileAssetTask = /** @class */ (function (_super) {
  112265. __extends(BinaryFileAssetTask, _super);
  112266. /**
  112267. * Creates a new BinaryFileAssetTask object
  112268. * @param name defines the name of the new task
  112269. * @param url defines the location of the file to load
  112270. */
  112271. function BinaryFileAssetTask(
  112272. /**
  112273. * Defines the name of the task
  112274. */
  112275. name,
  112276. /**
  112277. * Defines the location of the file to load
  112278. */
  112279. url) {
  112280. var _this = _super.call(this, name) || this;
  112281. _this.name = name;
  112282. _this.url = url;
  112283. return _this;
  112284. }
  112285. /**
  112286. * Execute the current task
  112287. * @param scene defines the scene where you want your assets to be loaded
  112288. * @param onSuccess is a callback called when the task is successfully executed
  112289. * @param onError is a callback called if an error occurs
  112290. */
  112291. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112292. var _this = this;
  112293. scene._loadFile(this.url, function (data) {
  112294. _this.data = data;
  112295. onSuccess();
  112296. }, undefined, true, true, function (request, exception) {
  112297. if (request) {
  112298. onError(request.status + " " + request.statusText, exception);
  112299. }
  112300. });
  112301. };
  112302. return BinaryFileAssetTask;
  112303. }(AbstractAssetTask));
  112304. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  112305. /**
  112306. * Define a task used by AssetsManager to load images
  112307. */
  112308. var ImageAssetTask = /** @class */ (function (_super) {
  112309. __extends(ImageAssetTask, _super);
  112310. /**
  112311. * Creates a new ImageAssetTask
  112312. * @param name defines the name of the task
  112313. * @param url defines the location of the image to load
  112314. */
  112315. function ImageAssetTask(
  112316. /**
  112317. * Defines the name of the task
  112318. */
  112319. name,
  112320. /**
  112321. * Defines the location of the image to load
  112322. */
  112323. url) {
  112324. var _this = _super.call(this, name) || this;
  112325. _this.name = name;
  112326. _this.url = url;
  112327. return _this;
  112328. }
  112329. /**
  112330. * Execute the current task
  112331. * @param scene defines the scene where you want your assets to be loaded
  112332. * @param onSuccess is a callback called when the task is successfully executed
  112333. * @param onError is a callback called if an error occurs
  112334. */
  112335. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112336. var _this = this;
  112337. var img = new Image();
  112338. BABYLON.Tools.SetCorsBehavior(this.url, img);
  112339. img.onload = function () {
  112340. _this.image = img;
  112341. onSuccess();
  112342. };
  112343. img.onerror = function (err) {
  112344. onError("Error loading image", err);
  112345. };
  112346. img.src = this.url;
  112347. };
  112348. return ImageAssetTask;
  112349. }(AbstractAssetTask));
  112350. BABYLON.ImageAssetTask = ImageAssetTask;
  112351. /**
  112352. * Define a task used by AssetsManager to load 2D textures
  112353. */
  112354. var TextureAssetTask = /** @class */ (function (_super) {
  112355. __extends(TextureAssetTask, _super);
  112356. /**
  112357. * Creates a new TextureAssetTask object
  112358. * @param name defines the name of the task
  112359. * @param url defines the location of the file to load
  112360. * @param noMipmap defines if mipmap should not be generated (default is false)
  112361. * @param invertY defines if texture must be inverted on Y axis (default is false)
  112362. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112363. */
  112364. function TextureAssetTask(
  112365. /**
  112366. * Defines the name of the task
  112367. */
  112368. name,
  112369. /**
  112370. * Defines the location of the file to load
  112371. */
  112372. url,
  112373. /**
  112374. * Defines if mipmap should not be generated (default is false)
  112375. */
  112376. noMipmap,
  112377. /**
  112378. * Defines if texture must be inverted on Y axis (default is false)
  112379. */
  112380. invertY,
  112381. /**
  112382. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112383. */
  112384. samplingMode) {
  112385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  112386. var _this = _super.call(this, name) || this;
  112387. _this.name = name;
  112388. _this.url = url;
  112389. _this.noMipmap = noMipmap;
  112390. _this.invertY = invertY;
  112391. _this.samplingMode = samplingMode;
  112392. return _this;
  112393. }
  112394. /**
  112395. * Execute the current task
  112396. * @param scene defines the scene where you want your assets to be loaded
  112397. * @param onSuccess is a callback called when the task is successfully executed
  112398. * @param onError is a callback called if an error occurs
  112399. */
  112400. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112401. var onload = function () {
  112402. onSuccess();
  112403. };
  112404. var onerror = function (message, exception) {
  112405. onError(message, exception);
  112406. };
  112407. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  112408. };
  112409. return TextureAssetTask;
  112410. }(AbstractAssetTask));
  112411. BABYLON.TextureAssetTask = TextureAssetTask;
  112412. /**
  112413. * Define a task used by AssetsManager to load cube textures
  112414. */
  112415. var CubeTextureAssetTask = /** @class */ (function (_super) {
  112416. __extends(CubeTextureAssetTask, _super);
  112417. /**
  112418. * Creates a new CubeTextureAssetTask
  112419. * @param name defines the name of the task
  112420. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  112421. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  112422. * @param noMipmap defines if mipmaps should not be generated (default is false)
  112423. * @param files defines the explicit list of files (undefined by default)
  112424. */
  112425. function CubeTextureAssetTask(
  112426. /**
  112427. * Defines the name of the task
  112428. */
  112429. name,
  112430. /**
  112431. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  112432. */
  112433. url,
  112434. /**
  112435. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  112436. */
  112437. extensions,
  112438. /**
  112439. * Defines if mipmaps should not be generated (default is false)
  112440. */
  112441. noMipmap,
  112442. /**
  112443. * Defines the explicit list of files (undefined by default)
  112444. */
  112445. files) {
  112446. var _this = _super.call(this, name) || this;
  112447. _this.name = name;
  112448. _this.url = url;
  112449. _this.extensions = extensions;
  112450. _this.noMipmap = noMipmap;
  112451. _this.files = files;
  112452. return _this;
  112453. }
  112454. /**
  112455. * Execute the current task
  112456. * @param scene defines the scene where you want your assets to be loaded
  112457. * @param onSuccess is a callback called when the task is successfully executed
  112458. * @param onError is a callback called if an error occurs
  112459. */
  112460. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112461. var onload = function () {
  112462. onSuccess();
  112463. };
  112464. var onerror = function (message, exception) {
  112465. onError(message, exception);
  112466. };
  112467. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  112468. };
  112469. return CubeTextureAssetTask;
  112470. }(AbstractAssetTask));
  112471. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  112472. /**
  112473. * Define a task used by AssetsManager to load HDR cube textures
  112474. */
  112475. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  112476. __extends(HDRCubeTextureAssetTask, _super);
  112477. /**
  112478. * Creates a new HDRCubeTextureAssetTask object
  112479. * @param name defines the name of the task
  112480. * @param url defines the location of the file to load
  112481. * @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.
  112482. * @param noMipmap defines if mipmaps should not be generated (default is false)
  112483. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  112484. * @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)
  112485. * @param reserved Internal use only
  112486. */
  112487. function HDRCubeTextureAssetTask(
  112488. /**
  112489. * Defines the name of the task
  112490. */
  112491. name,
  112492. /**
  112493. * Defines the location of the file to load
  112494. */
  112495. url,
  112496. /**
  112497. * Defines the desired size (the more it increases the longer the generation will be)
  112498. */
  112499. size,
  112500. /**
  112501. * Defines if mipmaps should not be generated (default is false)
  112502. */
  112503. noMipmap,
  112504. /**
  112505. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  112506. */
  112507. generateHarmonics,
  112508. /**
  112509. * 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)
  112510. */
  112511. gammaSpace,
  112512. /**
  112513. * Internal Use Only
  112514. */
  112515. reserved) {
  112516. if (noMipmap === void 0) { noMipmap = false; }
  112517. if (generateHarmonics === void 0) { generateHarmonics = true; }
  112518. if (gammaSpace === void 0) { gammaSpace = false; }
  112519. if (reserved === void 0) { reserved = false; }
  112520. var _this = _super.call(this, name) || this;
  112521. _this.name = name;
  112522. _this.url = url;
  112523. _this.size = size;
  112524. _this.noMipmap = noMipmap;
  112525. _this.generateHarmonics = generateHarmonics;
  112526. _this.gammaSpace = gammaSpace;
  112527. _this.reserved = reserved;
  112528. return _this;
  112529. }
  112530. /**
  112531. * Execute the current task
  112532. * @param scene defines the scene where you want your assets to be loaded
  112533. * @param onSuccess is a callback called when the task is successfully executed
  112534. * @param onError is a callback called if an error occurs
  112535. */
  112536. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112537. var onload = function () {
  112538. onSuccess();
  112539. };
  112540. var onerror = function (message, exception) {
  112541. onError(message, exception);
  112542. };
  112543. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  112544. };
  112545. return HDRCubeTextureAssetTask;
  112546. }(AbstractAssetTask));
  112547. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  112548. /**
  112549. * This class can be used to easily import assets into a scene
  112550. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  112551. */
  112552. var AssetsManager = /** @class */ (function () {
  112553. /**
  112554. * Creates a new AssetsManager
  112555. * @param scene defines the scene to work on
  112556. */
  112557. function AssetsManager(scene) {
  112558. this._isLoading = false;
  112559. this._tasks = new Array();
  112560. this._waitingTasksCount = 0;
  112561. this._totalTasksCount = 0;
  112562. /**
  112563. * Observable called when all tasks are processed
  112564. */
  112565. this.onTaskSuccessObservable = new BABYLON.Observable();
  112566. /**
  112567. * Observable called when a task had an error
  112568. */
  112569. this.onTaskErrorObservable = new BABYLON.Observable();
  112570. /**
  112571. * Observable called when a task is successful
  112572. */
  112573. this.onTasksDoneObservable = new BABYLON.Observable();
  112574. /**
  112575. * Observable called when a task is done (whatever the result is)
  112576. */
  112577. this.onProgressObservable = new BABYLON.Observable();
  112578. /**
  112579. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  112580. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  112581. */
  112582. this.useDefaultLoadingScreen = true;
  112583. this._scene = scene;
  112584. }
  112585. /**
  112586. * Add a MeshAssetTask to the list of active tasks
  112587. * @param taskName defines the name of the new task
  112588. * @param meshesNames defines the name of meshes to load
  112589. * @param rootUrl defines the root url to use to locate files
  112590. * @param sceneFilename defines the filename of the scene file
  112591. * @returns a new MeshAssetTask object
  112592. */
  112593. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  112594. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  112595. this._tasks.push(task);
  112596. return task;
  112597. };
  112598. /**
  112599. * Add a TextFileAssetTask to the list of active tasks
  112600. * @param taskName defines the name of the new task
  112601. * @param url defines the url of the file to load
  112602. * @returns a new TextFileAssetTask object
  112603. */
  112604. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  112605. var task = new TextFileAssetTask(taskName, url);
  112606. this._tasks.push(task);
  112607. return task;
  112608. };
  112609. /**
  112610. * Add a BinaryFileAssetTask to the list of active tasks
  112611. * @param taskName defines the name of the new task
  112612. * @param url defines the url of the file to load
  112613. * @returns a new BinaryFileAssetTask object
  112614. */
  112615. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  112616. var task = new BinaryFileAssetTask(taskName, url);
  112617. this._tasks.push(task);
  112618. return task;
  112619. };
  112620. /**
  112621. * Add a ImageAssetTask to the list of active tasks
  112622. * @param taskName defines the name of the new task
  112623. * @param url defines the url of the file to load
  112624. * @returns a new ImageAssetTask object
  112625. */
  112626. AssetsManager.prototype.addImageTask = function (taskName, url) {
  112627. var task = new ImageAssetTask(taskName, url);
  112628. this._tasks.push(task);
  112629. return task;
  112630. };
  112631. /**
  112632. * Add a TextureAssetTask to the list of active tasks
  112633. * @param taskName defines the name of the new task
  112634. * @param url defines the url of the file to load
  112635. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112636. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  112637. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  112638. * @returns a new TextureAssetTask object
  112639. */
  112640. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  112641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  112642. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  112643. this._tasks.push(task);
  112644. return task;
  112645. };
  112646. /**
  112647. * Add a CubeTextureAssetTask to the list of active tasks
  112648. * @param taskName defines the name of the new task
  112649. * @param url defines the url of the file to load
  112650. * @param extensions defines the extension to use to load the cube map (can be null)
  112651. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112652. * @param files defines the list of files to load (can be null)
  112653. * @returns a new CubeTextureAssetTask object
  112654. */
  112655. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  112656. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  112657. this._tasks.push(task);
  112658. return task;
  112659. };
  112660. /**
  112661. *
  112662. * Add a HDRCubeTextureAssetTask to the list of active tasks
  112663. * @param taskName defines the name of the new task
  112664. * @param url defines the url of the file to load
  112665. * @param size defines the size you want for the cubemap (can be null)
  112666. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112667. * @param generateHarmonics defines if you want to automatically generate (true by default)
  112668. * @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)
  112669. * @param reserved Internal use only
  112670. * @returns a new HDRCubeTextureAssetTask object
  112671. */
  112672. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  112673. if (noMipmap === void 0) { noMipmap = false; }
  112674. if (generateHarmonics === void 0) { generateHarmonics = true; }
  112675. if (gammaSpace === void 0) { gammaSpace = false; }
  112676. if (reserved === void 0) { reserved = false; }
  112677. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  112678. this._tasks.push(task);
  112679. return task;
  112680. };
  112681. /**
  112682. * Remove a task from the assets manager.
  112683. * @param task the task to remove
  112684. */
  112685. AssetsManager.prototype.removeTask = function (task) {
  112686. var index = this._tasks.indexOf(task);
  112687. if (index > -1) {
  112688. this._tasks.splice(index, 1);
  112689. }
  112690. };
  112691. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  112692. this._waitingTasksCount--;
  112693. try {
  112694. if (this.onProgress) {
  112695. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  112696. }
  112697. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  112698. }
  112699. catch (e) {
  112700. BABYLON.Tools.Error("Error running progress callbacks.");
  112701. console.log(e);
  112702. }
  112703. if (this._waitingTasksCount === 0) {
  112704. try {
  112705. if (this.onFinish) {
  112706. this.onFinish(this._tasks);
  112707. }
  112708. // Let's remove successfull tasks
  112709. var currentTasks = this._tasks.slice();
  112710. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  112711. var task = currentTasks_1[_i];
  112712. if (task.taskState === AssetTaskState.DONE) {
  112713. var index = this._tasks.indexOf(task);
  112714. if (index > -1) {
  112715. this._tasks.splice(index, 1);
  112716. }
  112717. }
  112718. }
  112719. this.onTasksDoneObservable.notifyObservers(this._tasks);
  112720. }
  112721. catch (e) {
  112722. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  112723. console.log(e);
  112724. }
  112725. this._isLoading = false;
  112726. this._scene.getEngine().hideLoadingUI();
  112727. }
  112728. };
  112729. AssetsManager.prototype._runTask = function (task) {
  112730. var _this = this;
  112731. var done = function () {
  112732. try {
  112733. if (_this.onTaskSuccess) {
  112734. _this.onTaskSuccess(task);
  112735. }
  112736. _this.onTaskSuccessObservable.notifyObservers(task);
  112737. _this._decreaseWaitingTasksCount(task);
  112738. }
  112739. catch (e) {
  112740. error("Error executing task success callbacks", e);
  112741. }
  112742. };
  112743. var error = function (message, exception) {
  112744. task._setErrorObject(message, exception);
  112745. if (_this.onTaskError) {
  112746. _this.onTaskError(task);
  112747. }
  112748. _this.onTaskErrorObservable.notifyObservers(task);
  112749. _this._decreaseWaitingTasksCount(task);
  112750. };
  112751. task.run(this._scene, done, error);
  112752. };
  112753. /**
  112754. * Reset the AssetsManager and remove all tasks
  112755. * @return the current instance of the AssetsManager
  112756. */
  112757. AssetsManager.prototype.reset = function () {
  112758. this._isLoading = false;
  112759. this._tasks = new Array();
  112760. return this;
  112761. };
  112762. /**
  112763. * Start the loading process
  112764. * @return the current instance of the AssetsManager
  112765. */
  112766. AssetsManager.prototype.load = function () {
  112767. if (this._isLoading) {
  112768. return this;
  112769. }
  112770. this._isLoading = true;
  112771. this._waitingTasksCount = this._tasks.length;
  112772. this._totalTasksCount = this._tasks.length;
  112773. if (this._waitingTasksCount === 0) {
  112774. this._isLoading = false;
  112775. if (this.onFinish) {
  112776. this.onFinish(this._tasks);
  112777. }
  112778. this.onTasksDoneObservable.notifyObservers(this._tasks);
  112779. return this;
  112780. }
  112781. if (this.useDefaultLoadingScreen) {
  112782. this._scene.getEngine().displayLoadingUI();
  112783. }
  112784. for (var index = 0; index < this._tasks.length; index++) {
  112785. var task = this._tasks[index];
  112786. if (task.taskState === AssetTaskState.INIT) {
  112787. this._runTask(task);
  112788. }
  112789. }
  112790. return this;
  112791. };
  112792. return AssetsManager;
  112793. }());
  112794. BABYLON.AssetsManager = AssetsManager;
  112795. })(BABYLON || (BABYLON = {}));
  112796. //# sourceMappingURL=babylon.assetsManager.js.map
  112797. var BABYLON;
  112798. (function (BABYLON) {
  112799. var serializedGeometries = [];
  112800. var serializeGeometry = function (geometry, serializationGeometries) {
  112801. if (serializedGeometries[geometry.id]) {
  112802. return;
  112803. }
  112804. if (geometry.doNotSerialize) {
  112805. return;
  112806. }
  112807. if (geometry instanceof BABYLON.BoxGeometry) {
  112808. serializationGeometries.boxes.push(geometry.serialize());
  112809. }
  112810. else if (geometry instanceof BABYLON.SphereGeometry) {
  112811. serializationGeometries.spheres.push(geometry.serialize());
  112812. }
  112813. else if (geometry instanceof BABYLON.CylinderGeometry) {
  112814. serializationGeometries.cylinders.push(geometry.serialize());
  112815. }
  112816. else if (geometry instanceof BABYLON.TorusGeometry) {
  112817. serializationGeometries.toruses.push(geometry.serialize());
  112818. }
  112819. else if (geometry instanceof BABYLON.GroundGeometry) {
  112820. serializationGeometries.grounds.push(geometry.serialize());
  112821. }
  112822. else if (geometry instanceof BABYLON.Plane) {
  112823. serializationGeometries.planes.push(geometry.serialize());
  112824. }
  112825. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  112826. serializationGeometries.torusKnots.push(geometry.serialize());
  112827. }
  112828. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  112829. throw new Error("Unknown primitive type");
  112830. }
  112831. else {
  112832. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  112833. }
  112834. serializedGeometries[geometry.id] = true;
  112835. };
  112836. var serializeMesh = function (mesh, serializationScene) {
  112837. var serializationObject = {};
  112838. // Geometry
  112839. var geometry = mesh._geometry;
  112840. if (geometry) {
  112841. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  112842. // 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
  112843. serializeGeometry(geometry, serializationScene.geometries);
  112844. }
  112845. }
  112846. // Custom
  112847. if (mesh.serialize) {
  112848. mesh.serialize(serializationObject);
  112849. }
  112850. return serializationObject;
  112851. };
  112852. var finalizeSingleMesh = function (mesh, serializationObject) {
  112853. //only works if the mesh is already loaded
  112854. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  112855. //serialize material
  112856. if (mesh.material) {
  112857. if (mesh.material instanceof BABYLON.MultiMaterial) {
  112858. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  112859. serializationObject.materials = serializationObject.materials || [];
  112860. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  112861. serializationObject.multiMaterials.push(mesh.material.serialize());
  112862. var _loop_1 = function (submaterial) {
  112863. if (submaterial) {
  112864. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  112865. serializationObject.materials.push(submaterial.serialize());
  112866. }
  112867. }
  112868. };
  112869. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  112870. var submaterial = _a[_i];
  112871. _loop_1(submaterial);
  112872. }
  112873. }
  112874. }
  112875. else {
  112876. serializationObject.materials = serializationObject.materials || [];
  112877. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  112878. serializationObject.materials.push(mesh.material.serialize());
  112879. }
  112880. }
  112881. }
  112882. //serialize geometry
  112883. var geometry = mesh._geometry;
  112884. if (geometry) {
  112885. if (!serializationObject.geometries) {
  112886. serializationObject.geometries = {};
  112887. serializationObject.geometries.boxes = [];
  112888. serializationObject.geometries.spheres = [];
  112889. serializationObject.geometries.cylinders = [];
  112890. serializationObject.geometries.toruses = [];
  112891. serializationObject.geometries.grounds = [];
  112892. serializationObject.geometries.planes = [];
  112893. serializationObject.geometries.torusKnots = [];
  112894. serializationObject.geometries.vertexData = [];
  112895. }
  112896. serializeGeometry(geometry, serializationObject.geometries);
  112897. }
  112898. // Skeletons
  112899. if (mesh.skeleton) {
  112900. serializationObject.skeletons = serializationObject.skeletons || [];
  112901. serializationObject.skeletons.push(mesh.skeleton.serialize());
  112902. }
  112903. //serialize the actual mesh
  112904. serializationObject.meshes = serializationObject.meshes || [];
  112905. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  112906. }
  112907. };
  112908. /**
  112909. * Class used to serialize a scene into a string
  112910. */
  112911. var SceneSerializer = /** @class */ (function () {
  112912. function SceneSerializer() {
  112913. }
  112914. /**
  112915. * Clear cache used by a previous serialization
  112916. */
  112917. SceneSerializer.ClearCache = function () {
  112918. serializedGeometries = [];
  112919. };
  112920. /**
  112921. * Serialize a scene into a JSON compatible object
  112922. * @param scene defines the scene to serialize
  112923. * @returns a JSON compatible object
  112924. */
  112925. SceneSerializer.Serialize = function (scene) {
  112926. var serializationObject = {};
  112927. SceneSerializer.ClearCache();
  112928. // Scene
  112929. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  112930. serializationObject.autoClear = scene.autoClear;
  112931. serializationObject.clearColor = scene.clearColor.asArray();
  112932. serializationObject.ambientColor = scene.ambientColor.asArray();
  112933. serializationObject.gravity = scene.gravity.asArray();
  112934. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  112935. serializationObject.workerCollisions = scene.workerCollisions;
  112936. // Fog
  112937. if (scene.fogMode && scene.fogMode !== 0) {
  112938. serializationObject.fogMode = scene.fogMode;
  112939. serializationObject.fogColor = scene.fogColor.asArray();
  112940. serializationObject.fogStart = scene.fogStart;
  112941. serializationObject.fogEnd = scene.fogEnd;
  112942. serializationObject.fogDensity = scene.fogDensity;
  112943. }
  112944. //Physics
  112945. if (scene.isPhysicsEnabled()) {
  112946. var physicEngine = scene.getPhysicsEngine();
  112947. if (physicEngine) {
  112948. serializationObject.physicsEnabled = true;
  112949. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  112950. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  112951. }
  112952. }
  112953. // Metadata
  112954. if (scene.metadata) {
  112955. serializationObject.metadata = scene.metadata;
  112956. }
  112957. // Morph targets
  112958. serializationObject.morphTargetManagers = [];
  112959. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  112960. var abstractMesh = _a[_i];
  112961. var manager = abstractMesh.morphTargetManager;
  112962. if (manager) {
  112963. serializationObject.morphTargetManagers.push(manager.serialize());
  112964. }
  112965. }
  112966. // Lights
  112967. serializationObject.lights = [];
  112968. var index;
  112969. var light;
  112970. for (index = 0; index < scene.lights.length; index++) {
  112971. light = scene.lights[index];
  112972. if (!light.doNotSerialize) {
  112973. serializationObject.lights.push(light.serialize());
  112974. }
  112975. }
  112976. // Cameras
  112977. serializationObject.cameras = [];
  112978. for (index = 0; index < scene.cameras.length; index++) {
  112979. var camera = scene.cameras[index];
  112980. if (!camera.doNotSerialize) {
  112981. serializationObject.cameras.push(camera.serialize());
  112982. }
  112983. }
  112984. if (scene.activeCamera) {
  112985. serializationObject.activeCameraID = scene.activeCamera.id;
  112986. }
  112987. // Animations
  112988. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  112989. // Materials
  112990. serializationObject.materials = [];
  112991. serializationObject.multiMaterials = [];
  112992. var material;
  112993. for (index = 0; index < scene.materials.length; index++) {
  112994. material = scene.materials[index];
  112995. if (!material.doNotSerialize) {
  112996. serializationObject.materials.push(material.serialize());
  112997. }
  112998. }
  112999. // MultiMaterials
  113000. serializationObject.multiMaterials = [];
  113001. for (index = 0; index < scene.multiMaterials.length; index++) {
  113002. var multiMaterial = scene.multiMaterials[index];
  113003. serializationObject.multiMaterials.push(multiMaterial.serialize());
  113004. }
  113005. // Environment texture
  113006. if (scene.environmentTexture) {
  113007. serializationObject.environmentTexture = scene.environmentTexture.name;
  113008. }
  113009. // Skeletons
  113010. serializationObject.skeletons = [];
  113011. for (index = 0; index < scene.skeletons.length; index++) {
  113012. var skeleton = scene.skeletons[index];
  113013. if (!skeleton.doNotSerialize) {
  113014. serializationObject.skeletons.push(skeleton.serialize());
  113015. }
  113016. }
  113017. // Transform nodes
  113018. serializationObject.transformNodes = [];
  113019. for (index = 0; index < scene.transformNodes.length; index++) {
  113020. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  113021. }
  113022. // Geometries
  113023. serializationObject.geometries = {};
  113024. serializationObject.geometries.boxes = [];
  113025. serializationObject.geometries.spheres = [];
  113026. serializationObject.geometries.cylinders = [];
  113027. serializationObject.geometries.toruses = [];
  113028. serializationObject.geometries.grounds = [];
  113029. serializationObject.geometries.planes = [];
  113030. serializationObject.geometries.torusKnots = [];
  113031. serializationObject.geometries.vertexData = [];
  113032. serializedGeometries = [];
  113033. var geometries = scene.getGeometries();
  113034. for (index = 0; index < geometries.length; index++) {
  113035. var geometry = geometries[index];
  113036. if (geometry.isReady()) {
  113037. serializeGeometry(geometry, serializationObject.geometries);
  113038. }
  113039. }
  113040. // Meshes
  113041. serializationObject.meshes = [];
  113042. for (index = 0; index < scene.meshes.length; index++) {
  113043. var abstractMesh = scene.meshes[index];
  113044. if (abstractMesh instanceof BABYLON.Mesh) {
  113045. var mesh = abstractMesh;
  113046. if (!mesh.doNotSerialize) {
  113047. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113048. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113049. }
  113050. }
  113051. }
  113052. }
  113053. // Particles Systems
  113054. serializationObject.particleSystems = [];
  113055. for (index = 0; index < scene.particleSystems.length; index++) {
  113056. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  113057. }
  113058. // Action Manager
  113059. if (scene.actionManager) {
  113060. serializationObject.actions = scene.actionManager.serialize("scene");
  113061. }
  113062. // Components
  113063. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  113064. var component = _c[_b];
  113065. component.serialize(serializationObject);
  113066. }
  113067. return serializationObject;
  113068. };
  113069. /**
  113070. * Serialize a mesh into a JSON compatible object
  113071. * @param toSerialize defines the mesh to serialize
  113072. * @param withParents defines if parents must be serialized as well
  113073. * @param withChildren defines if children must be serialized as well
  113074. * @returns a JSON compatible object
  113075. */
  113076. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  113077. if (withParents === void 0) { withParents = false; }
  113078. if (withChildren === void 0) { withChildren = false; }
  113079. var serializationObject = {};
  113080. SceneSerializer.ClearCache();
  113081. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  113082. if (withParents || withChildren) {
  113083. //deliberate for loop! not for each, appended should be processed as well.
  113084. for (var i = 0; i < toSerialize.length; ++i) {
  113085. if (withChildren) {
  113086. toSerialize[i].getDescendants().forEach(function (node) {
  113087. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  113088. toSerialize.push(node);
  113089. }
  113090. });
  113091. }
  113092. //make sure the array doesn't contain the object already
  113093. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  113094. toSerialize.push(toSerialize[i].parent);
  113095. }
  113096. }
  113097. }
  113098. toSerialize.forEach(function (mesh) {
  113099. finalizeSingleMesh(mesh, serializationObject);
  113100. });
  113101. return serializationObject;
  113102. };
  113103. return SceneSerializer;
  113104. }());
  113105. BABYLON.SceneSerializer = SceneSerializer;
  113106. })(BABYLON || (BABYLON = {}));
  113107. //# sourceMappingURL=babylon.sceneSerializer.js.map
  113108. var BABYLON;
  113109. (function (BABYLON) {
  113110. /**
  113111. * Class used to generate realtime reflection / refraction cube textures
  113112. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  113113. */
  113114. var ReflectionProbe = /** @class */ (function () {
  113115. /**
  113116. * Creates a new reflection probe
  113117. * @param name defines the name of the probe
  113118. * @param size defines the texture resolution (for each face)
  113119. * @param scene defines the hosting scene
  113120. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  113121. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  113122. */
  113123. function ReflectionProbe(
  113124. /** defines the name of the probe */
  113125. name, size, scene, generateMipMaps, useFloat) {
  113126. if (generateMipMaps === void 0) { generateMipMaps = true; }
  113127. if (useFloat === void 0) { useFloat = false; }
  113128. var _this = this;
  113129. this.name = name;
  113130. this._viewMatrix = BABYLON.Matrix.Identity();
  113131. this._target = BABYLON.Vector3.Zero();
  113132. this._add = BABYLON.Vector3.Zero();
  113133. this._invertYAxis = false;
  113134. /** Gets or sets probe position (center of the cube map) */
  113135. this.position = BABYLON.Vector3.Zero();
  113136. this._scene = scene;
  113137. // Create the scene field if not exist.
  113138. if (!this._scene.reflectionProbes) {
  113139. this._scene.reflectionProbes = new Array();
  113140. }
  113141. this._scene.reflectionProbes.push(this);
  113142. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  113143. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  113144. switch (faceIndex) {
  113145. case 0:
  113146. _this._add.copyFromFloats(1, 0, 0);
  113147. break;
  113148. case 1:
  113149. _this._add.copyFromFloats(-1, 0, 0);
  113150. break;
  113151. case 2:
  113152. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  113153. break;
  113154. case 3:
  113155. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  113156. break;
  113157. case 4:
  113158. _this._add.copyFromFloats(0, 0, 1);
  113159. break;
  113160. case 5:
  113161. _this._add.copyFromFloats(0, 0, -1);
  113162. break;
  113163. }
  113164. if (_this._attachedMesh) {
  113165. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  113166. }
  113167. _this.position.addToRef(_this._add, _this._target);
  113168. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  113169. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  113170. scene._forcedViewPosition = _this.position;
  113171. });
  113172. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  113173. scene._forcedViewPosition = null;
  113174. scene.updateTransformMatrix(true);
  113175. });
  113176. if (scene.activeCamera) {
  113177. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  113178. }
  113179. }
  113180. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  113181. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  113182. get: function () {
  113183. return this._renderTargetTexture.samples;
  113184. },
  113185. set: function (value) {
  113186. this._renderTargetTexture.samples = value;
  113187. },
  113188. enumerable: true,
  113189. configurable: true
  113190. });
  113191. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  113192. /** Gets or sets the refresh rate to use (on every frame by default) */
  113193. get: function () {
  113194. return this._renderTargetTexture.refreshRate;
  113195. },
  113196. set: function (value) {
  113197. this._renderTargetTexture.refreshRate = value;
  113198. },
  113199. enumerable: true,
  113200. configurable: true
  113201. });
  113202. /**
  113203. * Gets the hosting scene
  113204. * @returns a Scene
  113205. */
  113206. ReflectionProbe.prototype.getScene = function () {
  113207. return this._scene;
  113208. };
  113209. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  113210. /** Gets the internal CubeTexture used to render to */
  113211. get: function () {
  113212. return this._renderTargetTexture;
  113213. },
  113214. enumerable: true,
  113215. configurable: true
  113216. });
  113217. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  113218. /** Gets the list of meshes to render */
  113219. get: function () {
  113220. return this._renderTargetTexture.renderList;
  113221. },
  113222. enumerable: true,
  113223. configurable: true
  113224. });
  113225. /**
  113226. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  113227. * @param mesh defines the mesh to attach to
  113228. */
  113229. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  113230. this._attachedMesh = mesh;
  113231. };
  113232. /**
  113233. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  113234. * @param renderingGroupId The rendering group id corresponding to its index
  113235. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  113236. */
  113237. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  113238. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  113239. };
  113240. /**
  113241. * Clean all associated resources
  113242. */
  113243. ReflectionProbe.prototype.dispose = function () {
  113244. var index = this._scene.reflectionProbes.indexOf(this);
  113245. if (index !== -1) {
  113246. // Remove from the scene if found
  113247. this._scene.reflectionProbes.splice(index, 1);
  113248. }
  113249. if (this._renderTargetTexture) {
  113250. this._renderTargetTexture.dispose();
  113251. this._renderTargetTexture = null;
  113252. }
  113253. };
  113254. return ReflectionProbe;
  113255. }());
  113256. BABYLON.ReflectionProbe = ReflectionProbe;
  113257. })(BABYLON || (BABYLON = {}));
  113258. //# sourceMappingURL=babylon.reflectionProbe.js.map
  113259. var BABYLON;
  113260. (function (BABYLON) {
  113261. /**
  113262. * Defines the layer scene component responsible to manage any layers
  113263. * in a given scene.
  113264. */
  113265. var LayerSceneComponent = /** @class */ (function () {
  113266. /**
  113267. * Creates a new instance of the component for the given scene
  113268. * @param scene Defines the scene to register the component in
  113269. */
  113270. function LayerSceneComponent(scene) {
  113271. /**
  113272. * The component name helpfull to identify the component in the list of scene components.
  113273. */
  113274. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  113275. this.scene = scene;
  113276. this._engine = scene.getEngine();
  113277. scene.layers = new Array();
  113278. }
  113279. /**
  113280. * Registers the component in a given scene
  113281. */
  113282. LayerSceneComponent.prototype.register = function () {
  113283. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  113284. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  113285. };
  113286. /**
  113287. * Rebuilds the elements related to this component in case of
  113288. * context lost for instance.
  113289. */
  113290. LayerSceneComponent.prototype.rebuild = function () {
  113291. var layers = this.scene.layers;
  113292. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  113293. var layer = layers_1[_i];
  113294. layer._rebuild();
  113295. }
  113296. };
  113297. /**
  113298. * Disposes the component and the associated ressources.
  113299. */
  113300. LayerSceneComponent.prototype.dispose = function () {
  113301. var layers = this.scene.layers;
  113302. while (layers.length) {
  113303. layers[0].dispose();
  113304. }
  113305. };
  113306. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  113307. var layers = this.scene.layers;
  113308. if (layers.length) {
  113309. this._engine.setDepthBuffer(false);
  113310. var cameraLayerMask = camera.layerMask;
  113311. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  113312. var layer = layers_2[_i];
  113313. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  113314. layer.render();
  113315. }
  113316. }
  113317. this._engine.setDepthBuffer(true);
  113318. }
  113319. };
  113320. LayerSceneComponent.prototype._drawBackground = function (camera) {
  113321. this._draw(camera, true);
  113322. };
  113323. LayerSceneComponent.prototype._drawForeground = function (camera) {
  113324. this._draw(camera, false);
  113325. };
  113326. return LayerSceneComponent;
  113327. }());
  113328. BABYLON.LayerSceneComponent = LayerSceneComponent;
  113329. })(BABYLON || (BABYLON = {}));
  113330. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  113331. var BABYLON;
  113332. (function (BABYLON) {
  113333. /**
  113334. * This represents a full screen 2d layer.
  113335. * This can be usefull to display a picture in the background of your scene for instance.
  113336. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113337. */
  113338. var Layer = /** @class */ (function () {
  113339. /**
  113340. * Instantiates a new layer.
  113341. * This represents a full screen 2d layer.
  113342. * This can be usefull to display a picture in the background of your scene for instance.
  113343. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113344. * @param name Define the name of the layer in the scene
  113345. * @param imgUrl Define the url of the texture to display in the layer
  113346. * @param scene Define the scene the layer belongs to
  113347. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  113348. * @param color Defines a color for the layer
  113349. */
  113350. function Layer(
  113351. /**
  113352. * Define the name of the layer.
  113353. */
  113354. name, imgUrl, scene, isBackground, color) {
  113355. this.name = name;
  113356. /**
  113357. * Define the scale of the layer in order to zoom in out of the texture.
  113358. */
  113359. this.scale = new BABYLON.Vector2(1, 1);
  113360. /**
  113361. * Define an offset for the layer in order to shift the texture.
  113362. */
  113363. this.offset = new BABYLON.Vector2(0, 0);
  113364. /**
  113365. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  113366. */
  113367. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  113368. /**
  113369. * Define a mask to restrict the layer to only some of the scene cameras.
  113370. */
  113371. this.layerMask = 0x0FFFFFFF;
  113372. this._vertexBuffers = {};
  113373. /**
  113374. * An event triggered when the layer is disposed.
  113375. */
  113376. this.onDisposeObservable = new BABYLON.Observable();
  113377. /**
  113378. * An event triggered before rendering the scene
  113379. */
  113380. this.onBeforeRenderObservable = new BABYLON.Observable();
  113381. /**
  113382. * An event triggered after rendering the scene
  113383. */
  113384. this.onAfterRenderObservable = new BABYLON.Observable();
  113385. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  113386. this.isBackground = isBackground === undefined ? true : isBackground;
  113387. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  113388. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  113389. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  113390. if (!layerComponent) {
  113391. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  113392. this._scene._addComponent(layerComponent);
  113393. }
  113394. this._scene.layers.push(this);
  113395. var engine = this._scene.getEngine();
  113396. // VBO
  113397. var vertices = [];
  113398. vertices.push(1, 1);
  113399. vertices.push(-1, 1);
  113400. vertices.push(-1, -1);
  113401. vertices.push(1, -1);
  113402. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  113403. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  113404. this._createIndexBuffer();
  113405. // Effects
  113406. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  113407. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  113408. }
  113409. Object.defineProperty(Layer.prototype, "onDispose", {
  113410. /**
  113411. * Back compatibility with callback before the onDisposeObservable existed.
  113412. * The set callback will be triggered when the layer has been disposed.
  113413. */
  113414. set: function (callback) {
  113415. if (this._onDisposeObserver) {
  113416. this.onDisposeObservable.remove(this._onDisposeObserver);
  113417. }
  113418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  113419. },
  113420. enumerable: true,
  113421. configurable: true
  113422. });
  113423. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  113424. /**
  113425. * Back compatibility with callback before the onBeforeRenderObservable existed.
  113426. * The set callback will be triggered just before rendering the layer.
  113427. */
  113428. set: function (callback) {
  113429. if (this._onBeforeRenderObserver) {
  113430. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  113431. }
  113432. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  113433. },
  113434. enumerable: true,
  113435. configurable: true
  113436. });
  113437. Object.defineProperty(Layer.prototype, "onAfterRender", {
  113438. /**
  113439. * Back compatibility with callback before the onAfterRenderObservable existed.
  113440. * The set callback will be triggered just after rendering the layer.
  113441. */
  113442. set: function (callback) {
  113443. if (this._onAfterRenderObserver) {
  113444. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  113445. }
  113446. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  113447. },
  113448. enumerable: true,
  113449. configurable: true
  113450. });
  113451. Layer.prototype._createIndexBuffer = function () {
  113452. var engine = this._scene.getEngine();
  113453. // Indices
  113454. var indices = [];
  113455. indices.push(0);
  113456. indices.push(1);
  113457. indices.push(2);
  113458. indices.push(0);
  113459. indices.push(2);
  113460. indices.push(3);
  113461. this._indexBuffer = engine.createIndexBuffer(indices);
  113462. };
  113463. /** @hidden */
  113464. Layer.prototype._rebuild = function () {
  113465. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113466. if (vb) {
  113467. vb._rebuild();
  113468. }
  113469. this._createIndexBuffer();
  113470. };
  113471. /**
  113472. * Renders the layer in the scene.
  113473. */
  113474. Layer.prototype.render = function () {
  113475. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  113476. // Check
  113477. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  113478. return;
  113479. }
  113480. var engine = this._scene.getEngine();
  113481. this.onBeforeRenderObservable.notifyObservers(this);
  113482. // Render
  113483. engine.enableEffect(currentEffect);
  113484. engine.setState(false);
  113485. // Texture
  113486. currentEffect.setTexture("textureSampler", this.texture);
  113487. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  113488. // Color
  113489. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  113490. // Scale / offset
  113491. currentEffect.setVector2("offset", this.offset);
  113492. currentEffect.setVector2("scale", this.scale);
  113493. // VBOs
  113494. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  113495. // Draw order
  113496. if (!this.alphaTest) {
  113497. engine.setAlphaMode(this.alphaBlendingMode);
  113498. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  113499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  113500. }
  113501. else {
  113502. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  113503. }
  113504. this.onAfterRenderObservable.notifyObservers(this);
  113505. };
  113506. /**
  113507. * Disposes and releases the associated ressources.
  113508. */
  113509. Layer.prototype.dispose = function () {
  113510. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113511. if (vertexBuffer) {
  113512. vertexBuffer.dispose();
  113513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  113514. }
  113515. if (this._indexBuffer) {
  113516. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  113517. this._indexBuffer = null;
  113518. }
  113519. if (this.texture) {
  113520. this.texture.dispose();
  113521. this.texture = null;
  113522. }
  113523. // Remove from scene
  113524. var index = this._scene.layers.indexOf(this);
  113525. this._scene.layers.splice(index, 1);
  113526. // Callback
  113527. this.onDisposeObservable.notifyObservers(this);
  113528. this.onDisposeObservable.clear();
  113529. this.onAfterRenderObservable.clear();
  113530. this.onBeforeRenderObservable.clear();
  113531. };
  113532. return Layer;
  113533. }());
  113534. BABYLON.Layer = Layer;
  113535. })(BABYLON || (BABYLON = {}));
  113536. //# sourceMappingURL=babylon.layer.js.map
  113537. var BABYLON;
  113538. (function (BABYLON) {
  113539. /**
  113540. * Class used to host texture specific utilities
  113541. */
  113542. var TextureTools = /** @class */ (function () {
  113543. function TextureTools() {
  113544. }
  113545. /**
  113546. * Uses the GPU to create a copy texture rescaled at a given size
  113547. * @param texture Texture to copy from
  113548. * @param width defines the desired width
  113549. * @param height defines the desired height
  113550. * @param useBilinearMode defines if bilinear mode has to be used
  113551. * @return the generated texture
  113552. */
  113553. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  113554. if (useBilinearMode === void 0) { useBilinearMode = true; }
  113555. var scene = texture.getScene();
  113556. var engine = scene.getEngine();
  113557. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  113558. rtt.wrapU = texture.wrapU;
  113559. rtt.wrapV = texture.wrapV;
  113560. rtt.uOffset = texture.uOffset;
  113561. rtt.vOffset = texture.vOffset;
  113562. rtt.uScale = texture.uScale;
  113563. rtt.vScale = texture.vScale;
  113564. rtt.uAng = texture.uAng;
  113565. rtt.vAng = texture.vAng;
  113566. rtt.wAng = texture.wAng;
  113567. rtt.coordinatesIndex = texture.coordinatesIndex;
  113568. rtt.level = texture.level;
  113569. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  113570. rtt._texture.isReady = false;
  113571. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113572. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113573. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  113574. passPostProcess.getEffect().executeWhenCompiled(function () {
  113575. passPostProcess.onApply = function (effect) {
  113576. effect.setTexture("textureSampler", texture);
  113577. };
  113578. var internalTexture = rtt.getInternalTexture();
  113579. if (internalTexture) {
  113580. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  113581. engine.unBindFramebuffer(internalTexture);
  113582. rtt.disposeFramebufferObjects();
  113583. passPostProcess.dispose();
  113584. internalTexture.isReady = true;
  113585. }
  113586. });
  113587. return rtt;
  113588. };
  113589. /**
  113590. * Gets an environment BRDF texture for a given scene
  113591. * @param scene defines the hosting scene
  113592. * @returns the environment BRDF texture
  113593. */
  113594. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  113595. if (!scene._environmentBRDFTexture) {
  113596. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  113597. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113598. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113599. scene._environmentBRDFTexture = texture;
  113600. }
  113601. return scene._environmentBRDFTexture;
  113602. };
  113603. 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=";
  113604. return TextureTools;
  113605. }());
  113606. BABYLON.TextureTools = TextureTools;
  113607. })(BABYLON || (BABYLON = {}));
  113608. //# sourceMappingURL=babylon.textureTools.js.map
  113609. var BABYLON;
  113610. (function (BABYLON) {
  113611. /**
  113612. * 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.
  113613. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  113614. */
  113615. var FramingBehavior = /** @class */ (function () {
  113616. function FramingBehavior() {
  113617. this._mode = FramingBehavior.FitFrustumSidesMode;
  113618. this._radiusScale = 1.0;
  113619. this._positionScale = 0.5;
  113620. this._defaultElevation = 0.3;
  113621. this._elevationReturnTime = 1500;
  113622. this._elevationReturnWaitTime = 1000;
  113623. this._zoomStopsAnimation = false;
  113624. this._framingTime = 1500;
  113625. /**
  113626. * Define if the behavior should automatically change the configured
  113627. * camera limits and sensibilities.
  113628. */
  113629. this.autoCorrectCameraLimitsAndSensibility = true;
  113630. this._isPointerDown = false;
  113631. this._lastInteractionTime = -Infinity;
  113632. // Framing control
  113633. this._animatables = new Array();
  113634. this._betaIsAnimating = false;
  113635. }
  113636. Object.defineProperty(FramingBehavior.prototype, "name", {
  113637. /**
  113638. * Gets the name of the behavior.
  113639. */
  113640. get: function () {
  113641. return "Framing";
  113642. },
  113643. enumerable: true,
  113644. configurable: true
  113645. });
  113646. Object.defineProperty(FramingBehavior.prototype, "mode", {
  113647. /**
  113648. * Gets current mode used by the behavior.
  113649. */
  113650. get: function () {
  113651. return this._mode;
  113652. },
  113653. /**
  113654. * Sets the current mode used by the behavior
  113655. */
  113656. set: function (mode) {
  113657. this._mode = mode;
  113658. },
  113659. enumerable: true,
  113660. configurable: true
  113661. });
  113662. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  113663. /**
  113664. * Gets the scale applied to the radius
  113665. */
  113666. get: function () {
  113667. return this._radiusScale;
  113668. },
  113669. /**
  113670. * Sets the scale applied to the radius (1 by default)
  113671. */
  113672. set: function (radius) {
  113673. this._radiusScale = radius;
  113674. },
  113675. enumerable: true,
  113676. configurable: true
  113677. });
  113678. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  113679. /**
  113680. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  113681. */
  113682. get: function () {
  113683. return this._positionScale;
  113684. },
  113685. /**
  113686. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  113687. */
  113688. set: function (scale) {
  113689. this._positionScale = scale;
  113690. },
  113691. enumerable: true,
  113692. configurable: true
  113693. });
  113694. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  113695. /**
  113696. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  113697. * behaviour is triggered, in radians.
  113698. */
  113699. get: function () {
  113700. return this._defaultElevation;
  113701. },
  113702. /**
  113703. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  113704. * behaviour is triggered, in radians.
  113705. */
  113706. set: function (elevation) {
  113707. this._defaultElevation = elevation;
  113708. },
  113709. enumerable: true,
  113710. configurable: true
  113711. });
  113712. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  113713. /**
  113714. * Gets the time (in milliseconds) taken to return to the default beta position.
  113715. * Negative value indicates camera should not return to default.
  113716. */
  113717. get: function () {
  113718. return this._elevationReturnTime;
  113719. },
  113720. /**
  113721. * Sets the time (in milliseconds) taken to return to the default beta position.
  113722. * Negative value indicates camera should not return to default.
  113723. */
  113724. set: function (speed) {
  113725. this._elevationReturnTime = speed;
  113726. },
  113727. enumerable: true,
  113728. configurable: true
  113729. });
  113730. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  113731. /**
  113732. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  113733. */
  113734. get: function () {
  113735. return this._elevationReturnWaitTime;
  113736. },
  113737. /**
  113738. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  113739. */
  113740. set: function (time) {
  113741. this._elevationReturnWaitTime = time;
  113742. },
  113743. enumerable: true,
  113744. configurable: true
  113745. });
  113746. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  113747. /**
  113748. * Gets the flag that indicates if user zooming should stop animation.
  113749. */
  113750. get: function () {
  113751. return this._zoomStopsAnimation;
  113752. },
  113753. /**
  113754. * Sets the flag that indicates if user zooming should stop animation.
  113755. */
  113756. set: function (flag) {
  113757. this._zoomStopsAnimation = flag;
  113758. },
  113759. enumerable: true,
  113760. configurable: true
  113761. });
  113762. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  113763. /**
  113764. * Gets the transition time when framing the mesh, in milliseconds
  113765. */
  113766. get: function () {
  113767. return this._framingTime;
  113768. },
  113769. /**
  113770. * Sets the transition time when framing the mesh, in milliseconds
  113771. */
  113772. set: function (time) {
  113773. this._framingTime = time;
  113774. },
  113775. enumerable: true,
  113776. configurable: true
  113777. });
  113778. /**
  113779. * Initializes the behavior.
  113780. */
  113781. FramingBehavior.prototype.init = function () {
  113782. // Do notihng
  113783. };
  113784. /**
  113785. * Attaches the behavior to its arc rotate camera.
  113786. * @param camera Defines the camera to attach the behavior to
  113787. */
  113788. FramingBehavior.prototype.attach = function (camera) {
  113789. var _this = this;
  113790. this._attachedCamera = camera;
  113791. var scene = this._attachedCamera.getScene();
  113792. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  113793. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  113794. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  113795. _this._isPointerDown = true;
  113796. return;
  113797. }
  113798. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  113799. _this._isPointerDown = false;
  113800. }
  113801. });
  113802. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  113803. if (mesh) {
  113804. _this.zoomOnMesh(mesh);
  113805. }
  113806. });
  113807. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  113808. // Stop the animation if there is user interaction and the animation should stop for this interaction
  113809. _this._applyUserInteraction();
  113810. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  113811. // back to the default position after a given timeout
  113812. _this._maintainCameraAboveGround();
  113813. });
  113814. };
  113815. /**
  113816. * Detaches the behavior from its current arc rotate camera.
  113817. */
  113818. FramingBehavior.prototype.detach = function () {
  113819. if (!this._attachedCamera) {
  113820. return;
  113821. }
  113822. var scene = this._attachedCamera.getScene();
  113823. if (this._onPrePointerObservableObserver) {
  113824. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  113825. }
  113826. if (this._onAfterCheckInputsObserver) {
  113827. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  113828. }
  113829. if (this._onMeshTargetChangedObserver) {
  113830. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  113831. }
  113832. this._attachedCamera = null;
  113833. };
  113834. /**
  113835. * Targets the given mesh and updates zoom level accordingly.
  113836. * @param mesh The mesh to target.
  113837. * @param radius Optional. If a cached radius position already exists, overrides default.
  113838. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  113839. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  113840. * @param onAnimationEnd Callback triggered at the end of the framing animation
  113841. */
  113842. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  113843. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  113844. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  113845. mesh.computeWorldMatrix(true);
  113846. var boundingBox = mesh.getBoundingInfo().boundingBox;
  113847. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  113848. };
  113849. /**
  113850. * Targets the given mesh with its children and updates zoom level accordingly.
  113851. * @param mesh The mesh to target.
  113852. * @param radius Optional. If a cached radius position already exists, overrides default.
  113853. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  113854. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  113855. * @param onAnimationEnd Callback triggered at the end of the framing animation
  113856. */
  113857. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  113858. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  113859. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  113860. mesh.computeWorldMatrix(true);
  113861. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  113862. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  113863. };
  113864. /**
  113865. * Targets the given meshes with their children and updates zoom level accordingly.
  113866. * @param meshes The mesh to target.
  113867. * @param radius Optional. If a cached radius position already exists, overrides default.
  113868. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  113869. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  113870. * @param onAnimationEnd Callback triggered at the end of the framing animation
  113871. */
  113872. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  113873. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  113874. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  113875. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  113876. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  113877. for (var i = 0; i < meshes.length; i++) {
  113878. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  113879. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  113880. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  113881. }
  113882. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  113883. };
  113884. /**
  113885. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  113886. * @param minimumWorld Determines the smaller position of the bounding box extend
  113887. * @param maximumWorld Determines the bigger position of the bounding box extend
  113888. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  113889. * @param onAnimationEnd Callback triggered at the end of the framing animation
  113890. */
  113891. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  113892. var _this = this;
  113893. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  113894. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  113895. var zoomTarget;
  113896. if (!this._attachedCamera) {
  113897. return;
  113898. }
  113899. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  113900. var bottom = minimumWorld.y;
  113901. var top = maximumWorld.y;
  113902. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  113903. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  113904. if (focusOnOriginXZ) {
  113905. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  113906. }
  113907. else {
  113908. var centerWorld = minimumWorld.add(radiusWorld);
  113909. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  113910. }
  113911. if (!this._vectorTransition) {
  113912. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  113913. }
  113914. this._betaIsAnimating = true;
  113915. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  113916. if (animatable) {
  113917. this._animatables.push(animatable);
  113918. }
  113919. // sets the radius and lower radius bounds
  113920. // Small delta ensures camera is not always at lower zoom limit.
  113921. var radius = 0;
  113922. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  113923. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  113924. if (this.autoCorrectCameraLimitsAndSensibility) {
  113925. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  113926. }
  113927. radius = position;
  113928. }
  113929. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  113930. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  113931. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  113932. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  113933. }
  113934. }
  113935. // Set sensibilities
  113936. if (this.autoCorrectCameraLimitsAndSensibility) {
  113937. var extend = maximumWorld.subtract(minimumWorld).length();
  113938. this._attachedCamera.panningSensibility = 5000 / extend;
  113939. this._attachedCamera.wheelPrecision = 100 / radius;
  113940. }
  113941. // transition to new radius
  113942. if (!this._radiusTransition) {
  113943. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  113944. }
  113945. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  113946. _this.stopAllAnimations();
  113947. if (onAnimationEnd) {
  113948. onAnimationEnd();
  113949. }
  113950. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  113951. _this._attachedCamera.storeState();
  113952. }
  113953. });
  113954. if (animatable) {
  113955. this._animatables.push(animatable);
  113956. }
  113957. };
  113958. /**
  113959. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  113960. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  113961. * frustum width.
  113962. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  113963. * to fully enclose the mesh in the viewing frustum.
  113964. */
  113965. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  113966. var size = maximumWorld.subtract(minimumWorld);
  113967. var boxVectorGlobalDiagonal = size.length();
  113968. var frustumSlope = this._getFrustumSlope();
  113969. // Formula for setting distance
  113970. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  113971. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  113972. // Horizon distance
  113973. var radius = radiusWithoutFraming * this._radiusScale;
  113974. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  113975. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  113976. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  113977. var camera = this._attachedCamera;
  113978. if (!camera) {
  113979. return 0;
  113980. }
  113981. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  113982. // Don't exceed the requested limit
  113983. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  113984. }
  113985. // Don't exceed the upper radius limit
  113986. if (camera.upperRadiusLimit) {
  113987. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  113988. }
  113989. return distance;
  113990. };
  113991. /**
  113992. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  113993. * is automatically returned to its default position (expected to be above ground plane).
  113994. */
  113995. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  113996. var _this = this;
  113997. if (this._elevationReturnTime < 0) {
  113998. return;
  113999. }
  114000. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  114001. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  114002. var limitBeta = Math.PI * 0.5;
  114003. // Bring the camera back up if below the ground plane
  114004. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  114005. this._betaIsAnimating = true;
  114006. //Transition to new position
  114007. this.stopAllAnimations();
  114008. if (!this._betaTransition) {
  114009. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114010. }
  114011. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  114012. _this._clearAnimationLocks();
  114013. _this.stopAllAnimations();
  114014. });
  114015. if (animatabe) {
  114016. this._animatables.push(animatabe);
  114017. }
  114018. }
  114019. };
  114020. /**
  114021. * Returns the frustum slope based on the canvas ratio and camera FOV
  114022. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  114023. */
  114024. FramingBehavior.prototype._getFrustumSlope = function () {
  114025. // Calculate the viewport ratio
  114026. // Aspect Ratio is Height/Width.
  114027. var camera = this._attachedCamera;
  114028. if (!camera) {
  114029. return BABYLON.Vector2.Zero();
  114030. }
  114031. var engine = camera.getScene().getEngine();
  114032. var aspectRatio = engine.getAspectRatio(camera);
  114033. // Camera FOV is the vertical field of view (top-bottom) in radians.
  114034. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  114035. var frustumSlopeY = Math.tan(camera.fov / 2);
  114036. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  114037. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  114038. // along the forward vector.
  114039. var frustumSlopeX = frustumSlopeY * aspectRatio;
  114040. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  114041. };
  114042. /**
  114043. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  114044. */
  114045. FramingBehavior.prototype._clearAnimationLocks = function () {
  114046. this._betaIsAnimating = false;
  114047. };
  114048. /**
  114049. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114050. */
  114051. FramingBehavior.prototype._applyUserInteraction = function () {
  114052. if (this.isUserIsMoving) {
  114053. this._lastInteractionTime = BABYLON.Tools.Now;
  114054. this.stopAllAnimations();
  114055. this._clearAnimationLocks();
  114056. }
  114057. };
  114058. /**
  114059. * Stops and removes all animations that have been applied to the camera
  114060. */
  114061. FramingBehavior.prototype.stopAllAnimations = function () {
  114062. if (this._attachedCamera) {
  114063. this._attachedCamera.animations = [];
  114064. }
  114065. while (this._animatables.length) {
  114066. if (this._animatables[0]) {
  114067. this._animatables[0].onAnimationEnd = null;
  114068. this._animatables[0].stop();
  114069. }
  114070. this._animatables.shift();
  114071. }
  114072. };
  114073. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  114074. /**
  114075. * Gets a value indicating if the user is moving the camera
  114076. */
  114077. get: function () {
  114078. if (!this._attachedCamera) {
  114079. return false;
  114080. }
  114081. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114082. this._attachedCamera.inertialBetaOffset !== 0 ||
  114083. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114084. this._attachedCamera.inertialPanningX !== 0 ||
  114085. this._attachedCamera.inertialPanningY !== 0 ||
  114086. this._isPointerDown;
  114087. },
  114088. enumerable: true,
  114089. configurable: true
  114090. });
  114091. /**
  114092. * The easing function used by animations
  114093. */
  114094. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  114095. /**
  114096. * The easing mode used by animations
  114097. */
  114098. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  114099. // Statics
  114100. /**
  114101. * The camera can move all the way towards the mesh.
  114102. */
  114103. FramingBehavior.IgnoreBoundsSizeMode = 0;
  114104. /**
  114105. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  114106. */
  114107. FramingBehavior.FitFrustumSidesMode = 1;
  114108. return FramingBehavior;
  114109. }());
  114110. BABYLON.FramingBehavior = FramingBehavior;
  114111. })(BABYLON || (BABYLON = {}));
  114112. //# sourceMappingURL=babylon.framingBehavior.js.map
  114113. var BABYLON;
  114114. (function (BABYLON) {
  114115. /**
  114116. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  114117. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  114118. */
  114119. var BouncingBehavior = /** @class */ (function () {
  114120. function BouncingBehavior() {
  114121. /**
  114122. * The duration of the animation, in milliseconds
  114123. */
  114124. this.transitionDuration = 450;
  114125. /**
  114126. * Length of the distance animated by the transition when lower radius is reached
  114127. */
  114128. this.lowerRadiusTransitionRange = 2;
  114129. /**
  114130. * Length of the distance animated by the transition when upper radius is reached
  114131. */
  114132. this.upperRadiusTransitionRange = -2;
  114133. this._autoTransitionRange = false;
  114134. // Animations
  114135. this._radiusIsAnimating = false;
  114136. this._radiusBounceTransition = null;
  114137. this._animatables = new Array();
  114138. }
  114139. Object.defineProperty(BouncingBehavior.prototype, "name", {
  114140. /**
  114141. * Gets the name of the behavior.
  114142. */
  114143. get: function () {
  114144. return "Bouncing";
  114145. },
  114146. enumerable: true,
  114147. configurable: true
  114148. });
  114149. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  114150. /**
  114151. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114152. */
  114153. get: function () {
  114154. return this._autoTransitionRange;
  114155. },
  114156. /**
  114157. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114158. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  114159. */
  114160. set: function (value) {
  114161. var _this = this;
  114162. if (this._autoTransitionRange === value) {
  114163. return;
  114164. }
  114165. this._autoTransitionRange = value;
  114166. var camera = this._attachedCamera;
  114167. if (!camera) {
  114168. return;
  114169. }
  114170. if (value) {
  114171. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114172. if (!mesh) {
  114173. return;
  114174. }
  114175. mesh.computeWorldMatrix(true);
  114176. var diagonal = mesh.getBoundingInfo().diagonalLength;
  114177. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  114178. _this.upperRadiusTransitionRange = diagonal * 0.05;
  114179. });
  114180. }
  114181. else if (this._onMeshTargetChangedObserver) {
  114182. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114183. }
  114184. },
  114185. enumerable: true,
  114186. configurable: true
  114187. });
  114188. /**
  114189. * Initializes the behavior.
  114190. */
  114191. BouncingBehavior.prototype.init = function () {
  114192. // Do notihng
  114193. };
  114194. /**
  114195. * Attaches the behavior to its arc rotate camera.
  114196. * @param camera Defines the camera to attach the behavior to
  114197. */
  114198. BouncingBehavior.prototype.attach = function (camera) {
  114199. var _this = this;
  114200. this._attachedCamera = camera;
  114201. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114202. if (!_this._attachedCamera) {
  114203. return;
  114204. }
  114205. // Add the bounce animation to the lower radius limit
  114206. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  114207. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  114208. }
  114209. // Add the bounce animation to the upper radius limit
  114210. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  114211. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  114212. }
  114213. });
  114214. };
  114215. /**
  114216. * Detaches the behavior from its current arc rotate camera.
  114217. */
  114218. BouncingBehavior.prototype.detach = function () {
  114219. if (!this._attachedCamera) {
  114220. return;
  114221. }
  114222. if (this._onAfterCheckInputsObserver) {
  114223. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114224. }
  114225. if (this._onMeshTargetChangedObserver) {
  114226. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114227. }
  114228. this._attachedCamera = null;
  114229. };
  114230. /**
  114231. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  114232. * @param radiusLimit The limit to check against.
  114233. * @return Bool to indicate if at limit.
  114234. */
  114235. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  114236. if (!this._attachedCamera) {
  114237. return false;
  114238. }
  114239. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  114240. return true;
  114241. }
  114242. return false;
  114243. };
  114244. /**
  114245. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  114246. * @param radiusDelta The delta by which to animate to. Can be negative.
  114247. */
  114248. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  114249. var _this = this;
  114250. if (!this._attachedCamera) {
  114251. return;
  114252. }
  114253. if (!this._radiusBounceTransition) {
  114254. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  114255. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  114256. }
  114257. // Prevent zoom until bounce has completed
  114258. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  114259. this._attachedCamera.wheelPrecision = Infinity;
  114260. this._attachedCamera.inertialRadiusOffset = 0;
  114261. // Animate to the radius limit
  114262. this.stopAllAnimations();
  114263. this._radiusIsAnimating = true;
  114264. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  114265. if (animatable) {
  114266. this._animatables.push(animatable);
  114267. }
  114268. };
  114269. /**
  114270. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  114271. */
  114272. BouncingBehavior.prototype._clearAnimationLocks = function () {
  114273. this._radiusIsAnimating = false;
  114274. if (this._attachedCamera) {
  114275. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  114276. }
  114277. };
  114278. /**
  114279. * Stops and removes all animations that have been applied to the camera
  114280. */
  114281. BouncingBehavior.prototype.stopAllAnimations = function () {
  114282. if (this._attachedCamera) {
  114283. this._attachedCamera.animations = [];
  114284. }
  114285. while (this._animatables.length) {
  114286. this._animatables[0].onAnimationEnd = null;
  114287. this._animatables[0].stop();
  114288. this._animatables.shift();
  114289. }
  114290. };
  114291. /**
  114292. * The easing function used by animations
  114293. */
  114294. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  114295. /**
  114296. * The easing mode used by animations
  114297. */
  114298. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  114299. return BouncingBehavior;
  114300. }());
  114301. BABYLON.BouncingBehavior = BouncingBehavior;
  114302. })(BABYLON || (BABYLON = {}));
  114303. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  114304. var BABYLON;
  114305. (function (BABYLON) {
  114306. /**
  114307. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  114308. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  114309. */
  114310. var AutoRotationBehavior = /** @class */ (function () {
  114311. function AutoRotationBehavior() {
  114312. this._zoomStopsAnimation = false;
  114313. this._idleRotationSpeed = 0.05;
  114314. this._idleRotationWaitTime = 2000;
  114315. this._idleRotationSpinupTime = 2000;
  114316. this._isPointerDown = false;
  114317. this._lastFrameTime = null;
  114318. this._lastInteractionTime = -Infinity;
  114319. this._cameraRotationSpeed = 0;
  114320. this._lastFrameRadius = 0;
  114321. }
  114322. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  114323. /**
  114324. * Gets the name of the behavior.
  114325. */
  114326. get: function () {
  114327. return "AutoRotation";
  114328. },
  114329. enumerable: true,
  114330. configurable: true
  114331. });
  114332. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  114333. /**
  114334. * Gets the flag that indicates if user zooming should stop animation.
  114335. */
  114336. get: function () {
  114337. return this._zoomStopsAnimation;
  114338. },
  114339. /**
  114340. * Sets the flag that indicates if user zooming should stop animation.
  114341. */
  114342. set: function (flag) {
  114343. this._zoomStopsAnimation = flag;
  114344. },
  114345. enumerable: true,
  114346. configurable: true
  114347. });
  114348. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  114349. /**
  114350. * Gets the default speed at which the camera rotates around the model.
  114351. */
  114352. get: function () {
  114353. return this._idleRotationSpeed;
  114354. },
  114355. /**
  114356. * Sets the default speed at which the camera rotates around the model.
  114357. */
  114358. set: function (speed) {
  114359. this._idleRotationSpeed = speed;
  114360. },
  114361. enumerable: true,
  114362. configurable: true
  114363. });
  114364. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  114365. /**
  114366. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  114367. */
  114368. get: function () {
  114369. return this._idleRotationWaitTime;
  114370. },
  114371. /**
  114372. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  114373. */
  114374. set: function (time) {
  114375. this._idleRotationWaitTime = time;
  114376. },
  114377. enumerable: true,
  114378. configurable: true
  114379. });
  114380. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  114381. /**
  114382. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  114383. */
  114384. get: function () {
  114385. return this._idleRotationSpinupTime;
  114386. },
  114387. /**
  114388. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  114389. */
  114390. set: function (time) {
  114391. this._idleRotationSpinupTime = time;
  114392. },
  114393. enumerable: true,
  114394. configurable: true
  114395. });
  114396. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  114397. /**
  114398. * Gets a value indicating if the camera is currently rotating because of this behavior
  114399. */
  114400. get: function () {
  114401. return Math.abs(this._cameraRotationSpeed) > 0;
  114402. },
  114403. enumerable: true,
  114404. configurable: true
  114405. });
  114406. /**
  114407. * Initializes the behavior.
  114408. */
  114409. AutoRotationBehavior.prototype.init = function () {
  114410. // Do notihng
  114411. };
  114412. /**
  114413. * Attaches the behavior to its arc rotate camera.
  114414. * @param camera Defines the camera to attach the behavior to
  114415. */
  114416. AutoRotationBehavior.prototype.attach = function (camera) {
  114417. var _this = this;
  114418. this._attachedCamera = camera;
  114419. var scene = this._attachedCamera.getScene();
  114420. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114421. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114422. _this._isPointerDown = true;
  114423. return;
  114424. }
  114425. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114426. _this._isPointerDown = false;
  114427. }
  114428. });
  114429. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114430. var now = BABYLON.Tools.Now;
  114431. var dt = 0;
  114432. if (_this._lastFrameTime != null) {
  114433. dt = now - _this._lastFrameTime;
  114434. }
  114435. _this._lastFrameTime = now;
  114436. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114437. _this._applyUserInteraction();
  114438. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  114439. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  114440. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  114441. // Step camera rotation by rotation speed
  114442. if (_this._attachedCamera) {
  114443. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  114444. }
  114445. });
  114446. };
  114447. /**
  114448. * Detaches the behavior from its current arc rotate camera.
  114449. */
  114450. AutoRotationBehavior.prototype.detach = function () {
  114451. if (!this._attachedCamera) {
  114452. return;
  114453. }
  114454. var scene = this._attachedCamera.getScene();
  114455. if (this._onPrePointerObservableObserver) {
  114456. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114457. }
  114458. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114459. this._attachedCamera = null;
  114460. };
  114461. /**
  114462. * Returns true if user is scrolling.
  114463. * @return true if user is scrolling.
  114464. */
  114465. AutoRotationBehavior.prototype._userIsZooming = function () {
  114466. if (!this._attachedCamera) {
  114467. return false;
  114468. }
  114469. return this._attachedCamera.inertialRadiusOffset !== 0;
  114470. };
  114471. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  114472. if (!this._attachedCamera) {
  114473. return false;
  114474. }
  114475. var zoomHasHitLimit = false;
  114476. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  114477. zoomHasHitLimit = true;
  114478. }
  114479. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  114480. this._lastFrameRadius = this._attachedCamera.radius;
  114481. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  114482. };
  114483. /**
  114484. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114485. */
  114486. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  114487. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  114488. this._lastInteractionTime = BABYLON.Tools.Now;
  114489. }
  114490. };
  114491. // Tools
  114492. AutoRotationBehavior.prototype._userIsMoving = function () {
  114493. if (!this._attachedCamera) {
  114494. return false;
  114495. }
  114496. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114497. this._attachedCamera.inertialBetaOffset !== 0 ||
  114498. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114499. this._attachedCamera.inertialPanningX !== 0 ||
  114500. this._attachedCamera.inertialPanningY !== 0 ||
  114501. this._isPointerDown;
  114502. };
  114503. return AutoRotationBehavior;
  114504. }());
  114505. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  114506. })(BABYLON || (BABYLON = {}));
  114507. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  114508. var BABYLON;
  114509. (function (BABYLON) {
  114510. /**
  114511. * Options to create the null engine
  114512. */
  114513. var NullEngineOptions = /** @class */ (function () {
  114514. function NullEngineOptions() {
  114515. /**
  114516. * Render width (Default: 512)
  114517. */
  114518. this.renderWidth = 512;
  114519. /**
  114520. * Render height (Default: 256)
  114521. */
  114522. this.renderHeight = 256;
  114523. /**
  114524. * Texture size (Default: 512)
  114525. */
  114526. this.textureSize = 512;
  114527. /**
  114528. * If delta time between frames should be constant
  114529. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114530. */
  114531. this.deterministicLockstep = false;
  114532. /**
  114533. * Maximum about of steps between frames (Default: 4)
  114534. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114535. */
  114536. this.lockstepMaxSteps = 4;
  114537. }
  114538. return NullEngineOptions;
  114539. }());
  114540. BABYLON.NullEngineOptions = NullEngineOptions;
  114541. /**
  114542. * The null engine class provides support for headless version of babylon.js.
  114543. * This can be used in server side scenario or for testing purposes
  114544. */
  114545. var NullEngine = /** @class */ (function (_super) {
  114546. __extends(NullEngine, _super);
  114547. function NullEngine(options) {
  114548. if (options === void 0) { options = new NullEngineOptions(); }
  114549. var _this = _super.call(this, null) || this;
  114550. if (options.deterministicLockstep === undefined) {
  114551. options.deterministicLockstep = false;
  114552. }
  114553. if (options.lockstepMaxSteps === undefined) {
  114554. options.lockstepMaxSteps = 4;
  114555. }
  114556. _this._options = options;
  114557. // Init caps
  114558. // We consider we are on a webgl1 capable device
  114559. _this._caps = new BABYLON.EngineCapabilities();
  114560. _this._caps.maxTexturesImageUnits = 16;
  114561. _this._caps.maxVertexTextureImageUnits = 16;
  114562. _this._caps.maxTextureSize = 512;
  114563. _this._caps.maxCubemapTextureSize = 512;
  114564. _this._caps.maxRenderTextureSize = 512;
  114565. _this._caps.maxVertexAttribs = 16;
  114566. _this._caps.maxVaryingVectors = 16;
  114567. _this._caps.maxFragmentUniformVectors = 16;
  114568. _this._caps.maxVertexUniformVectors = 16;
  114569. // Extensions
  114570. _this._caps.standardDerivatives = false;
  114571. _this._caps.astc = null;
  114572. _this._caps.s3tc = null;
  114573. _this._caps.pvrtc = null;
  114574. _this._caps.etc1 = null;
  114575. _this._caps.etc2 = null;
  114576. _this._caps.textureAnisotropicFilterExtension = null;
  114577. _this._caps.maxAnisotropy = 0;
  114578. _this._caps.uintIndices = false;
  114579. _this._caps.fragmentDepthSupported = false;
  114580. _this._caps.highPrecisionShaderSupported = true;
  114581. _this._caps.colorBufferFloat = false;
  114582. _this._caps.textureFloat = false;
  114583. _this._caps.textureFloatLinearFiltering = false;
  114584. _this._caps.textureFloatRender = false;
  114585. _this._caps.textureHalfFloat = false;
  114586. _this._caps.textureHalfFloatLinearFiltering = false;
  114587. _this._caps.textureHalfFloatRender = false;
  114588. _this._caps.textureLOD = false;
  114589. _this._caps.drawBuffersExtension = false;
  114590. _this._caps.depthTextureExtension = false;
  114591. _this._caps.vertexArrayObject = false;
  114592. _this._caps.instancedArrays = false;
  114593. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  114594. // Wrappers
  114595. if (typeof URL === "undefined") {
  114596. URL = {
  114597. createObjectURL: function () { },
  114598. revokeObjectURL: function () { }
  114599. };
  114600. }
  114601. if (typeof Blob === "undefined") {
  114602. Blob = function () { };
  114603. }
  114604. return _this;
  114605. }
  114606. /**
  114607. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114608. */
  114609. NullEngine.prototype.isDeterministicLockStep = function () {
  114610. return this._options.deterministicLockstep;
  114611. };
  114612. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  114613. NullEngine.prototype.getLockstepMaxSteps = function () {
  114614. return this._options.lockstepMaxSteps;
  114615. };
  114616. /**
  114617. * Sets hardware scaling, used to save performance if needed
  114618. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  114619. */
  114620. NullEngine.prototype.getHardwareScalingLevel = function () {
  114621. return 1.0;
  114622. };
  114623. NullEngine.prototype.createVertexBuffer = function (vertices) {
  114624. return {
  114625. capacity: 0,
  114626. references: 1,
  114627. is32Bits: false
  114628. };
  114629. };
  114630. NullEngine.prototype.createIndexBuffer = function (indices) {
  114631. return {
  114632. capacity: 0,
  114633. references: 1,
  114634. is32Bits: false
  114635. };
  114636. };
  114637. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  114638. if (stencil === void 0) { stencil = false; }
  114639. };
  114640. NullEngine.prototype.getRenderWidth = function (useScreen) {
  114641. if (useScreen === void 0) { useScreen = false; }
  114642. if (!useScreen && this._currentRenderTarget) {
  114643. return this._currentRenderTarget.width;
  114644. }
  114645. return this._options.renderWidth;
  114646. };
  114647. NullEngine.prototype.getRenderHeight = function (useScreen) {
  114648. if (useScreen === void 0) { useScreen = false; }
  114649. if (!useScreen && this._currentRenderTarget) {
  114650. return this._currentRenderTarget.height;
  114651. }
  114652. return this._options.renderHeight;
  114653. };
  114654. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  114655. this._cachedViewport = viewport;
  114656. };
  114657. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  114658. return {
  114659. transformFeedback: null,
  114660. __SPECTOR_rebuildProgram: null,
  114661. isParallelCompiled: false
  114662. };
  114663. };
  114664. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  114665. return [];
  114666. };
  114667. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  114668. return [];
  114669. };
  114670. NullEngine.prototype.bindSamplers = function (effect) {
  114671. this._currentEffect = null;
  114672. };
  114673. NullEngine.prototype.enableEffect = function (effect) {
  114674. this._currentEffect = effect;
  114675. if (effect.onBind) {
  114676. effect.onBind(effect);
  114677. }
  114678. if (effect._onBindObservable) {
  114679. effect._onBindObservable.notifyObservers(effect);
  114680. }
  114681. };
  114682. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  114683. if (zOffset === void 0) { zOffset = 0; }
  114684. if (reverseSide === void 0) { reverseSide = false; }
  114685. };
  114686. NullEngine.prototype.setIntArray = function (uniform, array) {
  114687. };
  114688. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  114689. };
  114690. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  114691. };
  114692. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  114693. };
  114694. NullEngine.prototype.setFloatArray = function (uniform, array) {
  114695. };
  114696. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  114697. };
  114698. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  114699. };
  114700. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  114701. };
  114702. NullEngine.prototype.setArray = function (uniform, array) {
  114703. };
  114704. NullEngine.prototype.setArray2 = function (uniform, array) {
  114705. };
  114706. NullEngine.prototype.setArray3 = function (uniform, array) {
  114707. };
  114708. NullEngine.prototype.setArray4 = function (uniform, array) {
  114709. };
  114710. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  114711. };
  114712. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  114713. };
  114714. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  114715. };
  114716. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  114717. };
  114718. NullEngine.prototype.setFloat = function (uniform, value) {
  114719. };
  114720. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  114721. };
  114722. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  114723. };
  114724. NullEngine.prototype.setBool = function (uniform, bool) {
  114725. };
  114726. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  114727. };
  114728. NullEngine.prototype.setColor3 = function (uniform, color3) {
  114729. };
  114730. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  114731. };
  114732. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  114733. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  114734. if (this._alphaMode === mode) {
  114735. return;
  114736. }
  114737. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  114738. if (!noDepthWriteChange) {
  114739. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  114740. }
  114741. this._alphaMode = mode;
  114742. };
  114743. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  114744. };
  114745. NullEngine.prototype.wipeCaches = function (bruteForce) {
  114746. if (this.preventCacheWipeBetweenFrames) {
  114747. return;
  114748. }
  114749. this.resetTextureCache();
  114750. this._currentEffect = null;
  114751. if (bruteForce) {
  114752. this._currentProgram = null;
  114753. this._stencilState.reset();
  114754. this._depthCullingState.reset();
  114755. this._alphaState.reset();
  114756. }
  114757. this._cachedVertexBuffers = null;
  114758. this._cachedIndexBuffer = null;
  114759. this._cachedEffectForVertexBuffers = null;
  114760. };
  114761. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  114762. };
  114763. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  114764. };
  114765. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  114766. };
  114767. /** @hidden */
  114768. NullEngine.prototype._createTexture = function () {
  114769. return {};
  114770. };
  114771. /** @hidden */
  114772. NullEngine.prototype._releaseTexture = function (texture) {
  114773. };
  114774. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  114775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  114776. if (onLoad === void 0) { onLoad = null; }
  114777. if (onError === void 0) { onError = null; }
  114778. if (buffer === void 0) { buffer = null; }
  114779. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  114780. var url = String(urlArg);
  114781. texture.url = url;
  114782. texture.generateMipMaps = !noMipmap;
  114783. texture.samplingMode = samplingMode;
  114784. texture.invertY = invertY;
  114785. texture.baseWidth = this._options.textureSize;
  114786. texture.baseHeight = this._options.textureSize;
  114787. texture.width = this._options.textureSize;
  114788. texture.height = this._options.textureSize;
  114789. if (format) {
  114790. texture.format = format;
  114791. }
  114792. texture.isReady = true;
  114793. if (onLoad) {
  114794. onLoad();
  114795. }
  114796. this._internalTexturesCache.push(texture);
  114797. return texture;
  114798. };
  114799. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  114800. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  114801. if (options !== undefined && typeof options === "object") {
  114802. fullOptions.generateMipMaps = options.generateMipMaps;
  114803. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  114804. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  114805. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  114806. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  114807. }
  114808. else {
  114809. fullOptions.generateMipMaps = options;
  114810. fullOptions.generateDepthBuffer = true;
  114811. fullOptions.generateStencilBuffer = false;
  114812. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  114813. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  114814. }
  114815. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  114816. var width = size.width || size;
  114817. var height = size.height || size;
  114818. texture._depthStencilBuffer = {};
  114819. texture._framebuffer = {};
  114820. texture.baseWidth = width;
  114821. texture.baseHeight = height;
  114822. texture.width = width;
  114823. texture.height = height;
  114824. texture.isReady = true;
  114825. texture.samples = 1;
  114826. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  114827. texture.samplingMode = fullOptions.samplingMode;
  114828. texture.type = fullOptions.type;
  114829. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  114830. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  114831. this._internalTexturesCache.push(texture);
  114832. return texture;
  114833. };
  114834. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  114835. texture.samplingMode = samplingMode;
  114836. };
  114837. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  114838. if (this._currentRenderTarget) {
  114839. this.unBindFramebuffer(this._currentRenderTarget);
  114840. }
  114841. this._currentRenderTarget = texture;
  114842. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  114843. if (this._cachedViewport && !forceFullscreenViewport) {
  114844. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  114845. }
  114846. };
  114847. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  114848. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  114849. this._currentRenderTarget = null;
  114850. if (onBeforeUnbind) {
  114851. if (texture._MSAAFramebuffer) {
  114852. this._currentFramebuffer = texture._framebuffer;
  114853. }
  114854. onBeforeUnbind();
  114855. }
  114856. this._currentFramebuffer = null;
  114857. };
  114858. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  114859. var vbo = {
  114860. capacity: 1,
  114861. references: 1,
  114862. is32Bits: false
  114863. };
  114864. return vbo;
  114865. };
  114866. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  114867. if (premulAlpha === void 0) { premulAlpha = false; }
  114868. };
  114869. NullEngine.prototype.areAllEffectsReady = function () {
  114870. return true;
  114871. };
  114872. /**
  114873. * @hidden
  114874. * Get the current error code of the webGL context
  114875. * @returns the error code
  114876. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  114877. */
  114878. NullEngine.prototype.getError = function () {
  114879. return 0;
  114880. };
  114881. /** @hidden */
  114882. NullEngine.prototype._getUnpackAlignement = function () {
  114883. return 1;
  114884. };
  114885. /** @hidden */
  114886. NullEngine.prototype._unpackFlipY = function (value) {
  114887. };
  114888. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  114889. if (offset === void 0) { offset = 0; }
  114890. };
  114891. /**
  114892. * Updates a dynamic vertex buffer.
  114893. * @param vertexBuffer the vertex buffer to update
  114894. * @param data the data used to update the vertex buffer
  114895. * @param byteOffset the byte offset of the data (optional)
  114896. * @param byteLength the byte length of the data (optional)
  114897. */
  114898. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  114899. };
  114900. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  114901. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  114902. this._boundTexturesCache[this._activeChannel] = texture;
  114903. return true;
  114904. }
  114905. return false;
  114906. };
  114907. /** @hidden */
  114908. NullEngine.prototype._bindTexture = function (channel, texture) {
  114909. if (channel < 0) {
  114910. return;
  114911. }
  114912. this._bindTextureDirectly(0, texture);
  114913. };
  114914. /** @hidden */
  114915. NullEngine.prototype._releaseBuffer = function (buffer) {
  114916. buffer.references--;
  114917. if (buffer.references === 0) {
  114918. return true;
  114919. }
  114920. return false;
  114921. };
  114922. NullEngine.prototype.releaseEffects = function () {
  114923. };
  114924. NullEngine.prototype.displayLoadingUI = function () {
  114925. };
  114926. NullEngine.prototype.hideLoadingUI = function () {
  114927. };
  114928. /** @hidden */
  114929. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  114930. if (faceIndex === void 0) { faceIndex = 0; }
  114931. if (lod === void 0) { lod = 0; }
  114932. };
  114933. /** @hidden */
  114934. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  114935. if (faceIndex === void 0) { faceIndex = 0; }
  114936. if (lod === void 0) { lod = 0; }
  114937. };
  114938. /** @hidden */
  114939. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  114940. if (faceIndex === void 0) { faceIndex = 0; }
  114941. if (lod === void 0) { lod = 0; }
  114942. };
  114943. /** @hidden */
  114944. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  114945. if (faceIndex === void 0) { faceIndex = 0; }
  114946. if (lod === void 0) { lod = 0; }
  114947. };
  114948. return NullEngine;
  114949. }(BABYLON.Engine));
  114950. BABYLON.NullEngine = NullEngine;
  114951. })(BABYLON || (BABYLON = {}));
  114952. //# sourceMappingURL=babylon.nullEngine.js.map
  114953. var BABYLON;
  114954. (function (BABYLON) {
  114955. /**
  114956. * This class can be used to get instrumentation data from a Babylon engine
  114957. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  114958. */
  114959. var EngineInstrumentation = /** @class */ (function () {
  114960. /**
  114961. * Instantiates a new engine instrumentation.
  114962. * This class can be used to get instrumentation data from a Babylon engine
  114963. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  114964. * @param engine Defines the engine to instrument
  114965. */
  114966. function EngineInstrumentation(
  114967. /**
  114968. * Define the instrumented engine.
  114969. */
  114970. engine) {
  114971. this.engine = engine;
  114972. this._captureGPUFrameTime = false;
  114973. this._gpuFrameTime = new BABYLON.PerfCounter();
  114974. this._captureShaderCompilationTime = false;
  114975. this._shaderCompilationTime = new BABYLON.PerfCounter();
  114976. // Observers
  114977. this._onBeginFrameObserver = null;
  114978. this._onEndFrameObserver = null;
  114979. this._onBeforeShaderCompilationObserver = null;
  114980. this._onAfterShaderCompilationObserver = null;
  114981. }
  114982. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  114983. // Properties
  114984. /**
  114985. * Gets the perf counter used for GPU frame time
  114986. */
  114987. get: function () {
  114988. return this._gpuFrameTime;
  114989. },
  114990. enumerable: true,
  114991. configurable: true
  114992. });
  114993. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  114994. /**
  114995. * Gets the GPU frame time capture status
  114996. */
  114997. get: function () {
  114998. return this._captureGPUFrameTime;
  114999. },
  115000. /**
  115001. * Enable or disable the GPU frame time capture
  115002. */
  115003. set: function (value) {
  115004. var _this = this;
  115005. if (value === this._captureGPUFrameTime) {
  115006. return;
  115007. }
  115008. this._captureGPUFrameTime = value;
  115009. if (value) {
  115010. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  115011. if (!_this._gpuFrameTimeToken) {
  115012. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  115013. }
  115014. });
  115015. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  115016. if (!_this._gpuFrameTimeToken) {
  115017. return;
  115018. }
  115019. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  115020. if (time > -1) {
  115021. _this._gpuFrameTimeToken = null;
  115022. _this._gpuFrameTime.fetchNewFrame();
  115023. _this._gpuFrameTime.addCount(time, true);
  115024. }
  115025. });
  115026. }
  115027. else {
  115028. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115029. this._onBeginFrameObserver = null;
  115030. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115031. this._onEndFrameObserver = null;
  115032. }
  115033. },
  115034. enumerable: true,
  115035. configurable: true
  115036. });
  115037. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  115038. /**
  115039. * Gets the perf counter used for shader compilation time
  115040. */
  115041. get: function () {
  115042. return this._shaderCompilationTime;
  115043. },
  115044. enumerable: true,
  115045. configurable: true
  115046. });
  115047. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  115048. /**
  115049. * Gets the shader compilation time capture status
  115050. */
  115051. get: function () {
  115052. return this._captureShaderCompilationTime;
  115053. },
  115054. /**
  115055. * Enable or disable the shader compilation time capture
  115056. */
  115057. set: function (value) {
  115058. var _this = this;
  115059. if (value === this._captureShaderCompilationTime) {
  115060. return;
  115061. }
  115062. this._captureShaderCompilationTime = value;
  115063. if (value) {
  115064. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  115065. _this._shaderCompilationTime.fetchNewFrame();
  115066. _this._shaderCompilationTime.beginMonitoring();
  115067. });
  115068. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  115069. _this._shaderCompilationTime.endMonitoring();
  115070. });
  115071. }
  115072. else {
  115073. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115074. this._onBeforeShaderCompilationObserver = null;
  115075. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115076. this._onAfterShaderCompilationObserver = null;
  115077. }
  115078. },
  115079. enumerable: true,
  115080. configurable: true
  115081. });
  115082. /**
  115083. * Dispose and release associated resources.
  115084. */
  115085. EngineInstrumentation.prototype.dispose = function () {
  115086. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115087. this._onBeginFrameObserver = null;
  115088. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115089. this._onEndFrameObserver = null;
  115090. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115091. this._onBeforeShaderCompilationObserver = null;
  115092. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115093. this._onAfterShaderCompilationObserver = null;
  115094. this.engine = null;
  115095. };
  115096. return EngineInstrumentation;
  115097. }());
  115098. BABYLON.EngineInstrumentation = EngineInstrumentation;
  115099. })(BABYLON || (BABYLON = {}));
  115100. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  115101. var BABYLON;
  115102. (function (BABYLON) {
  115103. /**
  115104. * This class can be used to get instrumentation data from a Babylon engine
  115105. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115106. */
  115107. var SceneInstrumentation = /** @class */ (function () {
  115108. /**
  115109. * Instantiates a new scene instrumentation.
  115110. * This class can be used to get instrumentation data from a Babylon engine
  115111. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115112. * @param scene Defines the scene to instrument
  115113. */
  115114. function SceneInstrumentation(
  115115. /**
  115116. * Defines the scene to instrument
  115117. */
  115118. scene) {
  115119. var _this = this;
  115120. this.scene = scene;
  115121. this._captureActiveMeshesEvaluationTime = false;
  115122. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  115123. this._captureRenderTargetsRenderTime = false;
  115124. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  115125. this._captureFrameTime = false;
  115126. this._frameTime = new BABYLON.PerfCounter();
  115127. this._captureRenderTime = false;
  115128. this._renderTime = new BABYLON.PerfCounter();
  115129. this._captureInterFrameTime = false;
  115130. this._interFrameTime = new BABYLON.PerfCounter();
  115131. this._captureParticlesRenderTime = false;
  115132. this._particlesRenderTime = new BABYLON.PerfCounter();
  115133. this._captureSpritesRenderTime = false;
  115134. this._spritesRenderTime = new BABYLON.PerfCounter();
  115135. this._capturePhysicsTime = false;
  115136. this._physicsTime = new BABYLON.PerfCounter();
  115137. this._captureAnimationsTime = false;
  115138. this._animationsTime = new BABYLON.PerfCounter();
  115139. this._captureCameraRenderTime = false;
  115140. this._cameraRenderTime = new BABYLON.PerfCounter();
  115141. // Observers
  115142. this._onBeforeActiveMeshesEvaluationObserver = null;
  115143. this._onAfterActiveMeshesEvaluationObserver = null;
  115144. this._onBeforeRenderTargetsRenderObserver = null;
  115145. this._onAfterRenderTargetsRenderObserver = null;
  115146. this._onAfterRenderObserver = null;
  115147. this._onBeforeDrawPhaseObserver = null;
  115148. this._onAfterDrawPhaseObserver = null;
  115149. this._onBeforeAnimationsObserver = null;
  115150. this._onBeforeParticlesRenderingObserver = null;
  115151. this._onAfterParticlesRenderingObserver = null;
  115152. this._onBeforeSpritesRenderingObserver = null;
  115153. this._onAfterSpritesRenderingObserver = null;
  115154. this._onBeforePhysicsObserver = null;
  115155. this._onAfterPhysicsObserver = null;
  115156. this._onAfterAnimationsObserver = null;
  115157. this._onBeforeCameraRenderObserver = null;
  115158. this._onAfterCameraRenderObserver = null;
  115159. // Before render
  115160. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  115161. if (_this._captureActiveMeshesEvaluationTime) {
  115162. _this._activeMeshesEvaluationTime.fetchNewFrame();
  115163. }
  115164. if (_this._captureRenderTargetsRenderTime) {
  115165. _this._renderTargetsRenderTime.fetchNewFrame();
  115166. }
  115167. if (_this._captureFrameTime) {
  115168. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  115169. _this._frameTime.beginMonitoring();
  115170. }
  115171. if (_this._captureInterFrameTime) {
  115172. _this._interFrameTime.endMonitoring();
  115173. }
  115174. if (_this._captureParticlesRenderTime) {
  115175. _this._particlesRenderTime.fetchNewFrame();
  115176. }
  115177. if (_this._captureSpritesRenderTime) {
  115178. _this._spritesRenderTime.fetchNewFrame();
  115179. }
  115180. if (_this._captureAnimationsTime) {
  115181. _this._animationsTime.beginMonitoring();
  115182. }
  115183. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  115184. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  115185. });
  115186. // After render
  115187. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  115188. if (_this._captureFrameTime) {
  115189. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  115190. _this._frameTime.endMonitoring();
  115191. }
  115192. if (_this._captureRenderTime) {
  115193. _this._renderTime.endMonitoring(false);
  115194. }
  115195. if (_this._captureInterFrameTime) {
  115196. _this._interFrameTime.beginMonitoring();
  115197. }
  115198. });
  115199. }
  115200. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  115201. // Properties
  115202. /**
  115203. * Gets the perf counter used for active meshes evaluation time
  115204. */
  115205. get: function () {
  115206. return this._activeMeshesEvaluationTime;
  115207. },
  115208. enumerable: true,
  115209. configurable: true
  115210. });
  115211. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  115212. /**
  115213. * Gets the active meshes evaluation time capture status
  115214. */
  115215. get: function () {
  115216. return this._captureActiveMeshesEvaluationTime;
  115217. },
  115218. /**
  115219. * Enable or disable the active meshes evaluation time capture
  115220. */
  115221. set: function (value) {
  115222. var _this = this;
  115223. if (value === this._captureActiveMeshesEvaluationTime) {
  115224. return;
  115225. }
  115226. this._captureActiveMeshesEvaluationTime = value;
  115227. if (value) {
  115228. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  115229. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  115230. _this._activeMeshesEvaluationTime.beginMonitoring();
  115231. });
  115232. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  115233. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  115234. _this._activeMeshesEvaluationTime.endMonitoring();
  115235. });
  115236. }
  115237. else {
  115238. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115239. this._onBeforeActiveMeshesEvaluationObserver = null;
  115240. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115241. this._onAfterActiveMeshesEvaluationObserver = null;
  115242. }
  115243. },
  115244. enumerable: true,
  115245. configurable: true
  115246. });
  115247. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  115248. /**
  115249. * Gets the perf counter used for render targets render time
  115250. */
  115251. get: function () {
  115252. return this._renderTargetsRenderTime;
  115253. },
  115254. enumerable: true,
  115255. configurable: true
  115256. });
  115257. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  115258. /**
  115259. * Gets the render targets render time capture status
  115260. */
  115261. get: function () {
  115262. return this._captureRenderTargetsRenderTime;
  115263. },
  115264. /**
  115265. * Enable or disable the render targets render time capture
  115266. */
  115267. set: function (value) {
  115268. var _this = this;
  115269. if (value === this._captureRenderTargetsRenderTime) {
  115270. return;
  115271. }
  115272. this._captureRenderTargetsRenderTime = value;
  115273. if (value) {
  115274. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  115275. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  115276. _this._renderTargetsRenderTime.beginMonitoring();
  115277. });
  115278. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  115279. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  115280. _this._renderTargetsRenderTime.endMonitoring(false);
  115281. });
  115282. }
  115283. else {
  115284. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115285. this._onBeforeRenderTargetsRenderObserver = null;
  115286. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115287. this._onAfterRenderTargetsRenderObserver = null;
  115288. }
  115289. },
  115290. enumerable: true,
  115291. configurable: true
  115292. });
  115293. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  115294. /**
  115295. * Gets the perf counter used for particles render time
  115296. */
  115297. get: function () {
  115298. return this._particlesRenderTime;
  115299. },
  115300. enumerable: true,
  115301. configurable: true
  115302. });
  115303. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  115304. /**
  115305. * Gets the particles render time capture status
  115306. */
  115307. get: function () {
  115308. return this._captureParticlesRenderTime;
  115309. },
  115310. /**
  115311. * Enable or disable the particles render time capture
  115312. */
  115313. set: function (value) {
  115314. var _this = this;
  115315. if (value === this._captureParticlesRenderTime) {
  115316. return;
  115317. }
  115318. this._captureParticlesRenderTime = value;
  115319. if (value) {
  115320. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  115321. BABYLON.Tools.StartPerformanceCounter("Particles");
  115322. _this._particlesRenderTime.beginMonitoring();
  115323. });
  115324. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  115325. BABYLON.Tools.EndPerformanceCounter("Particles");
  115326. _this._particlesRenderTime.endMonitoring(false);
  115327. });
  115328. }
  115329. else {
  115330. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115331. this._onBeforeParticlesRenderingObserver = null;
  115332. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115333. this._onAfterParticlesRenderingObserver = null;
  115334. }
  115335. },
  115336. enumerable: true,
  115337. configurable: true
  115338. });
  115339. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  115340. /**
  115341. * Gets the perf counter used for sprites render time
  115342. */
  115343. get: function () {
  115344. return this._spritesRenderTime;
  115345. },
  115346. enumerable: true,
  115347. configurable: true
  115348. });
  115349. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  115350. /**
  115351. * Gets the sprites render time capture status
  115352. */
  115353. get: function () {
  115354. return this._captureSpritesRenderTime;
  115355. },
  115356. /**
  115357. * Enable or disable the sprites render time capture
  115358. */
  115359. set: function (value) {
  115360. var _this = this;
  115361. if (value === this._captureSpritesRenderTime) {
  115362. return;
  115363. }
  115364. this._captureSpritesRenderTime = value;
  115365. if (!this.scene.spriteManagers) {
  115366. return;
  115367. }
  115368. if (value) {
  115369. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  115370. BABYLON.Tools.StartPerformanceCounter("Sprites");
  115371. _this._spritesRenderTime.beginMonitoring();
  115372. });
  115373. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  115374. BABYLON.Tools.EndPerformanceCounter("Sprites");
  115375. _this._spritesRenderTime.endMonitoring(false);
  115376. });
  115377. }
  115378. else {
  115379. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  115380. this._onBeforeSpritesRenderingObserver = null;
  115381. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  115382. this._onAfterSpritesRenderingObserver = null;
  115383. }
  115384. },
  115385. enumerable: true,
  115386. configurable: true
  115387. });
  115388. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  115389. /**
  115390. * Gets the perf counter used for physics time
  115391. */
  115392. get: function () {
  115393. return this._physicsTime;
  115394. },
  115395. enumerable: true,
  115396. configurable: true
  115397. });
  115398. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  115399. /**
  115400. * Gets the physics time capture status
  115401. */
  115402. get: function () {
  115403. return this._capturePhysicsTime;
  115404. },
  115405. /**
  115406. * Enable or disable the physics time capture
  115407. */
  115408. set: function (value) {
  115409. var _this = this;
  115410. if (value === this._capturePhysicsTime) {
  115411. return;
  115412. }
  115413. if (!this.scene.onBeforePhysicsObservable) {
  115414. return;
  115415. }
  115416. this._capturePhysicsTime = value;
  115417. if (value) {
  115418. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  115419. BABYLON.Tools.StartPerformanceCounter("Physics");
  115420. _this._physicsTime.beginMonitoring();
  115421. });
  115422. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  115423. BABYLON.Tools.EndPerformanceCounter("Physics");
  115424. _this._physicsTime.endMonitoring();
  115425. });
  115426. }
  115427. else {
  115428. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  115429. this._onBeforePhysicsObserver = null;
  115430. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  115431. this._onAfterPhysicsObserver = null;
  115432. }
  115433. },
  115434. enumerable: true,
  115435. configurable: true
  115436. });
  115437. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  115438. /**
  115439. * Gets the perf counter used for animations time
  115440. */
  115441. get: function () {
  115442. return this._animationsTime;
  115443. },
  115444. enumerable: true,
  115445. configurable: true
  115446. });
  115447. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  115448. /**
  115449. * Gets the animations time capture status
  115450. */
  115451. get: function () {
  115452. return this._captureAnimationsTime;
  115453. },
  115454. /**
  115455. * Enable or disable the animations time capture
  115456. */
  115457. set: function (value) {
  115458. var _this = this;
  115459. if (value === this._captureAnimationsTime) {
  115460. return;
  115461. }
  115462. this._captureAnimationsTime = value;
  115463. if (value) {
  115464. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  115465. _this._animationsTime.endMonitoring();
  115466. });
  115467. }
  115468. else {
  115469. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  115470. this._onAfterAnimationsObserver = null;
  115471. }
  115472. },
  115473. enumerable: true,
  115474. configurable: true
  115475. });
  115476. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  115477. /**
  115478. * Gets the perf counter used for frame time capture
  115479. */
  115480. get: function () {
  115481. return this._frameTime;
  115482. },
  115483. enumerable: true,
  115484. configurable: true
  115485. });
  115486. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  115487. /**
  115488. * Gets the frame time capture status
  115489. */
  115490. get: function () {
  115491. return this._captureFrameTime;
  115492. },
  115493. /**
  115494. * Enable or disable the frame time capture
  115495. */
  115496. set: function (value) {
  115497. this._captureFrameTime = value;
  115498. },
  115499. enumerable: true,
  115500. configurable: true
  115501. });
  115502. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  115503. /**
  115504. * Gets the perf counter used for inter-frames time capture
  115505. */
  115506. get: function () {
  115507. return this._interFrameTime;
  115508. },
  115509. enumerable: true,
  115510. configurable: true
  115511. });
  115512. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  115513. /**
  115514. * Gets the inter-frames time capture status
  115515. */
  115516. get: function () {
  115517. return this._captureInterFrameTime;
  115518. },
  115519. /**
  115520. * Enable or disable the inter-frames time capture
  115521. */
  115522. set: function (value) {
  115523. this._captureInterFrameTime = value;
  115524. },
  115525. enumerable: true,
  115526. configurable: true
  115527. });
  115528. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  115529. /**
  115530. * Gets the perf counter used for render time capture
  115531. */
  115532. get: function () {
  115533. return this._renderTime;
  115534. },
  115535. enumerable: true,
  115536. configurable: true
  115537. });
  115538. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  115539. /**
  115540. * Gets the render time capture status
  115541. */
  115542. get: function () {
  115543. return this._captureRenderTime;
  115544. },
  115545. /**
  115546. * Enable or disable the render time capture
  115547. */
  115548. set: function (value) {
  115549. var _this = this;
  115550. if (value === this._captureRenderTime) {
  115551. return;
  115552. }
  115553. this._captureRenderTime = value;
  115554. if (value) {
  115555. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  115556. _this._renderTime.beginMonitoring();
  115557. BABYLON.Tools.StartPerformanceCounter("Main render");
  115558. });
  115559. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  115560. _this._renderTime.endMonitoring(false);
  115561. BABYLON.Tools.EndPerformanceCounter("Main render");
  115562. });
  115563. }
  115564. else {
  115565. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  115566. this._onBeforeDrawPhaseObserver = null;
  115567. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  115568. this._onAfterDrawPhaseObserver = null;
  115569. }
  115570. },
  115571. enumerable: true,
  115572. configurable: true
  115573. });
  115574. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  115575. /**
  115576. * Gets the perf counter used for camera render time capture
  115577. */
  115578. get: function () {
  115579. return this._cameraRenderTime;
  115580. },
  115581. enumerable: true,
  115582. configurable: true
  115583. });
  115584. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  115585. /**
  115586. * Gets the camera render time capture status
  115587. */
  115588. get: function () {
  115589. return this._captureCameraRenderTime;
  115590. },
  115591. /**
  115592. * Enable or disable the camera render time capture
  115593. */
  115594. set: function (value) {
  115595. var _this = this;
  115596. if (value === this._captureCameraRenderTime) {
  115597. return;
  115598. }
  115599. this._captureCameraRenderTime = value;
  115600. if (value) {
  115601. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  115602. _this._cameraRenderTime.beginMonitoring();
  115603. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  115604. });
  115605. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  115606. _this._cameraRenderTime.endMonitoring(false);
  115607. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  115608. });
  115609. }
  115610. else {
  115611. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  115612. this._onBeforeCameraRenderObserver = null;
  115613. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  115614. this._onAfterCameraRenderObserver = null;
  115615. }
  115616. },
  115617. enumerable: true,
  115618. configurable: true
  115619. });
  115620. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  115621. /**
  115622. * Gets the perf counter used for draw calls
  115623. */
  115624. get: function () {
  115625. return this.scene.getEngine()._drawCalls;
  115626. },
  115627. enumerable: true,
  115628. configurable: true
  115629. });
  115630. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  115631. /**
  115632. * Gets the perf counter used for texture collisions
  115633. */
  115634. get: function () {
  115635. return this.scene.getEngine()._textureCollisions;
  115636. },
  115637. enumerable: true,
  115638. configurable: true
  115639. });
  115640. /**
  115641. * Dispose and release associated resources.
  115642. */
  115643. SceneInstrumentation.prototype.dispose = function () {
  115644. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  115645. this._onAfterRenderObserver = null;
  115646. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115647. this._onBeforeActiveMeshesEvaluationObserver = null;
  115648. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115649. this._onAfterActiveMeshesEvaluationObserver = null;
  115650. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115651. this._onBeforeRenderTargetsRenderObserver = null;
  115652. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115653. this._onAfterRenderTargetsRenderObserver = null;
  115654. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  115655. this._onBeforeAnimationsObserver = null;
  115656. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115657. this._onBeforeParticlesRenderingObserver = null;
  115658. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115659. this._onAfterParticlesRenderingObserver = null;
  115660. if (this._onBeforeSpritesRenderingObserver) {
  115661. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  115662. this._onBeforeSpritesRenderingObserver = null;
  115663. }
  115664. if (this._onAfterSpritesRenderingObserver) {
  115665. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  115666. this._onAfterSpritesRenderingObserver = null;
  115667. }
  115668. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  115669. this._onBeforeDrawPhaseObserver = null;
  115670. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  115671. this._onAfterDrawPhaseObserver = null;
  115672. if (this._onBeforePhysicsObserver) {
  115673. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  115674. this._onBeforePhysicsObserver = null;
  115675. }
  115676. if (this._onAfterPhysicsObserver) {
  115677. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  115678. this._onAfterPhysicsObserver = null;
  115679. }
  115680. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  115681. this._onAfterAnimationsObserver = null;
  115682. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  115683. this._onBeforeCameraRenderObserver = null;
  115684. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  115685. this._onAfterCameraRenderObserver = null;
  115686. this.scene = null;
  115687. };
  115688. return SceneInstrumentation;
  115689. }());
  115690. BABYLON.SceneInstrumentation = SceneInstrumentation;
  115691. })(BABYLON || (BABYLON = {}));
  115692. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  115693. var BABYLON;
  115694. (function (BABYLON) {
  115695. /**
  115696. * @hidden
  115697. **/
  115698. var _TimeToken = /** @class */ (function () {
  115699. function _TimeToken() {
  115700. this._timeElapsedQueryEnded = false;
  115701. }
  115702. return _TimeToken;
  115703. }());
  115704. BABYLON._TimeToken = _TimeToken;
  115705. })(BABYLON || (BABYLON = {}));
  115706. //# sourceMappingURL=babylon.timeToken.js.map
  115707. var BABYLON;
  115708. (function (BABYLON) {
  115709. /**
  115710. * Background material defines definition.
  115711. * @hidden Mainly internal Use
  115712. */
  115713. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  115714. __extends(BackgroundMaterialDefines, _super);
  115715. /**
  115716. * Constructor of the defines.
  115717. */
  115718. function BackgroundMaterialDefines() {
  115719. var _this = _super.call(this) || this;
  115720. /**
  115721. * True if the diffuse texture is in use.
  115722. */
  115723. _this.DIFFUSE = false;
  115724. /**
  115725. * The direct UV channel to use.
  115726. */
  115727. _this.DIFFUSEDIRECTUV = 0;
  115728. /**
  115729. * True if the diffuse texture is in gamma space.
  115730. */
  115731. _this.GAMMADIFFUSE = false;
  115732. /**
  115733. * True if the diffuse texture has opacity in the alpha channel.
  115734. */
  115735. _this.DIFFUSEHASALPHA = false;
  115736. /**
  115737. * True if you want the material to fade to transparent at grazing angle.
  115738. */
  115739. _this.OPACITYFRESNEL = false;
  115740. /**
  115741. * True if an extra blur needs to be added in the reflection.
  115742. */
  115743. _this.REFLECTIONBLUR = false;
  115744. /**
  115745. * True if you want the material to fade to reflection at grazing angle.
  115746. */
  115747. _this.REFLECTIONFRESNEL = false;
  115748. /**
  115749. * True if you want the material to falloff as far as you move away from the scene center.
  115750. */
  115751. _this.REFLECTIONFALLOFF = false;
  115752. /**
  115753. * False if the current Webgl implementation does not support the texture lod extension.
  115754. */
  115755. _this.TEXTURELODSUPPORT = false;
  115756. /**
  115757. * True to ensure the data are premultiplied.
  115758. */
  115759. _this.PREMULTIPLYALPHA = false;
  115760. /**
  115761. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  115762. */
  115763. _this.USERGBCOLOR = false;
  115764. /**
  115765. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  115766. * stays aligned with the desired configuration.
  115767. */
  115768. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  115769. /**
  115770. * True to add noise in order to reduce the banding effect.
  115771. */
  115772. _this.NOISE = false;
  115773. /**
  115774. * is the reflection texture in BGR color scheme?
  115775. * Mainly used to solve a bug in ios10 video tag
  115776. */
  115777. _this.REFLECTIONBGR = false;
  115778. _this.IMAGEPROCESSING = false;
  115779. _this.VIGNETTE = false;
  115780. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  115781. _this.VIGNETTEBLENDMODEOPAQUE = false;
  115782. _this.TONEMAPPING = false;
  115783. _this.TONEMAPPING_ACES = false;
  115784. _this.CONTRAST = false;
  115785. _this.COLORCURVES = false;
  115786. _this.COLORGRADING = false;
  115787. _this.COLORGRADING3D = false;
  115788. _this.SAMPLER3DGREENDEPTH = false;
  115789. _this.SAMPLER3DBGRMAP = false;
  115790. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  115791. _this.EXPOSURE = false;
  115792. // Reflection.
  115793. _this.REFLECTION = false;
  115794. _this.REFLECTIONMAP_3D = false;
  115795. _this.REFLECTIONMAP_SPHERICAL = false;
  115796. _this.REFLECTIONMAP_PLANAR = false;
  115797. _this.REFLECTIONMAP_CUBIC = false;
  115798. _this.REFLECTIONMAP_PROJECTION = false;
  115799. _this.REFLECTIONMAP_SKYBOX = false;
  115800. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  115801. _this.REFLECTIONMAP_EXPLICIT = false;
  115802. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  115803. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  115804. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  115805. _this.INVERTCUBICMAP = false;
  115806. _this.REFLECTIONMAP_OPPOSITEZ = false;
  115807. _this.LODINREFLECTIONALPHA = false;
  115808. _this.GAMMAREFLECTION = false;
  115809. _this.RGBDREFLECTION = false;
  115810. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  115811. // Default BJS.
  115812. _this.MAINUV1 = false;
  115813. _this.MAINUV2 = false;
  115814. _this.UV1 = false;
  115815. _this.UV2 = false;
  115816. _this.CLIPPLANE = false;
  115817. _this.CLIPPLANE2 = false;
  115818. _this.CLIPPLANE3 = false;
  115819. _this.CLIPPLANE4 = false;
  115820. _this.POINTSIZE = false;
  115821. _this.FOG = false;
  115822. _this.NORMAL = false;
  115823. _this.NUM_BONE_INFLUENCERS = 0;
  115824. _this.BonesPerMesh = 0;
  115825. _this.INSTANCES = false;
  115826. _this.SHADOWFLOAT = false;
  115827. _this.rebuild();
  115828. return _this;
  115829. }
  115830. return BackgroundMaterialDefines;
  115831. }(BABYLON.MaterialDefines));
  115832. /**
  115833. * Background material used to create an efficient environement around your scene.
  115834. */
  115835. var BackgroundMaterial = /** @class */ (function (_super) {
  115836. __extends(BackgroundMaterial, _super);
  115837. /**
  115838. * Instantiates a Background Material in the given scene
  115839. * @param name The friendly name of the material
  115840. * @param scene The scene to add the material to
  115841. */
  115842. function BackgroundMaterial(name, scene) {
  115843. var _this = _super.call(this, name, scene) || this;
  115844. /**
  115845. * Key light Color (multiply against the environement texture)
  115846. */
  115847. _this.primaryColor = BABYLON.Color3.White();
  115848. _this._primaryColorShadowLevel = 0;
  115849. _this._primaryColorHighlightLevel = 0;
  115850. /**
  115851. * Reflection Texture used in the material.
  115852. * Should be author in a specific way for the best result (refer to the documentation).
  115853. */
  115854. _this.reflectionTexture = null;
  115855. /**
  115856. * Reflection Texture level of blur.
  115857. *
  115858. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  115859. * texture twice.
  115860. */
  115861. _this.reflectionBlur = 0;
  115862. /**
  115863. * Diffuse Texture used in the material.
  115864. * Should be author in a specific way for the best result (refer to the documentation).
  115865. */
  115866. _this.diffuseTexture = null;
  115867. _this._shadowLights = null;
  115868. /**
  115869. * Specify the list of lights casting shadow on the material.
  115870. * All scene shadow lights will be included if null.
  115871. */
  115872. _this.shadowLights = null;
  115873. /**
  115874. * Helps adjusting the shadow to a softer level if required.
  115875. * 0 means black shadows and 1 means no shadows.
  115876. */
  115877. _this.shadowLevel = 0;
  115878. /**
  115879. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  115880. * It is usually zero but might be interesting to modify according to your setup.
  115881. */
  115882. _this.sceneCenter = BABYLON.Vector3.Zero();
  115883. /**
  115884. * This helps specifying that the material is falling off to the sky box at grazing angle.
  115885. * This helps ensuring a nice transition when the camera goes under the ground.
  115886. */
  115887. _this.opacityFresnel = true;
  115888. /**
  115889. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  115890. * This helps adding a mirror texture on the ground.
  115891. */
  115892. _this.reflectionFresnel = false;
  115893. /**
  115894. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  115895. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  115896. */
  115897. _this.reflectionFalloffDistance = 0.0;
  115898. /**
  115899. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  115900. */
  115901. _this.reflectionAmount = 1.0;
  115902. /**
  115903. * This specifies the weight of the reflection at grazing angle.
  115904. */
  115905. _this.reflectionReflectance0 = 0.05;
  115906. /**
  115907. * This specifies the weight of the reflection at a perpendicular point of view.
  115908. */
  115909. _this.reflectionReflectance90 = 0.5;
  115910. /**
  115911. * Helps to directly use the maps channels instead of their level.
  115912. */
  115913. _this.useRGBColor = true;
  115914. /**
  115915. * This helps reducing the banding effect that could occur on the background.
  115916. */
  115917. _this.enableNoise = false;
  115918. _this._fovMultiplier = 1.0;
  115919. /**
  115920. * Enable the FOV adjustment feature controlled by fovMultiplier.
  115921. */
  115922. _this.useEquirectangularFOV = false;
  115923. _this._maxSimultaneousLights = 4;
  115924. /**
  115925. * Number of Simultaneous lights allowed on the material.
  115926. */
  115927. _this.maxSimultaneousLights = 4;
  115928. /**
  115929. * Keep track of the image processing observer to allow dispose and replace.
  115930. */
  115931. _this._imageProcessingObserver = null;
  115932. /**
  115933. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  115934. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  115935. */
  115936. _this.switchToBGR = false;
  115937. // Temp values kept as cache in the material.
  115938. _this._renderTargets = new BABYLON.SmartArray(16);
  115939. _this._reflectionControls = BABYLON.Vector4.Zero();
  115940. _this._white = BABYLON.Color3.White();
  115941. _this._primaryShadowColor = BABYLON.Color3.Black();
  115942. _this._primaryHighlightColor = BABYLON.Color3.Black();
  115943. // Setup the default processing configuration to the scene.
  115944. _this._attachImageProcessingConfiguration(null);
  115945. _this.getRenderTargetTextures = function () {
  115946. _this._renderTargets.reset();
  115947. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  115948. _this._renderTargets.push(_this._diffuseTexture);
  115949. }
  115950. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  115951. _this._renderTargets.push(_this._reflectionTexture);
  115952. }
  115953. return _this._renderTargets;
  115954. };
  115955. return _this;
  115956. }
  115957. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  115958. /**
  115959. * Experimental Internal Use Only.
  115960. *
  115961. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  115962. * This acts as a helper to set the primary color to a more "human friendly" value.
  115963. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  115964. * output color as close as possible from the chosen value.
  115965. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  115966. * part of lighting setup.)
  115967. */
  115968. get: function () {
  115969. return this.__perceptualColor;
  115970. },
  115971. set: function (value) {
  115972. this.__perceptualColor = value;
  115973. this._computePrimaryColorFromPerceptualColor();
  115974. this._markAllSubMeshesAsLightsDirty();
  115975. },
  115976. enumerable: true,
  115977. configurable: true
  115978. });
  115979. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  115980. /**
  115981. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  115982. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  115983. */
  115984. get: function () {
  115985. return this._primaryColorShadowLevel;
  115986. },
  115987. set: function (value) {
  115988. this._primaryColorShadowLevel = value;
  115989. this._computePrimaryColors();
  115990. this._markAllSubMeshesAsLightsDirty();
  115991. },
  115992. enumerable: true,
  115993. configurable: true
  115994. });
  115995. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  115996. /**
  115997. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  115998. * The primary color is used at the level chosen to define what the white area would look.
  115999. */
  116000. get: function () {
  116001. return this._primaryColorHighlightLevel;
  116002. },
  116003. set: function (value) {
  116004. this._primaryColorHighlightLevel = value;
  116005. this._computePrimaryColors();
  116006. this._markAllSubMeshesAsLightsDirty();
  116007. },
  116008. enumerable: true,
  116009. configurable: true
  116010. });
  116011. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  116012. /**
  116013. * Sets the reflection reflectance fresnel values according to the default standard
  116014. * empirically know to work well :-)
  116015. */
  116016. set: function (value) {
  116017. var reflectionWeight = value;
  116018. if (reflectionWeight < 0.5) {
  116019. reflectionWeight = reflectionWeight * 2.0;
  116020. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  116021. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  116022. }
  116023. else {
  116024. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  116025. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  116026. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  116027. }
  116028. },
  116029. enumerable: true,
  116030. configurable: true
  116031. });
  116032. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  116033. /**
  116034. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116035. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  116036. * Recommended to be keep at 1.0 except for special cases.
  116037. */
  116038. get: function () {
  116039. return this._fovMultiplier;
  116040. },
  116041. set: function (value) {
  116042. if (isNaN(value)) {
  116043. value = 1.0;
  116044. }
  116045. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  116046. },
  116047. enumerable: true,
  116048. configurable: true
  116049. });
  116050. /**
  116051. * Attaches a new image processing configuration to the PBR Material.
  116052. * @param configuration (if null the scene configuration will be use)
  116053. */
  116054. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  116055. var _this = this;
  116056. if (configuration === this._imageProcessingConfiguration) {
  116057. return;
  116058. }
  116059. // Detaches observer.
  116060. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116061. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116062. }
  116063. // Pick the scene configuration if needed.
  116064. if (!configuration) {
  116065. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  116066. }
  116067. else {
  116068. this._imageProcessingConfiguration = configuration;
  116069. }
  116070. // Attaches observer.
  116071. if (this._imageProcessingConfiguration) {
  116072. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  116073. _this._computePrimaryColorFromPerceptualColor();
  116074. _this._markAllSubMeshesAsImageProcessingDirty();
  116075. });
  116076. }
  116077. };
  116078. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  116079. /**
  116080. * Gets the image processing configuration used either in this material.
  116081. */
  116082. get: function () {
  116083. return this._imageProcessingConfiguration;
  116084. },
  116085. /**
  116086. * Sets the Default image processing configuration used either in the this material.
  116087. *
  116088. * If sets to null, the scene one is in use.
  116089. */
  116090. set: function (value) {
  116091. this._attachImageProcessingConfiguration(value);
  116092. // Ensure the effect will be rebuilt.
  116093. this._markAllSubMeshesAsTexturesDirty();
  116094. },
  116095. enumerable: true,
  116096. configurable: true
  116097. });
  116098. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  116099. /**
  116100. * Gets wether the color curves effect is enabled.
  116101. */
  116102. get: function () {
  116103. return this.imageProcessingConfiguration.colorCurvesEnabled;
  116104. },
  116105. /**
  116106. * Sets wether the color curves effect is enabled.
  116107. */
  116108. set: function (value) {
  116109. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  116110. },
  116111. enumerable: true,
  116112. configurable: true
  116113. });
  116114. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  116115. /**
  116116. * Gets wether the color grading effect is enabled.
  116117. */
  116118. get: function () {
  116119. return this.imageProcessingConfiguration.colorGradingEnabled;
  116120. },
  116121. /**
  116122. * Gets wether the color grading effect is enabled.
  116123. */
  116124. set: function (value) {
  116125. this.imageProcessingConfiguration.colorGradingEnabled = value;
  116126. },
  116127. enumerable: true,
  116128. configurable: true
  116129. });
  116130. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  116131. /**
  116132. * Gets wether tonemapping is enabled or not.
  116133. */
  116134. get: function () {
  116135. return this._imageProcessingConfiguration.toneMappingEnabled;
  116136. },
  116137. /**
  116138. * Sets wether tonemapping is enabled or not
  116139. */
  116140. set: function (value) {
  116141. this._imageProcessingConfiguration.toneMappingEnabled = value;
  116142. },
  116143. enumerable: true,
  116144. configurable: true
  116145. });
  116146. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  116147. /**
  116148. * The camera exposure used on this material.
  116149. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116150. * This corresponds to a photographic exposure.
  116151. */
  116152. get: function () {
  116153. return this._imageProcessingConfiguration.exposure;
  116154. },
  116155. /**
  116156. * The camera exposure used on this material.
  116157. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116158. * This corresponds to a photographic exposure.
  116159. */
  116160. set: function (value) {
  116161. this._imageProcessingConfiguration.exposure = value;
  116162. },
  116163. enumerable: true,
  116164. configurable: true
  116165. });
  116166. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  116167. /**
  116168. * Gets The camera contrast used on this material.
  116169. */
  116170. get: function () {
  116171. return this._imageProcessingConfiguration.contrast;
  116172. },
  116173. /**
  116174. * Sets The camera contrast used on this material.
  116175. */
  116176. set: function (value) {
  116177. this._imageProcessingConfiguration.contrast = value;
  116178. },
  116179. enumerable: true,
  116180. configurable: true
  116181. });
  116182. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  116183. /**
  116184. * Gets the Color Grading 2D Lookup Texture.
  116185. */
  116186. get: function () {
  116187. return this._imageProcessingConfiguration.colorGradingTexture;
  116188. },
  116189. /**
  116190. * Sets the Color Grading 2D Lookup Texture.
  116191. */
  116192. set: function (value) {
  116193. this.imageProcessingConfiguration.colorGradingTexture = value;
  116194. },
  116195. enumerable: true,
  116196. configurable: true
  116197. });
  116198. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  116199. /**
  116200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116202. * 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;
  116203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116204. */
  116205. get: function () {
  116206. return this.imageProcessingConfiguration.colorCurves;
  116207. },
  116208. /**
  116209. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116210. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116211. * 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;
  116212. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116213. */
  116214. set: function (value) {
  116215. this.imageProcessingConfiguration.colorCurves = value;
  116216. },
  116217. enumerable: true,
  116218. configurable: true
  116219. });
  116220. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  116221. /**
  116222. * Gets a boolean indicating that current material needs to register RTT
  116223. */
  116224. get: function () {
  116225. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116226. return true;
  116227. }
  116228. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116229. return true;
  116230. }
  116231. return false;
  116232. },
  116233. enumerable: true,
  116234. configurable: true
  116235. });
  116236. /**
  116237. * The entire material has been created in order to prevent overdraw.
  116238. * @returns false
  116239. */
  116240. BackgroundMaterial.prototype.needAlphaTesting = function () {
  116241. return true;
  116242. };
  116243. /**
  116244. * The entire material has been created in order to prevent overdraw.
  116245. * @returns true if blending is enable
  116246. */
  116247. BackgroundMaterial.prototype.needAlphaBlending = function () {
  116248. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  116249. };
  116250. /**
  116251. * Checks wether the material is ready to be rendered for a given mesh.
  116252. * @param mesh The mesh to render
  116253. * @param subMesh The submesh to check against
  116254. * @param useInstances Specify wether or not the material is used with instances
  116255. * @returns true if all the dependencies are ready (Textures, Effects...)
  116256. */
  116257. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  116258. var _this = this;
  116259. if (useInstances === void 0) { useInstances = false; }
  116260. if (subMesh.effect && this.isFrozen) {
  116261. if (this._wasPreviouslyReady) {
  116262. return true;
  116263. }
  116264. }
  116265. if (!subMesh._materialDefines) {
  116266. subMesh._materialDefines = new BackgroundMaterialDefines();
  116267. }
  116268. var scene = this.getScene();
  116269. var defines = subMesh._materialDefines;
  116270. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  116271. if (defines._renderId === scene.getRenderId()) {
  116272. return true;
  116273. }
  116274. }
  116275. var engine = scene.getEngine();
  116276. // Lights
  116277. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  116278. defines._needNormals = true;
  116279. // Textures
  116280. if (defines._areTexturesDirty) {
  116281. defines._needUVs = false;
  116282. if (scene.texturesEnabled) {
  116283. if (scene.getEngine().getCaps().textureLOD) {
  116284. defines.TEXTURELODSUPPORT = true;
  116285. }
  116286. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116287. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  116288. return false;
  116289. }
  116290. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  116291. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  116292. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  116293. defines.OPACITYFRESNEL = this._opacityFresnel;
  116294. }
  116295. else {
  116296. defines.DIFFUSE = false;
  116297. defines.DIFFUSEHASALPHA = false;
  116298. defines.GAMMADIFFUSE = false;
  116299. defines.OPACITYFRESNEL = false;
  116300. }
  116301. var reflectionTexture = this._reflectionTexture;
  116302. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116303. if (!reflectionTexture.isReadyOrNotBlocking()) {
  116304. return false;
  116305. }
  116306. defines.REFLECTION = true;
  116307. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  116308. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  116309. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  116310. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  116311. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  116312. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  116313. defines.REFLECTIONBGR = this.switchToBGR;
  116314. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  116315. defines.INVERTCUBICMAP = true;
  116316. }
  116317. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  116318. switch (reflectionTexture.coordinatesMode) {
  116319. case BABYLON.Texture.EXPLICIT_MODE:
  116320. defines.REFLECTIONMAP_EXPLICIT = true;
  116321. break;
  116322. case BABYLON.Texture.PLANAR_MODE:
  116323. defines.REFLECTIONMAP_PLANAR = true;
  116324. break;
  116325. case BABYLON.Texture.PROJECTION_MODE:
  116326. defines.REFLECTIONMAP_PROJECTION = true;
  116327. break;
  116328. case BABYLON.Texture.SKYBOX_MODE:
  116329. defines.REFLECTIONMAP_SKYBOX = true;
  116330. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  116331. break;
  116332. case BABYLON.Texture.SPHERICAL_MODE:
  116333. defines.REFLECTIONMAP_SPHERICAL = true;
  116334. break;
  116335. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  116336. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  116337. break;
  116338. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  116339. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  116340. break;
  116341. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  116342. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  116343. break;
  116344. case BABYLON.Texture.CUBIC_MODE:
  116345. case BABYLON.Texture.INVCUBIC_MODE:
  116346. default:
  116347. defines.REFLECTIONMAP_CUBIC = true;
  116348. break;
  116349. }
  116350. if (this.reflectionFresnel) {
  116351. defines.REFLECTIONFRESNEL = true;
  116352. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  116353. this._reflectionControls.x = this.reflectionAmount;
  116354. this._reflectionControls.y = this.reflectionReflectance0;
  116355. this._reflectionControls.z = this.reflectionReflectance90;
  116356. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  116357. }
  116358. else {
  116359. defines.REFLECTIONFRESNEL = false;
  116360. defines.REFLECTIONFALLOFF = false;
  116361. }
  116362. }
  116363. else {
  116364. defines.REFLECTION = false;
  116365. defines.REFLECTIONFRESNEL = false;
  116366. defines.REFLECTIONFALLOFF = false;
  116367. defines.REFLECTIONBLUR = false;
  116368. defines.REFLECTIONMAP_3D = false;
  116369. defines.REFLECTIONMAP_SPHERICAL = false;
  116370. defines.REFLECTIONMAP_PLANAR = false;
  116371. defines.REFLECTIONMAP_CUBIC = false;
  116372. defines.REFLECTIONMAP_PROJECTION = false;
  116373. defines.REFLECTIONMAP_SKYBOX = false;
  116374. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116375. defines.REFLECTIONMAP_EXPLICIT = false;
  116376. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116377. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116378. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116379. defines.INVERTCUBICMAP = false;
  116380. defines.REFLECTIONMAP_OPPOSITEZ = false;
  116381. defines.LODINREFLECTIONALPHA = false;
  116382. defines.GAMMAREFLECTION = false;
  116383. defines.RGBDREFLECTION = false;
  116384. }
  116385. }
  116386. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  116387. defines.USERGBCOLOR = this._useRGBColor;
  116388. defines.NOISE = this._enableNoise;
  116389. }
  116390. if (defines._areLightsDirty) {
  116391. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  116392. }
  116393. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  116394. if (!this._imageProcessingConfiguration.isReady()) {
  116395. return false;
  116396. }
  116397. this._imageProcessingConfiguration.prepareDefines(defines);
  116398. }
  116399. // Misc.
  116400. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  116401. // Values that need to be evaluated on every frame
  116402. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  116403. // Attribs
  116404. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  116405. if (mesh) {
  116406. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  116407. mesh.createNormals(true);
  116408. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  116409. }
  116410. }
  116411. }
  116412. // Get correct effect
  116413. if (defines.isDirty) {
  116414. defines.markAsProcessed();
  116415. scene.resetCachedMaterial();
  116416. // Fallbacks
  116417. var fallbacks = new BABYLON.EffectFallbacks();
  116418. if (defines.FOG) {
  116419. fallbacks.addFallback(0, "FOG");
  116420. }
  116421. if (defines.POINTSIZE) {
  116422. fallbacks.addFallback(1, "POINTSIZE");
  116423. }
  116424. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  116425. if (defines.NUM_BONE_INFLUENCERS > 0) {
  116426. fallbacks.addCPUSkinningFallback(0, mesh);
  116427. }
  116428. //Attributes
  116429. var attribs = [BABYLON.VertexBuffer.PositionKind];
  116430. if (defines.NORMAL) {
  116431. attribs.push(BABYLON.VertexBuffer.NormalKind);
  116432. }
  116433. if (defines.UV1) {
  116434. attribs.push(BABYLON.VertexBuffer.UVKind);
  116435. }
  116436. if (defines.UV2) {
  116437. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  116438. }
  116439. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  116440. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  116441. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  116442. "vFogInfos", "vFogColor", "pointSize",
  116443. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  116444. "vPrimaryColor", "vPrimaryColorShadow",
  116445. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  116446. "shadowLevel", "alpha",
  116447. "vBackgroundCenter", "vReflectionControl",
  116448. "vDiffuseInfos", "diffuseMatrix",
  116449. ];
  116450. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  116451. var uniformBuffers = ["Material", "Scene"];
  116452. if (BABYLON.ImageProcessingConfiguration) {
  116453. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  116454. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  116455. }
  116456. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  116457. uniformsNames: uniforms,
  116458. uniformBuffersNames: uniformBuffers,
  116459. samplers: samplers,
  116460. defines: defines,
  116461. maxSimultaneousLights: this._maxSimultaneousLights
  116462. });
  116463. var onCompiled = function (effect) {
  116464. if (_this.onCompiled) {
  116465. _this.onCompiled(effect);
  116466. }
  116467. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  116468. };
  116469. var join = defines.toString();
  116470. subMesh.setEffect(scene.getEngine().createEffect("background", {
  116471. attributes: attribs,
  116472. uniformsNames: uniforms,
  116473. uniformBuffersNames: uniformBuffers,
  116474. samplers: samplers,
  116475. defines: join,
  116476. fallbacks: fallbacks,
  116477. onCompiled: onCompiled,
  116478. onError: this.onError,
  116479. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  116480. }, engine), defines);
  116481. this.buildUniformLayout();
  116482. }
  116483. if (!subMesh.effect || !subMesh.effect.isReady()) {
  116484. return false;
  116485. }
  116486. defines._renderId = scene.getRenderId();
  116487. this._wasPreviouslyReady = true;
  116488. return true;
  116489. };
  116490. /**
  116491. * Compute the primary color according to the chosen perceptual color.
  116492. */
  116493. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  116494. if (!this.__perceptualColor) {
  116495. return;
  116496. }
  116497. this._primaryColor.copyFrom(this.__perceptualColor);
  116498. // Revert gamma space.
  116499. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  116500. // Revert image processing configuration.
  116501. if (this._imageProcessingConfiguration) {
  116502. // Revert Exposure.
  116503. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  116504. }
  116505. this._computePrimaryColors();
  116506. };
  116507. /**
  116508. * Compute the highlights and shadow colors according to their chosen levels.
  116509. */
  116510. BackgroundMaterial.prototype._computePrimaryColors = function () {
  116511. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  116512. return;
  116513. }
  116514. // Find the highlight color based on the configuration.
  116515. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  116516. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  116517. // Find the shadow color based on the configuration.
  116518. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  116519. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  116520. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  116521. };
  116522. /**
  116523. * Build the uniform buffer used in the material.
  116524. */
  116525. BackgroundMaterial.prototype.buildUniformLayout = function () {
  116526. // Order is important !
  116527. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  116528. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  116529. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  116530. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  116531. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  116532. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  116533. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  116534. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  116535. this._uniformBuffer.addUniform("pointSize", 1);
  116536. this._uniformBuffer.addUniform("shadowLevel", 1);
  116537. this._uniformBuffer.addUniform("alpha", 1);
  116538. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  116539. this._uniformBuffer.addUniform("vReflectionControl", 4);
  116540. this._uniformBuffer.create();
  116541. };
  116542. /**
  116543. * Unbind the material.
  116544. */
  116545. BackgroundMaterial.prototype.unbind = function () {
  116546. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116547. this._uniformBuffer.setTexture("diffuseSampler", null);
  116548. }
  116549. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116550. this._uniformBuffer.setTexture("reflectionSampler", null);
  116551. }
  116552. _super.prototype.unbind.call(this);
  116553. };
  116554. /**
  116555. * Bind only the world matrix to the material.
  116556. * @param world The world matrix to bind.
  116557. */
  116558. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  116559. this._activeEffect.setMatrix("world", world);
  116560. };
  116561. /**
  116562. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  116563. * @param world The world matrix to bind.
  116564. * @param subMesh The submesh to bind for.
  116565. */
  116566. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  116567. var scene = this.getScene();
  116568. var defines = subMesh._materialDefines;
  116569. if (!defines) {
  116570. return;
  116571. }
  116572. var effect = subMesh.effect;
  116573. if (!effect) {
  116574. return;
  116575. }
  116576. this._activeEffect = effect;
  116577. // Matrices
  116578. this.bindOnlyWorldMatrix(world);
  116579. // Bones
  116580. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  116581. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  116582. if (mustRebind) {
  116583. this._uniformBuffer.bindToEffect(effect, "Material");
  116584. this.bindViewProjection(effect);
  116585. var reflectionTexture = this._reflectionTexture;
  116586. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  116587. // Texture uniforms
  116588. if (scene.texturesEnabled) {
  116589. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116590. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  116591. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  116592. }
  116593. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116594. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  116595. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  116596. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  116597. }
  116598. }
  116599. if (this.shadowLevel > 0) {
  116600. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  116601. }
  116602. this._uniformBuffer.updateFloat("alpha", this.alpha);
  116603. // Point size
  116604. if (this.pointsCloud) {
  116605. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  116606. }
  116607. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  116608. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  116609. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  116610. }
  116611. else {
  116612. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  116613. }
  116614. }
  116615. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  116616. // Textures
  116617. if (scene.texturesEnabled) {
  116618. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116619. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  116620. }
  116621. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116622. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  116623. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  116624. }
  116625. else if (!defines.REFLECTIONBLUR) {
  116626. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  116627. }
  116628. else {
  116629. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  116630. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  116631. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  116632. }
  116633. if (defines.REFLECTIONFRESNEL) {
  116634. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  116635. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  116636. }
  116637. }
  116638. }
  116639. // Clip plane
  116640. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  116641. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  116642. }
  116643. if (mustRebind || !this.isFrozen) {
  116644. if (scene.lightsEnabled) {
  116645. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  116646. }
  116647. // View
  116648. this.bindView(effect);
  116649. // Fog
  116650. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  116651. // image processing
  116652. if (this._imageProcessingConfiguration) {
  116653. this._imageProcessingConfiguration.bind(this._activeEffect);
  116654. }
  116655. }
  116656. this._uniformBuffer.update();
  116657. this._afterBind(mesh, this._activeEffect);
  116658. };
  116659. /**
  116660. * Dispose the material.
  116661. * @param forceDisposeEffect Force disposal of the associated effect.
  116662. * @param forceDisposeTextures Force disposal of the associated textures.
  116663. */
  116664. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  116665. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  116666. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  116667. if (forceDisposeTextures) {
  116668. if (this.diffuseTexture) {
  116669. this.diffuseTexture.dispose();
  116670. }
  116671. if (this.reflectionTexture) {
  116672. this.reflectionTexture.dispose();
  116673. }
  116674. }
  116675. this._renderTargets.dispose();
  116676. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116677. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116678. }
  116679. _super.prototype.dispose.call(this, forceDisposeEffect);
  116680. };
  116681. /**
  116682. * Clones the material.
  116683. * @param name The cloned name.
  116684. * @returns The cloned material.
  116685. */
  116686. BackgroundMaterial.prototype.clone = function (name) {
  116687. var _this = this;
  116688. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  116689. };
  116690. /**
  116691. * Serializes the current material to its JSON representation.
  116692. * @returns The JSON representation.
  116693. */
  116694. BackgroundMaterial.prototype.serialize = function () {
  116695. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  116696. serializationObject.customType = "BABYLON.BackgroundMaterial";
  116697. return serializationObject;
  116698. };
  116699. /**
  116700. * Gets the class name of the material
  116701. * @returns "BackgroundMaterial"
  116702. */
  116703. BackgroundMaterial.prototype.getClassName = function () {
  116704. return "BackgroundMaterial";
  116705. };
  116706. /**
  116707. * Parse a JSON input to create back a background material.
  116708. * @param source The JSON data to parse
  116709. * @param scene The scene to create the parsed material in
  116710. * @param rootUrl The root url of the assets the material depends upon
  116711. * @returns the instantiated BackgroundMaterial.
  116712. */
  116713. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  116714. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  116715. };
  116716. /**
  116717. * Standard reflectance value at parallel view angle.
  116718. */
  116719. BackgroundMaterial.StandardReflectance0 = 0.05;
  116720. /**
  116721. * Standard reflectance value at grazing angle.
  116722. */
  116723. BackgroundMaterial.StandardReflectance90 = 0.5;
  116724. __decorate([
  116725. BABYLON.serializeAsColor3()
  116726. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  116727. __decorate([
  116728. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  116729. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  116730. __decorate([
  116731. BABYLON.serializeAsColor3()
  116732. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  116733. __decorate([
  116734. BABYLON.serialize()
  116735. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  116736. __decorate([
  116737. BABYLON.serialize()
  116738. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  116739. __decorate([
  116740. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  116741. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  116742. __decorate([
  116743. BABYLON.serializeAsTexture()
  116744. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  116745. __decorate([
  116746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116747. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  116748. __decorate([
  116749. BABYLON.serialize()
  116750. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  116751. __decorate([
  116752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116753. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  116754. __decorate([
  116755. BABYLON.serializeAsTexture()
  116756. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  116757. __decorate([
  116758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116759. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  116760. __decorate([
  116761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116762. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  116763. __decorate([
  116764. BABYLON.serialize()
  116765. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  116766. __decorate([
  116767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116768. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  116769. __decorate([
  116770. BABYLON.serializeAsVector3()
  116771. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  116772. __decorate([
  116773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116774. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  116775. __decorate([
  116776. BABYLON.serialize()
  116777. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  116778. __decorate([
  116779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116780. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  116781. __decorate([
  116782. BABYLON.serialize()
  116783. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  116784. __decorate([
  116785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116786. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  116787. __decorate([
  116788. BABYLON.serialize()
  116789. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  116790. __decorate([
  116791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116792. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  116793. __decorate([
  116794. BABYLON.serialize()
  116795. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  116796. __decorate([
  116797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116798. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  116799. __decorate([
  116800. BABYLON.serialize()
  116801. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  116802. __decorate([
  116803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116804. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  116805. __decorate([
  116806. BABYLON.serialize()
  116807. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  116808. __decorate([
  116809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116810. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  116811. __decorate([
  116812. BABYLON.serialize()
  116813. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  116814. __decorate([
  116815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116816. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  116817. __decorate([
  116818. BABYLON.serialize()
  116819. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  116820. __decorate([
  116821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116822. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  116823. __decorate([
  116824. BABYLON.serialize()
  116825. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  116826. __decorate([
  116827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  116828. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  116829. __decorate([
  116830. BABYLON.serializeAsImageProcessingConfiguration()
  116831. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  116832. return BackgroundMaterial;
  116833. }(BABYLON.PushMaterial));
  116834. BABYLON.BackgroundMaterial = BackgroundMaterial;
  116835. })(BABYLON || (BABYLON = {}));
  116836. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  116837. var __assign = (this && this.__assign) || function () {
  116838. __assign = Object.assign || function(t) {
  116839. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116840. s = arguments[i];
  116841. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116842. t[p] = s[p];
  116843. }
  116844. return t;
  116845. };
  116846. return __assign.apply(this, arguments);
  116847. };
  116848. var BABYLON;
  116849. (function (BABYLON) {
  116850. /**
  116851. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  116852. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  116853. * It also helps with the default setup of your imageProcessing configuration.
  116854. */
  116855. var EnvironmentHelper = /** @class */ (function () {
  116856. /**
  116857. * constructor
  116858. * @param options
  116859. * @param scene The scene to add the material to
  116860. */
  116861. function EnvironmentHelper(options, scene) {
  116862. var _this = this;
  116863. this._errorHandler = function (message, exception) {
  116864. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  116865. };
  116866. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  116867. this._scene = scene;
  116868. this.onErrorObservable = new BABYLON.Observable();
  116869. this._setupBackground();
  116870. this._setupImageProcessing();
  116871. }
  116872. /**
  116873. * Creates the default options for the helper.
  116874. */
  116875. EnvironmentHelper._getDefaultOptions = function () {
  116876. return {
  116877. createGround: true,
  116878. groundSize: 15,
  116879. groundTexture: this._groundTextureCDNUrl,
  116880. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  116881. groundOpacity: 0.9,
  116882. enableGroundShadow: true,
  116883. groundShadowLevel: 0.5,
  116884. enableGroundMirror: false,
  116885. groundMirrorSizeRatio: 0.3,
  116886. groundMirrorBlurKernel: 64,
  116887. groundMirrorAmount: 1,
  116888. groundMirrorFresnelWeight: 1,
  116889. groundMirrorFallOffDistance: 0,
  116890. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  116891. groundYBias: 0.00001,
  116892. createSkybox: true,
  116893. skyboxSize: 20,
  116894. skyboxTexture: this._skyboxTextureCDNUrl,
  116895. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  116896. backgroundYRotation: 0,
  116897. sizeAuto: true,
  116898. rootPosition: BABYLON.Vector3.Zero(),
  116899. setupImageProcessing: true,
  116900. environmentTexture: this._environmentTextureCDNUrl,
  116901. cameraExposure: 0.8,
  116902. cameraContrast: 1.2,
  116903. toneMappingEnabled: true,
  116904. };
  116905. };
  116906. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  116907. /**
  116908. * Gets the root mesh created by the helper.
  116909. */
  116910. get: function () {
  116911. return this._rootMesh;
  116912. },
  116913. enumerable: true,
  116914. configurable: true
  116915. });
  116916. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  116917. /**
  116918. * Gets the skybox created by the helper.
  116919. */
  116920. get: function () {
  116921. return this._skybox;
  116922. },
  116923. enumerable: true,
  116924. configurable: true
  116925. });
  116926. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  116927. /**
  116928. * Gets the skybox texture created by the helper.
  116929. */
  116930. get: function () {
  116931. return this._skyboxTexture;
  116932. },
  116933. enumerable: true,
  116934. configurable: true
  116935. });
  116936. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  116937. /**
  116938. * Gets the skybox material created by the helper.
  116939. */
  116940. get: function () {
  116941. return this._skyboxMaterial;
  116942. },
  116943. enumerable: true,
  116944. configurable: true
  116945. });
  116946. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  116947. /**
  116948. * Gets the ground mesh created by the helper.
  116949. */
  116950. get: function () {
  116951. return this._ground;
  116952. },
  116953. enumerable: true,
  116954. configurable: true
  116955. });
  116956. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  116957. /**
  116958. * Gets the ground texture created by the helper.
  116959. */
  116960. get: function () {
  116961. return this._groundTexture;
  116962. },
  116963. enumerable: true,
  116964. configurable: true
  116965. });
  116966. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  116967. /**
  116968. * Gets the ground mirror created by the helper.
  116969. */
  116970. get: function () {
  116971. return this._groundMirror;
  116972. },
  116973. enumerable: true,
  116974. configurable: true
  116975. });
  116976. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  116977. /**
  116978. * Gets the ground mirror render list to helps pushing the meshes
  116979. * you wish in the ground reflection.
  116980. */
  116981. get: function () {
  116982. if (this._groundMirror) {
  116983. return this._groundMirror.renderList;
  116984. }
  116985. return null;
  116986. },
  116987. enumerable: true,
  116988. configurable: true
  116989. });
  116990. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  116991. /**
  116992. * Gets the ground material created by the helper.
  116993. */
  116994. get: function () {
  116995. return this._groundMaterial;
  116996. },
  116997. enumerable: true,
  116998. configurable: true
  116999. });
  117000. /**
  117001. * Updates the background according to the new options
  117002. * @param options
  117003. */
  117004. EnvironmentHelper.prototype.updateOptions = function (options) {
  117005. var newOptions = __assign({}, this._options, options);
  117006. if (this._ground && !newOptions.createGround) {
  117007. this._ground.dispose();
  117008. this._ground = null;
  117009. }
  117010. if (this._groundMaterial && !newOptions.createGround) {
  117011. this._groundMaterial.dispose();
  117012. this._groundMaterial = null;
  117013. }
  117014. if (this._groundTexture) {
  117015. if (this._options.groundTexture != newOptions.groundTexture) {
  117016. this._groundTexture.dispose();
  117017. this._groundTexture = null;
  117018. }
  117019. }
  117020. if (this._skybox && !newOptions.createSkybox) {
  117021. this._skybox.dispose();
  117022. this._skybox = null;
  117023. }
  117024. if (this._skyboxMaterial && !newOptions.createSkybox) {
  117025. this._skyboxMaterial.dispose();
  117026. this._skyboxMaterial = null;
  117027. }
  117028. if (this._skyboxTexture) {
  117029. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  117030. this._skyboxTexture.dispose();
  117031. this._skyboxTexture = null;
  117032. }
  117033. }
  117034. if (this._groundMirror && !newOptions.enableGroundMirror) {
  117035. this._groundMirror.dispose();
  117036. this._groundMirror = null;
  117037. }
  117038. if (this._scene.environmentTexture) {
  117039. if (this._options.environmentTexture != newOptions.environmentTexture) {
  117040. this._scene.environmentTexture.dispose();
  117041. }
  117042. }
  117043. this._options = newOptions;
  117044. this._setupBackground();
  117045. this._setupImageProcessing();
  117046. };
  117047. /**
  117048. * Sets the primary color of all the available elements.
  117049. * @param color the main color to affect to the ground and the background
  117050. */
  117051. EnvironmentHelper.prototype.setMainColor = function (color) {
  117052. if (this.groundMaterial) {
  117053. this.groundMaterial.primaryColor = color;
  117054. }
  117055. if (this.skyboxMaterial) {
  117056. this.skyboxMaterial.primaryColor = color;
  117057. }
  117058. if (this.groundMirror) {
  117059. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  117060. }
  117061. };
  117062. /**
  117063. * Setup the image processing according to the specified options.
  117064. */
  117065. EnvironmentHelper.prototype._setupImageProcessing = function () {
  117066. if (this._options.setupImageProcessing) {
  117067. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  117068. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  117069. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  117070. this._setupEnvironmentTexture();
  117071. }
  117072. };
  117073. /**
  117074. * Setup the environment texture according to the specified options.
  117075. */
  117076. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  117077. if (this._scene.environmentTexture) {
  117078. return;
  117079. }
  117080. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  117081. this._scene.environmentTexture = this._options.environmentTexture;
  117082. return;
  117083. }
  117084. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  117085. this._scene.environmentTexture = environmentTexture;
  117086. };
  117087. /**
  117088. * Setup the background according to the specified options.
  117089. */
  117090. EnvironmentHelper.prototype._setupBackground = function () {
  117091. if (!this._rootMesh) {
  117092. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  117093. }
  117094. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  117095. var sceneSize = this._getSceneSize();
  117096. if (this._options.createGround) {
  117097. this._setupGround(sceneSize);
  117098. this._setupGroundMaterial();
  117099. this._setupGroundDiffuseTexture();
  117100. if (this._options.enableGroundMirror) {
  117101. this._setupGroundMirrorTexture(sceneSize);
  117102. }
  117103. this._setupMirrorInGroundMaterial();
  117104. }
  117105. if (this._options.createSkybox) {
  117106. this._setupSkybox(sceneSize);
  117107. this._setupSkyboxMaterial();
  117108. this._setupSkyboxReflectionTexture();
  117109. }
  117110. this._rootMesh.position.x = sceneSize.rootPosition.x;
  117111. this._rootMesh.position.z = sceneSize.rootPosition.z;
  117112. this._rootMesh.position.y = sceneSize.rootPosition.y;
  117113. };
  117114. /**
  117115. * Get the scene sizes according to the setup.
  117116. */
  117117. EnvironmentHelper.prototype._getSceneSize = function () {
  117118. var _this = this;
  117119. var groundSize = this._options.groundSize;
  117120. var skyboxSize = this._options.skyboxSize;
  117121. var rootPosition = this._options.rootPosition;
  117122. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  117123. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117124. }
  117125. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  117126. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  117127. });
  117128. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117129. if (this._options.sizeAuto) {
  117130. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  117131. this._scene.activeCamera.upperRadiusLimit) {
  117132. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  117133. skyboxSize = groundSize;
  117134. }
  117135. var sceneDiagonalLenght = sceneDiagonal.length();
  117136. if (sceneDiagonalLenght > groundSize) {
  117137. groundSize = sceneDiagonalLenght * 2;
  117138. skyboxSize = groundSize;
  117139. }
  117140. // 10 % bigger.
  117141. groundSize *= 1.1;
  117142. skyboxSize *= 1.5;
  117143. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  117144. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  117145. }
  117146. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117147. };
  117148. /**
  117149. * Setup the ground according to the specified options.
  117150. */
  117151. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  117152. var _this = this;
  117153. if (!this._ground || this._ground.isDisposed()) {
  117154. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  117155. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  117156. this._ground.parent = this._rootMesh;
  117157. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  117158. }
  117159. this._ground.receiveShadows = this._options.enableGroundShadow;
  117160. };
  117161. /**
  117162. * Setup the ground material according to the specified options.
  117163. */
  117164. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  117165. if (!this._groundMaterial) {
  117166. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  117167. }
  117168. this._groundMaterial.alpha = this._options.groundOpacity;
  117169. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  117170. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  117171. this._groundMaterial.primaryColor = this._options.groundColor;
  117172. this._groundMaterial.useRGBColor = false;
  117173. this._groundMaterial.enableNoise = true;
  117174. if (this._ground) {
  117175. this._ground.material = this._groundMaterial;
  117176. }
  117177. };
  117178. /**
  117179. * Setup the ground diffuse texture according to the specified options.
  117180. */
  117181. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  117182. if (!this._groundMaterial) {
  117183. return;
  117184. }
  117185. if (this._groundTexture) {
  117186. return;
  117187. }
  117188. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  117189. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  117190. return;
  117191. }
  117192. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117193. diffuseTexture.gammaSpace = false;
  117194. diffuseTexture.hasAlpha = true;
  117195. this._groundMaterial.diffuseTexture = diffuseTexture;
  117196. };
  117197. /**
  117198. * Setup the ground mirror texture according to the specified options.
  117199. */
  117200. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  117201. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117202. if (!this._groundMirror) {
  117203. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  117204. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  117205. this._groundMirror.anisotropicFilteringLevel = 1;
  117206. this._groundMirror.wrapU = wrapping;
  117207. this._groundMirror.wrapV = wrapping;
  117208. this._groundMirror.gammaSpace = false;
  117209. if (this._groundMirror.renderList) {
  117210. for (var i = 0; i < this._scene.meshes.length; i++) {
  117211. var mesh = this._scene.meshes[i];
  117212. if (mesh !== this._ground &&
  117213. mesh !== this._skybox &&
  117214. mesh !== this._rootMesh) {
  117215. this._groundMirror.renderList.push(mesh);
  117216. }
  117217. }
  117218. }
  117219. }
  117220. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  117221. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  117222. };
  117223. /**
  117224. * Setup the ground to receive the mirror texture.
  117225. */
  117226. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  117227. if (this._groundMaterial) {
  117228. this._groundMaterial.reflectionTexture = this._groundMirror;
  117229. this._groundMaterial.reflectionFresnel = true;
  117230. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  117231. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  117232. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  117233. }
  117234. };
  117235. /**
  117236. * Setup the skybox according to the specified options.
  117237. */
  117238. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  117239. var _this = this;
  117240. if (!this._skybox || this._skybox.isDisposed()) {
  117241. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  117242. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  117243. }
  117244. this._skybox.parent = this._rootMesh;
  117245. };
  117246. /**
  117247. * Setup the skybox material according to the specified options.
  117248. */
  117249. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  117250. if (!this._skybox) {
  117251. return;
  117252. }
  117253. if (!this._skyboxMaterial) {
  117254. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  117255. }
  117256. this._skyboxMaterial.useRGBColor = false;
  117257. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  117258. this._skyboxMaterial.enableNoise = true;
  117259. this._skybox.material = this._skyboxMaterial;
  117260. };
  117261. /**
  117262. * Setup the skybox reflection texture according to the specified options.
  117263. */
  117264. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  117265. if (!this._skyboxMaterial) {
  117266. return;
  117267. }
  117268. if (this._skyboxTexture) {
  117269. return;
  117270. }
  117271. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  117272. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  117273. return;
  117274. }
  117275. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117276. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117277. this._skyboxTexture.gammaSpace = false;
  117278. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  117279. };
  117280. /**
  117281. * Dispose all the elements created by the Helper.
  117282. */
  117283. EnvironmentHelper.prototype.dispose = function () {
  117284. if (this._groundMaterial) {
  117285. this._groundMaterial.dispose(true, true);
  117286. }
  117287. if (this._skyboxMaterial) {
  117288. this._skyboxMaterial.dispose(true, true);
  117289. }
  117290. this._rootMesh.dispose(false);
  117291. };
  117292. /**
  117293. * Default ground texture URL.
  117294. */
  117295. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  117296. /**
  117297. * Default skybox texture URL.
  117298. */
  117299. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  117300. /**
  117301. * Default environment texture URL.
  117302. */
  117303. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  117304. return EnvironmentHelper;
  117305. }());
  117306. BABYLON.EnvironmentHelper = EnvironmentHelper;
  117307. })(BABYLON || (BABYLON = {}));
  117308. //# sourceMappingURL=babylon.environmentHelper.js.map
  117309. var BABYLON;
  117310. (function (BABYLON) {
  117311. /** Internal class used to store shapes for emitters */
  117312. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  117313. function ParticleSystemSetEmitterCreationOptions() {
  117314. }
  117315. return ParticleSystemSetEmitterCreationOptions;
  117316. }());
  117317. /**
  117318. * Represents a set of particle systems working together to create a specific effect
  117319. */
  117320. var ParticleSystemSet = /** @class */ (function () {
  117321. function ParticleSystemSet() {
  117322. /**
  117323. * Gets the particle system list
  117324. */
  117325. this.systems = new Array();
  117326. }
  117327. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  117328. /**
  117329. * Gets the emitter node used with this set
  117330. */
  117331. get: function () {
  117332. return this._emitterNode;
  117333. },
  117334. enumerable: true,
  117335. configurable: true
  117336. });
  117337. /**
  117338. * Creates a new emitter mesh as a sphere
  117339. * @param options defines the options used to create the sphere
  117340. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  117341. * @param scene defines the hosting scene
  117342. */
  117343. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  117344. if (this._emitterNode) {
  117345. this._emitterNode.dispose();
  117346. }
  117347. this._emitterCreationOptions = {
  117348. kind: "Sphere",
  117349. options: options,
  117350. renderingGroupId: renderingGroupId
  117351. };
  117352. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  117353. emitterMesh.renderingGroupId = renderingGroupId;
  117354. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  117355. material.emissiveColor = options.color;
  117356. emitterMesh.material = material;
  117357. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117358. var system = _a[_i];
  117359. system.emitter = emitterMesh;
  117360. }
  117361. this._emitterNode = emitterMesh;
  117362. };
  117363. /**
  117364. * Starts all particle systems of the set
  117365. * @param emitter defines an optional mesh to use as emitter for the particle systems
  117366. */
  117367. ParticleSystemSet.prototype.start = function (emitter) {
  117368. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117369. var system = _a[_i];
  117370. if (emitter) {
  117371. system.emitter = emitter;
  117372. }
  117373. system.start();
  117374. }
  117375. };
  117376. /**
  117377. * Release all associated resources
  117378. */
  117379. ParticleSystemSet.prototype.dispose = function () {
  117380. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117381. var system = _a[_i];
  117382. system.dispose();
  117383. }
  117384. this.systems = [];
  117385. if (this._emitterNode) {
  117386. this._emitterNode.dispose();
  117387. this._emitterNode = null;
  117388. }
  117389. };
  117390. /**
  117391. * Serialize the set into a JSON compatible object
  117392. * @returns a JSON compatible representation of the set
  117393. */
  117394. ParticleSystemSet.prototype.serialize = function () {
  117395. var result = {};
  117396. result.systems = [];
  117397. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117398. var system = _a[_i];
  117399. result.systems.push(system.serialize());
  117400. }
  117401. if (this._emitterNode) {
  117402. result.emitter = this._emitterCreationOptions;
  117403. }
  117404. return result;
  117405. };
  117406. /**
  117407. * Parse a new ParticleSystemSet from a serialized source
  117408. * @param data defines a JSON compatible representation of the set
  117409. * @param scene defines the hosting scene
  117410. * @param gpu defines if we want GPU particles or CPU particles
  117411. * @returns a new ParticleSystemSet
  117412. */
  117413. ParticleSystemSet.Parse = function (data, scene, gpu) {
  117414. if (gpu === void 0) { gpu = false; }
  117415. var result = new ParticleSystemSet();
  117416. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  117417. scene = scene || BABYLON.Engine.LastCreatedScene;
  117418. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  117419. var system = _a[_i];
  117420. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  117421. }
  117422. if (data.emitter) {
  117423. var options = data.emitter.options;
  117424. switch (data.emitter.kind) {
  117425. case "Sphere":
  117426. result.setEmitterAsSphere({
  117427. diameter: options.diameter,
  117428. segments: options.segments,
  117429. color: BABYLON.Color3.FromArray(options.color)
  117430. }, data.emitter.renderingGroupId, scene);
  117431. break;
  117432. }
  117433. }
  117434. return result;
  117435. };
  117436. return ParticleSystemSet;
  117437. }());
  117438. BABYLON.ParticleSystemSet = ParticleSystemSet;
  117439. })(BABYLON || (BABYLON = {}));
  117440. //# sourceMappingURL=babylon.particleSystemSet.js.map
  117441. var BABYLON;
  117442. (function (BABYLON) {
  117443. /**
  117444. * This class is made for on one-liner static method to help creating particle system set.
  117445. */
  117446. var ParticleHelper = /** @class */ (function () {
  117447. function ParticleHelper() {
  117448. }
  117449. /**
  117450. * Create a default particle system that you can tweak
  117451. * @param emitter defines the emitter to use
  117452. * @param capacity defines the system capacity (default is 500 particles)
  117453. * @param scene defines the hosting scene
  117454. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  117455. * @returns the new Particle system
  117456. */
  117457. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  117458. if (capacity === void 0) { capacity = 500; }
  117459. if (useGPU === void 0) { useGPU = false; }
  117460. var system;
  117461. if (useGPU) {
  117462. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  117463. }
  117464. else {
  117465. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  117466. }
  117467. system.emitter = emitter;
  117468. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  117469. system.createConeEmitter(0.1, Math.PI / 4);
  117470. // Particle color
  117471. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  117472. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  117473. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  117474. // Particle Size
  117475. system.minSize = 0.1;
  117476. system.maxSize = 0.1;
  117477. // Emission speed
  117478. system.minEmitPower = 2;
  117479. system.maxEmitPower = 2;
  117480. // Update speed
  117481. system.updateSpeed = 1 / 60;
  117482. system.emitRate = 30;
  117483. return system;
  117484. };
  117485. /**
  117486. * This is the main static method (one-liner) of this helper to create different particle systems
  117487. * @param type This string represents the type to the particle system to create
  117488. * @param scene The scene where the particle system should live
  117489. * @param gpu If the system will use gpu
  117490. * @returns the ParticleSystemSet created
  117491. */
  117492. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  117493. if (gpu === void 0) { gpu = false; }
  117494. if (!scene) {
  117495. scene = BABYLON.Engine.LastCreatedScene;
  117496. }
  117497. var token = {};
  117498. scene._addPendingData(token);
  117499. return new Promise(function (resolve, reject) {
  117500. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  117501. scene._removePendingData(token);
  117502. return reject("Particle system with GPU is not supported.");
  117503. }
  117504. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  117505. scene._removePendingData(token);
  117506. var newData = JSON.parse(data.toString());
  117507. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  117508. }, undefined, undefined, undefined, function (req, exception) {
  117509. scene._removePendingData(token);
  117510. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  117511. });
  117512. });
  117513. };
  117514. /**
  117515. * Static function used to export a particle system to a ParticleSystemSet variable.
  117516. * Please note that the emitter shape is not exported
  117517. * @param systems defines the particle systems to export
  117518. * @returns the created particle system set
  117519. */
  117520. ParticleHelper.ExportSet = function (systems) {
  117521. var set = new BABYLON.ParticleSystemSet();
  117522. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  117523. var system = systems_1[_i];
  117524. set.systems.push(system);
  117525. }
  117526. return set;
  117527. };
  117528. /**
  117529. * Gets or sets base Assets URL
  117530. */
  117531. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  117532. return ParticleHelper;
  117533. }());
  117534. BABYLON.ParticleHelper = ParticleHelper;
  117535. })(BABYLON || (BABYLON = {}));
  117536. //# sourceMappingURL=babylon.particleHelper.js.map
  117537. var BABYLON;
  117538. (function (BABYLON) {
  117539. /**
  117540. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  117541. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  117542. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  117543. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  117544. */
  117545. var VideoDome = /** @class */ (function (_super) {
  117546. __extends(VideoDome, _super);
  117547. /**
  117548. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  117549. * @param name Element's name, child elements will append suffixes for their own names.
  117550. * @param urlsOrVideo defines the url(s) or the video element to use
  117551. * @param options An object containing optional or exposed sub element properties
  117552. */
  117553. function VideoDome(name, urlsOrVideo, options, scene) {
  117554. var _this = _super.call(this, name, scene) || this;
  117555. _this._useDirectMapping = false;
  117556. // set defaults and manage values
  117557. name = name || "videoDome";
  117558. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  117559. options.clickToPlay = Boolean(options.clickToPlay);
  117560. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  117561. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  117562. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  117563. if (options.useDirectMapping === undefined) {
  117564. _this._useDirectMapping = true;
  117565. }
  117566. else {
  117567. _this._useDirectMapping = options.useDirectMapping;
  117568. }
  117569. _this._setReady(false);
  117570. // create
  117571. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  117572. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  117573. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  117574. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  117575. texture.onLoadObservable.addOnce(function () {
  117576. _this._setReady(true);
  117577. });
  117578. // configure material
  117579. material.useEquirectangularFOV = true;
  117580. material.fovMultiplier = 1.0;
  117581. material.opacityFresnel = false;
  117582. if (_this._useDirectMapping) {
  117583. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117584. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117585. material.diffuseTexture = texture;
  117586. }
  117587. else {
  117588. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  117589. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117590. material.reflectionTexture = texture;
  117591. }
  117592. // configure mesh
  117593. _this._mesh.material = material;
  117594. _this._mesh.parent = _this;
  117595. // optional configuration
  117596. if (options.clickToPlay) {
  117597. scene.onPointerUp = function () {
  117598. _this._videoTexture.video.play();
  117599. };
  117600. }
  117601. return _this;
  117602. }
  117603. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  117604. /**
  117605. * Gets the video texture being displayed on the sphere
  117606. */
  117607. get: function () {
  117608. return this._videoTexture;
  117609. },
  117610. enumerable: true,
  117611. configurable: true
  117612. });
  117613. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  117614. /**
  117615. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  117616. * Also see the options.resolution property.
  117617. */
  117618. get: function () {
  117619. return this._material.fovMultiplier;
  117620. },
  117621. set: function (value) {
  117622. this._material.fovMultiplier = value;
  117623. },
  117624. enumerable: true,
  117625. configurable: true
  117626. });
  117627. /**
  117628. * Releases resources associated with this node.
  117629. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  117630. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  117631. */
  117632. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  117633. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  117634. this._videoTexture.dispose();
  117635. this._mesh.dispose();
  117636. this._material.dispose();
  117637. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  117638. };
  117639. return VideoDome;
  117640. }(BABYLON.TransformNode));
  117641. BABYLON.VideoDome = VideoDome;
  117642. })(BABYLON || (BABYLON = {}));
  117643. //# sourceMappingURL=babylon.videoDome.js.map
  117644. var BABYLON;
  117645. (function (BABYLON) {
  117646. /**
  117647. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  117648. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  117649. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  117650. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  117651. */
  117652. var PhotoDome = /** @class */ (function (_super) {
  117653. __extends(PhotoDome, _super);
  117654. /**
  117655. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  117656. * @param name Element's name, child elements will append suffixes for their own names.
  117657. * @param urlsOfPhoto defines the url of the photo to display
  117658. * @param options defines an object containing optional or exposed sub element properties
  117659. * @param onError defines a callback called when an error occured while loading the texture
  117660. */
  117661. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  117662. if (onError === void 0) { onError = null; }
  117663. var _this = _super.call(this, name, scene) || this;
  117664. _this._useDirectMapping = false;
  117665. /**
  117666. * Observable raised when an error occured while loading the 360 image
  117667. */
  117668. _this.onLoadErrorObservable = new BABYLON.Observable();
  117669. // set defaults and manage values
  117670. name = name || "photoDome";
  117671. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  117672. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  117673. if (options.useDirectMapping === undefined) {
  117674. _this._useDirectMapping = true;
  117675. }
  117676. else {
  117677. _this._useDirectMapping = options.useDirectMapping;
  117678. }
  117679. _this._setReady(false);
  117680. // create
  117681. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  117682. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  117683. // configure material
  117684. material.opacityFresnel = false;
  117685. material.useEquirectangularFOV = true;
  117686. material.fovMultiplier = 1.0;
  117687. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  117688. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  117689. if (onError) {
  117690. onError(message, exception);
  117691. }
  117692. });
  117693. _this.photoTexture.onLoadObservable.addOnce(function () {
  117694. _this._setReady(true);
  117695. });
  117696. // configure mesh
  117697. _this._mesh.material = material;
  117698. _this._mesh.parent = _this;
  117699. return _this;
  117700. }
  117701. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  117702. /**
  117703. * Gets or sets the texture being displayed on the sphere
  117704. */
  117705. get: function () {
  117706. return this._photoTexture;
  117707. },
  117708. set: function (value) {
  117709. if (this._photoTexture === value) {
  117710. return;
  117711. }
  117712. this._photoTexture = value;
  117713. if (this._useDirectMapping) {
  117714. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117715. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117716. this._material.diffuseTexture = this._photoTexture;
  117717. }
  117718. else {
  117719. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  117720. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117721. this._material.reflectionTexture = this._photoTexture;
  117722. }
  117723. },
  117724. enumerable: true,
  117725. configurable: true
  117726. });
  117727. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  117728. /**
  117729. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  117730. * Also see the options.resolution property.
  117731. */
  117732. get: function () {
  117733. return this._material.fovMultiplier;
  117734. },
  117735. set: function (value) {
  117736. this._material.fovMultiplier = value;
  117737. },
  117738. enumerable: true,
  117739. configurable: true
  117740. });
  117741. /**
  117742. * Releases resources associated with this node.
  117743. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  117744. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  117745. */
  117746. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  117747. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  117748. this._photoTexture.dispose();
  117749. this._mesh.dispose();
  117750. this._material.dispose();
  117751. this.onLoadErrorObservable.clear();
  117752. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  117753. };
  117754. return PhotoDome;
  117755. }(BABYLON.TransformNode));
  117756. BABYLON.PhotoDome = PhotoDome;
  117757. })(BABYLON || (BABYLON = {}));
  117758. //# sourceMappingURL=babylon.photoDome.js.map
  117759. var BABYLON;
  117760. (function (BABYLON) {
  117761. /** @hidden */
  117762. var _OcclusionDataStorage = /** @class */ (function () {
  117763. function _OcclusionDataStorage() {
  117764. /** @hidden */
  117765. this.occlusionInternalRetryCounter = 0;
  117766. /** @hidden */
  117767. this.isOcclusionQueryInProgress = false;
  117768. /** @hidden */
  117769. this.isOccluded = false;
  117770. /** @hidden */
  117771. this.occlusionRetryCount = -1;
  117772. /** @hidden */
  117773. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  117774. /** @hidden */
  117775. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  117776. }
  117777. return _OcclusionDataStorage;
  117778. }());
  117779. BABYLON.Engine.prototype.createQuery = function () {
  117780. return this._gl.createQuery();
  117781. };
  117782. BABYLON.Engine.prototype.deleteQuery = function (query) {
  117783. this._gl.deleteQuery(query);
  117784. return this;
  117785. };
  117786. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  117787. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  117788. };
  117789. BABYLON.Engine.prototype.getQueryResult = function (query) {
  117790. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  117791. };
  117792. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  117793. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  117794. this._gl.beginQuery(glAlgorithm, query);
  117795. return this;
  117796. };
  117797. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  117798. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  117799. this._gl.endQuery(glAlgorithm);
  117800. return this;
  117801. };
  117802. BABYLON.Engine.prototype._createTimeQuery = function () {
  117803. var timerQuery = this.getCaps().timerQuery;
  117804. if (timerQuery.createQueryEXT) {
  117805. return timerQuery.createQueryEXT();
  117806. }
  117807. return this.createQuery();
  117808. };
  117809. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  117810. var timerQuery = this.getCaps().timerQuery;
  117811. if (timerQuery.deleteQueryEXT) {
  117812. timerQuery.deleteQueryEXT(query);
  117813. return;
  117814. }
  117815. this.deleteQuery(query);
  117816. };
  117817. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  117818. var timerQuery = this.getCaps().timerQuery;
  117819. if (timerQuery.getQueryObjectEXT) {
  117820. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  117821. }
  117822. return this.getQueryResult(query);
  117823. };
  117824. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  117825. var timerQuery = this.getCaps().timerQuery;
  117826. if (timerQuery.getQueryObjectEXT) {
  117827. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  117828. }
  117829. return this.isQueryResultAvailable(query);
  117830. };
  117831. BABYLON.Engine.prototype.startTimeQuery = function () {
  117832. var caps = this.getCaps();
  117833. var timerQuery = caps.timerQuery;
  117834. if (!timerQuery) {
  117835. return null;
  117836. }
  117837. var token = new BABYLON._TimeToken();
  117838. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  117839. if (caps.canUseTimestampForTimerQuery) {
  117840. token._startTimeQuery = this._createTimeQuery();
  117841. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  117842. }
  117843. else {
  117844. if (this._currentNonTimestampToken) {
  117845. return this._currentNonTimestampToken;
  117846. }
  117847. token._timeElapsedQuery = this._createTimeQuery();
  117848. if (timerQuery.beginQueryEXT) {
  117849. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  117850. }
  117851. else {
  117852. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  117853. }
  117854. this._currentNonTimestampToken = token;
  117855. }
  117856. return token;
  117857. };
  117858. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  117859. var caps = this.getCaps();
  117860. var timerQuery = caps.timerQuery;
  117861. if (!timerQuery || !token) {
  117862. return -1;
  117863. }
  117864. if (caps.canUseTimestampForTimerQuery) {
  117865. if (!token._startTimeQuery) {
  117866. return -1;
  117867. }
  117868. if (!token._endTimeQuery) {
  117869. token._endTimeQuery = this._createTimeQuery();
  117870. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  117871. }
  117872. }
  117873. else if (!token._timeElapsedQueryEnded) {
  117874. if (!token._timeElapsedQuery) {
  117875. return -1;
  117876. }
  117877. if (timerQuery.endQueryEXT) {
  117878. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  117879. }
  117880. else {
  117881. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  117882. }
  117883. token._timeElapsedQueryEnded = true;
  117884. }
  117885. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  117886. var available = false;
  117887. if (token._endTimeQuery) {
  117888. available = this._getTimeQueryAvailability(token._endTimeQuery);
  117889. }
  117890. else if (token._timeElapsedQuery) {
  117891. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  117892. }
  117893. if (available && !disjoint) {
  117894. var result = 0;
  117895. if (caps.canUseTimestampForTimerQuery) {
  117896. if (!token._startTimeQuery || !token._endTimeQuery) {
  117897. return -1;
  117898. }
  117899. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  117900. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  117901. result = timeEnd - timeStart;
  117902. this._deleteTimeQuery(token._startTimeQuery);
  117903. this._deleteTimeQuery(token._endTimeQuery);
  117904. token._startTimeQuery = null;
  117905. token._endTimeQuery = null;
  117906. }
  117907. else {
  117908. if (!token._timeElapsedQuery) {
  117909. return -1;
  117910. }
  117911. result = this._getTimeQueryResult(token._timeElapsedQuery);
  117912. this._deleteTimeQuery(token._timeElapsedQuery);
  117913. token._timeElapsedQuery = null;
  117914. token._timeElapsedQueryEnded = false;
  117915. this._currentNonTimestampToken = null;
  117916. }
  117917. return result;
  117918. }
  117919. return -1;
  117920. };
  117921. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  117922. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  117923. };
  117924. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  117925. get: function () {
  117926. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  117927. },
  117928. enumerable: false,
  117929. configurable: true
  117930. });
  117931. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  117932. get: function () {
  117933. if (!this.__occlusionDataStorage) {
  117934. this.__occlusionDataStorage = new _OcclusionDataStorage();
  117935. }
  117936. return this.__occlusionDataStorage;
  117937. },
  117938. enumerable: false,
  117939. configurable: true
  117940. });
  117941. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  117942. get: function () {
  117943. return this._occlusionDataStorage.isOccluded;
  117944. },
  117945. set: function (value) {
  117946. this._occlusionDataStorage.isOccluded = value;
  117947. },
  117948. enumerable: true,
  117949. configurable: true
  117950. });
  117951. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  117952. get: function () {
  117953. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  117954. },
  117955. set: function (value) {
  117956. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  117957. },
  117958. enumerable: true,
  117959. configurable: true
  117960. });
  117961. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  117962. get: function () {
  117963. return this._occlusionDataStorage.occlusionType;
  117964. },
  117965. set: function (value) {
  117966. this._occlusionDataStorage.occlusionType = value;
  117967. },
  117968. enumerable: true,
  117969. configurable: true
  117970. });
  117971. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  117972. get: function () {
  117973. return this._occlusionDataStorage.occlusionRetryCount;
  117974. },
  117975. set: function (value) {
  117976. this._occlusionDataStorage.occlusionRetryCount = value;
  117977. },
  117978. enumerable: true,
  117979. configurable: true
  117980. });
  117981. // We also need to update AbstractMesh as there is a portion of the code there
  117982. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  117983. var dataStorage = this._occlusionDataStorage;
  117984. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  117985. dataStorage.isOccluded = false;
  117986. return false;
  117987. }
  117988. var engine = this.getEngine();
  117989. if (engine.webGLVersion < 2) {
  117990. dataStorage.isOccluded = false;
  117991. return false;
  117992. }
  117993. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  117994. dataStorage.isOccluded = false;
  117995. return false;
  117996. }
  117997. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  117998. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  117999. if (isOcclusionQueryAvailable) {
  118000. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  118001. dataStorage.isOcclusionQueryInProgress = false;
  118002. dataStorage.occlusionInternalRetryCounter = 0;
  118003. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  118004. }
  118005. else {
  118006. dataStorage.occlusionInternalRetryCounter++;
  118007. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  118008. dataStorage.isOcclusionQueryInProgress = false;
  118009. dataStorage.occlusionInternalRetryCounter = 0;
  118010. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  118011. // if strict continue the last state of the object.
  118012. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  118013. }
  118014. else {
  118015. return false;
  118016. }
  118017. }
  118018. }
  118019. var scene = this.getScene();
  118020. if (scene.getBoundingBoxRenderer) {
  118021. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  118022. if (!this._occlusionQuery) {
  118023. this._occlusionQuery = engine.createQuery();
  118024. }
  118025. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  118026. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  118027. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  118028. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  118029. }
  118030. return dataStorage.isOccluded;
  118031. };
  118032. })(BABYLON || (BABYLON = {}));
  118033. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  118034. var BABYLON;
  118035. (function (BABYLON) {
  118036. /**
  118037. * Class used to generate noise procedural textures
  118038. */
  118039. var NoiseProceduralTexture = /** @class */ (function (_super) {
  118040. __extends(NoiseProceduralTexture, _super);
  118041. /**
  118042. * Creates a new NoiseProceduralTexture
  118043. * @param name defines the name fo the texture
  118044. * @param size defines the size of the texture (default is 256)
  118045. * @param scene defines the hosting scene
  118046. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  118047. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  118048. */
  118049. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  118050. if (size === void 0) { size = 256; }
  118051. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  118052. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  118053. _this._time = 0;
  118054. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  118055. _this.brightness = 0.2;
  118056. /** Defines the number of octaves to process */
  118057. _this.octaves = 3;
  118058. /** Defines the level of persistence (0.8 by default) */
  118059. _this.persistence = 0.8;
  118060. /** Gets or sets animation speed factor (default is 1) */
  118061. _this.animationSpeedFactor = 1;
  118062. _this.autoClear = false;
  118063. _this._updateShaderUniforms();
  118064. return _this;
  118065. }
  118066. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  118067. var scene = this.getScene();
  118068. if (!scene) {
  118069. return;
  118070. }
  118071. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  118072. this.setFloat("brightness", this.brightness);
  118073. this.setFloat("persistence", this.persistence);
  118074. this.setFloat("timeScale", this._time);
  118075. };
  118076. NoiseProceduralTexture.prototype._getDefines = function () {
  118077. return "#define OCTAVES " + (this.octaves | 0);
  118078. };
  118079. /** Generate the current state of the procedural texture */
  118080. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  118081. this._updateShaderUniforms();
  118082. _super.prototype.render.call(this, useCameraPostProcess);
  118083. };
  118084. /**
  118085. * Serializes this noise procedural texture
  118086. * @returns a serialized noise procedural texture object
  118087. */
  118088. NoiseProceduralTexture.prototype.serialize = function () {
  118089. var serializationObject = {};
  118090. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  118091. serializationObject.brightness = this.brightness;
  118092. serializationObject.octaves = this.octaves;
  118093. serializationObject.persistence = this.persistence;
  118094. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  118095. serializationObject.size = this.getSize().width;
  118096. serializationObject.generateMipMaps = this._generateMipMaps;
  118097. return serializationObject;
  118098. };
  118099. /**
  118100. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  118101. * @param parsedTexture defines parsed texture data
  118102. * @param scene defines the current scene
  118103. * @param rootUrl defines the root URL containing noise procedural texture information
  118104. * @returns a parsed NoiseProceduralTexture
  118105. */
  118106. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  118107. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  118108. texture.brightness = parsedTexture.brightness;
  118109. texture.octaves = parsedTexture.octaves;
  118110. texture.persistence = parsedTexture.persistence;
  118111. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  118112. return texture;
  118113. };
  118114. return NoiseProceduralTexture;
  118115. }(BABYLON.ProceduralTexture));
  118116. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  118117. })(BABYLON || (BABYLON = {}));
  118118. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  118119. var __assign = (this && this.__assign) || function () {
  118120. __assign = Object.assign || function(t) {
  118121. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118122. s = arguments[i];
  118123. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118124. t[p] = s[p];
  118125. }
  118126. return t;
  118127. };
  118128. return __assign.apply(this, arguments);
  118129. };
  118130. var BABYLON;
  118131. (function (BABYLON) {
  118132. /**
  118133. * This can helps recording videos from BabylonJS.
  118134. * This is based on the available WebRTC functionalities of the browser.
  118135. *
  118136. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  118137. */
  118138. var VideoRecorder = /** @class */ (function () {
  118139. /**
  118140. * Create a new VideoCapture object which can help converting what you see in Babylon to
  118141. * a video file.
  118142. * @param engine Defines the BabylonJS Engine you wish to record
  118143. * @param options Defines options that can be used to customized the capture
  118144. */
  118145. function VideoRecorder(engine, options) {
  118146. if (options === void 0) { options = null; }
  118147. if (!VideoRecorder.IsSupported(engine)) {
  118148. throw "Your browser does not support recording so far.";
  118149. }
  118150. var canvas = engine.getRenderingCanvas();
  118151. if (!canvas) {
  118152. throw "The babylon engine must have a canvas to be recorded";
  118153. }
  118154. this._canvas = canvas;
  118155. this._canvas.isRecording = false;
  118156. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  118157. var stream = this._canvas.captureStream(this._options.fps);
  118158. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  118159. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  118160. this._mediaRecorder.onerror = this._handleError.bind(this);
  118161. this._mediaRecorder.onstop = this._handleStop.bind(this);
  118162. }
  118163. /**
  118164. * Returns wehther or not the VideoRecorder is available in your browser.
  118165. * @param engine Defines the Babylon Engine to check the support for
  118166. * @returns true if supported otherwise false
  118167. */
  118168. VideoRecorder.IsSupported = function (engine) {
  118169. var canvas = engine.getRenderingCanvas();
  118170. return (!!canvas && typeof canvas.captureStream === "function");
  118171. };
  118172. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  118173. /**
  118174. * True wether a recording is already in progress.
  118175. */
  118176. get: function () {
  118177. return !!this._canvas && this._canvas.isRecording;
  118178. },
  118179. enumerable: true,
  118180. configurable: true
  118181. });
  118182. /**
  118183. * Stops the current recording before the default capture timeout passed in the startRecording
  118184. * functions.
  118185. */
  118186. VideoRecorder.prototype.stopRecording = function () {
  118187. if (!this._canvas || !this._mediaRecorder) {
  118188. return;
  118189. }
  118190. if (!this.isRecording) {
  118191. return;
  118192. }
  118193. this._canvas.isRecording = false;
  118194. this._mediaRecorder.stop();
  118195. };
  118196. /**
  118197. * Starts recording the canvas for a max duration specified in parameters.
  118198. * @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.
  118199. * @param maxDuration Defines the maximum recording time in seconds.
  118200. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  118201. * @return a promise callback at the end of the recording with the video data in Blob.
  118202. */
  118203. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  118204. var _this = this;
  118205. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  118206. if (maxDuration === void 0) { maxDuration = 7; }
  118207. if (!this._canvas || !this._mediaRecorder) {
  118208. throw "Recorder has already been disposed";
  118209. }
  118210. if (this.isRecording) {
  118211. throw "Recording already in progress";
  118212. }
  118213. if (maxDuration > 0) {
  118214. setTimeout(function () {
  118215. _this.stopRecording();
  118216. }, maxDuration * 1000);
  118217. }
  118218. this._fileName = fileName;
  118219. this._recordedChunks = [];
  118220. this._resolve = null;
  118221. this._reject = null;
  118222. this._canvas.isRecording = true;
  118223. this._mediaRecorder.start(this._options.recordChunckSize);
  118224. return new Promise(function (resolve, reject) {
  118225. _this._resolve = resolve;
  118226. _this._reject = reject;
  118227. });
  118228. };
  118229. /**
  118230. * Releases internal resources used during the recording.
  118231. */
  118232. VideoRecorder.prototype.dispose = function () {
  118233. this._canvas = null;
  118234. this._mediaRecorder = null;
  118235. this._recordedChunks = [];
  118236. this._fileName = null;
  118237. this._resolve = null;
  118238. this._reject = null;
  118239. };
  118240. VideoRecorder.prototype._handleDataAvailable = function (event) {
  118241. if (event.data.size > 0) {
  118242. this._recordedChunks.push(event.data);
  118243. }
  118244. };
  118245. VideoRecorder.prototype._handleError = function (event) {
  118246. this.stopRecording();
  118247. if (this._reject) {
  118248. this._reject(event.error);
  118249. }
  118250. else {
  118251. throw new event.error();
  118252. }
  118253. };
  118254. VideoRecorder.prototype._handleStop = function () {
  118255. this.stopRecording();
  118256. var superBuffer = new Blob(this._recordedChunks);
  118257. if (this._resolve) {
  118258. this._resolve(superBuffer);
  118259. }
  118260. window.URL.createObjectURL(superBuffer);
  118261. if (this._fileName) {
  118262. BABYLON.Tools.Download(superBuffer, this._fileName);
  118263. }
  118264. };
  118265. VideoRecorder._defaultOptions = {
  118266. mimeType: "video/webm",
  118267. fps: 25,
  118268. recordChunckSize: 3000
  118269. };
  118270. return VideoRecorder;
  118271. }());
  118272. BABYLON.VideoRecorder = VideoRecorder;
  118273. })(BABYLON || (BABYLON = {}));
  118274. //# sourceMappingURL=babylon.videoRecorder.js.map
  118275. var BABYLON;
  118276. (function (BABYLON) {
  118277. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  118278. if (replace === void 0) { replace = false; }
  118279. // Dispose existing light in replace mode.
  118280. if (replace) {
  118281. if (this.lights) {
  118282. for (var i = 0; i < this.lights.length; i++) {
  118283. this.lights[i].dispose();
  118284. }
  118285. }
  118286. }
  118287. // Light
  118288. if (this.lights.length === 0) {
  118289. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  118290. }
  118291. };
  118292. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  118293. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118294. if (replace === void 0) { replace = false; }
  118295. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118296. // Dispose existing camera in replace mode.
  118297. if (replace) {
  118298. if (this.activeCamera) {
  118299. this.activeCamera.dispose();
  118300. this.activeCamera = null;
  118301. }
  118302. }
  118303. // Camera
  118304. if (!this.activeCamera) {
  118305. var worldExtends = this.getWorldExtends();
  118306. var worldSize = worldExtends.max.subtract(worldExtends.min);
  118307. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  118308. var camera;
  118309. var radius = worldSize.length() * 1.5;
  118310. // empty scene scenario!
  118311. if (!isFinite(radius)) {
  118312. radius = 1;
  118313. worldCenter.copyFromFloats(0, 0, 0);
  118314. }
  118315. if (createArcRotateCamera) {
  118316. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  118317. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  118318. arcRotateCamera.wheelPrecision = 100 / radius;
  118319. camera = arcRotateCamera;
  118320. }
  118321. else {
  118322. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  118323. freeCamera.setTarget(worldCenter);
  118324. camera = freeCamera;
  118325. }
  118326. camera.minZ = radius * 0.01;
  118327. camera.maxZ = radius * 1000;
  118328. camera.speed = radius * 0.2;
  118329. this.activeCamera = camera;
  118330. var canvas = this.getEngine().getRenderingCanvas();
  118331. if (attachCameraControls && canvas) {
  118332. camera.attachControl(canvas);
  118333. }
  118334. }
  118335. };
  118336. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  118337. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118338. if (replace === void 0) { replace = false; }
  118339. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118340. this.createDefaultLight(replace);
  118341. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  118342. };
  118343. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  118344. if (pbr === void 0) { pbr = false; }
  118345. if (scale === void 0) { scale = 1000; }
  118346. if (blur === void 0) { blur = 0; }
  118347. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  118348. if (!environmentTexture) {
  118349. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  118350. return null;
  118351. }
  118352. if (setGlobalEnvTexture) {
  118353. if (environmentTexture) {
  118354. this.environmentTexture = environmentTexture;
  118355. }
  118356. }
  118357. // Skybox
  118358. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  118359. if (pbr) {
  118360. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  118361. hdrSkyboxMaterial.backFaceCulling = false;
  118362. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  118363. if (hdrSkyboxMaterial.reflectionTexture) {
  118364. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118365. }
  118366. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  118367. hdrSkyboxMaterial.disableLighting = true;
  118368. hdrSkyboxMaterial.twoSidedLighting = true;
  118369. hdrSkybox.infiniteDistance = true;
  118370. hdrSkybox.material = hdrSkyboxMaterial;
  118371. }
  118372. else {
  118373. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  118374. skyboxMaterial.backFaceCulling = false;
  118375. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  118376. if (skyboxMaterial.reflectionTexture) {
  118377. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118378. }
  118379. skyboxMaterial.disableLighting = true;
  118380. hdrSkybox.infiniteDistance = true;
  118381. hdrSkybox.material = skyboxMaterial;
  118382. }
  118383. return hdrSkybox;
  118384. };
  118385. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  118386. if (BABYLON.EnvironmentHelper) {
  118387. return new BABYLON.EnvironmentHelper(options, this);
  118388. }
  118389. return null;
  118390. };
  118391. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  118392. if (webVROptions === void 0) { webVROptions = {}; }
  118393. return new BABYLON.VRExperienceHelper(this, webVROptions);
  118394. };
  118395. })(BABYLON || (BABYLON = {}));
  118396. //# sourceMappingURL=babylon.sceneHelpers.js.map
  118397. 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\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\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\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\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 VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\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[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,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}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\n\ngl_FragColor=result/float(samplesCount);\n}\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"};
  118398. 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};"};